Pages

Thursday, September 14, 2023

Download Multiple Files from Array of Links using PHP CURL

 <?php


// List of URLs to download

$urls = [

    'https://example.com/file1.zip',

    'https://example.com/file2.pdf',

    'https://example.com/file3.txt',

]


// Destination directory to save the downloaded files

$destinationDir = 'downloads/';

$directory = 'downloads/';

foreach (glob($directory . "*.mp3") as $filename) {

    $file = realpath($filename);

    $newFilename = urldecode($file);

    if ($newFilename !== $file) {

        rename($file, $newFilename);

        echo 'Renamed ' . $file . ' to ' . $newFilename . PHP_EOL;

    }

}

// Create the destination directory if it doesn't exist

if (!is_dir($destinationDir)) {

    mkdir($destinationDir, 0777, true);

}


// Iterate over each URL and download the file

foreach ($urls as $url) {

    // Extract the filename from the URL

    $filename = basename($url);


    // Encode the filename to handle special characters

    $encodedFilename = urlencode($filename);


    // Set the destination path for the downloaded file

    $destinationPath = $destinationDir . $encodedFilename;


    // Initialize cURL session

    $curl = curl_init($url);


    // Set the option to return the response as a string

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);


    // Execute the cURL session and store the response

    $response = curl_exec($curl);


    // Check if any error occurred during the request

    if (curl_errno($curl)) {

        echo 'Error downloading ' . $url . ': ' . curl_error($curl) . PHP_EOL;

    } else {

        // Save the response to the destination file

        file_put_contents($destinationPath, $response);

        echo 'Downloaded ' . $url . ' to ' . $destinationPath . PHP_EOL;

    }

    // Close the cURL session

    curl_close($curl);

}

show time in human difference time in custom php function

function time_elapsed_string($datetime, $full = false) {

            $now = new DateTime;

            $ago = new DateTime($datetime);

            $diff = $now->diff($ago);

            $diff->w = floor($diff->d / 7);
            $diff->d -= $diff->w * 7;

            $string = array(

                'y' => 'year',

                'm' => 'month',

                'w' => 'week',

                'd' => 'day',

                'h' => 'hour',

                'i' => 'minute',

                's' => 'second',

            );

            foreach ($string as $k => &$v) {

                if ($diff->$k) {

                    $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');

                } else {

                    unset($string[$k]);

                }

            }

            if (!$full) $string = array_slice($string, 0, 1);

            return $string ? implode(', ', $string) . ' ago' : 'just now';

        }

// show time in human difference time in custom php function

<?php echo  time_elapsed_string($key['date_created'], true); ?>

Tuesday, May 9, 2023

How to exclude databases while importing a MySQL backup file

Introduction:

If you need to import a MySQL backup file that contains multiple databases, you may want to exclude some of the existing databases from being overwritten. In this tutorial, we will show you how to exclude specific databases while importing a MySQL backup file using a bash script.

Prerequisites:

Basic knowledge of bash scripting

Access to a command-line interface

A MySQL database backup file (.sql extension)

Steps:

1. Create a new bash script file and open it using a text editor of your choice.

2. Add the following code to the file:

bash
#!/bin/bash 
echo "Enter MySQL username: "
read -s USERNAME
echo "Enter MySQL password: "
read -s PASSWORD
echo "Enter MySQL host (default: localhost): "
read HOST 
if [ -z "$HOST" ]; 
  then HOST="localhost"
fi 
echo "Enter path to backup file (e.g. /path/to/backup.sql): "
read BACKUP_PATH
if [ ! -f "$BACKUP_PATH" ];
then
  echo "File not found: $BACKUP_PATH"
  exit 1
fi 
 DATABASES=$(mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|mysql|mytinerycms|performance_schema|sys)")

for
db in $DATABASES
do
 DB_ARGS+=(
"--database" "$db")
done 
 mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" "${DB_ARGS[@]}" < "$BACKUP_PATH"

3. Save the file with a name such as mysql-import.sh.
4. Open a terminal or command prompt and navigate to the directory where you saved the script.
5. Make the script executable by running the following command:

chmod +x mysql-import.sh

7. When prompted, enter your MySQL username and password. If your MySQL server is running on a different host than localhost, enter the hostname as well.
8. Enter the path to the backup file when prompted.
9. The script will exclude the following databases from the import: information_schema, mysql, mytinerycms, performance_schema, sys. All other databases will be included.
10. The script will import the backup file to the specified MySQL server.

Conclusion:
In this tutorial, we showed you how to exclude specific databases while importing a MySQL backup file using a bash script. By modifying the script, you can exclude any database from the import by adding its name to the exclusion list. This is a simple and effective way to prevent overwriting existing databases while importing backups.








Saturday, December 31, 2022

Laravel .htacess for setting root as working directory

 <IfModule mod_rewrite.c>

RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

React app build .htaccess for live server

 <IfModule mod_rewrite.c>


  RewriteEngine On

  RewriteBase /

  RewriteRule ^index\.html$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f

  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteCond %{REQUEST_FILENAME} !-l

  RewriteRule . /index.html [L]


</IfModule>

Friday, November 5, 2021

Update User password in firebase and update data in firebase table

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>

<!--   TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries   -->

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-analytics.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-auth.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-database.js"></script>


<scipt>

const firebaseConfig = {

    apiKey: "APIKEY",

    authDomain: "my-project-ID.firebaseapp.com",

    projectId: "my-project-ID",

    storageBucket: "my-project-ID.appspot.com",

    messagingSenderId: "messagingSenderID",

    appId: "1:APIID",

    measurementId: "MEASUREMENT-ID",

    databaseURL: "https://my-project-ID-default-rtdb.firebaseio.com/",

  };

</scipt>


<script>

var New_Password = "test123";

const user = firebase.auth().currentUser;

              user.updatePassword(New_Password).then(() => {

                alert("successfully updated password");

              }).catch(function (error) {

                alert("failed"+ error.message);

              }); 

/********** UPDATE USER DATA ***********/

$("#updateUserData").on('click', function (e) {

  e.preventDefault();

  var firstName = $("#First-Name-Account").val();

  var lastName = $("#Last-Name-Account").val();

  var emailAddress = $("#Email-Account").val();

  var phoneNumber = $("#Phone-Account").val();

  

  let userRef = database.ref('users/' + userId);

  userRef.child(userId).set({

    "firstName": firstName,

    'lastName': lastName,

    'emailAddress': emailAddress,

    'phoneNumber': phoneNumber

  }).then(function() {

    errors = "Profile updated successfully";

    alert(errors);

    // Data saved successfully!

  })

  .catch(function(error) {

    // The write failed...

    errors = error.message;

    alert(errors);

  });

});

</script>

Friday, July 16, 2021

Find and delete all files from current and recursive directory in Linux

https://www.cyberciti.biz/faq/linux-unix-how-to-find-and-remove-files/

find . -type f -name "*youfilename" -print0 | xargs -I {} -0 rm -v "{}"

 

find . -type f -name "*.zip" -print0 | xargs -I {} -0 rm -v "{}"