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); ?>