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

}

No comments:

Post a Comment