<?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);
}
Zahid Ali Keerio (PHP Developer)
I’m an experienced, dedicated and ambitious Programmer looking for a challenging career as a Web Developer with the opportunity to work with the latest technologies on challenging and diverse projects.
Thursday, September 14, 2023
Download Multiple Files from Array of Links using PHP 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_PATHif [ ! -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"
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:
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 "{}"