How to Download file from URL using PHP
In this tutorial, we are going to see how to download file from URL using PHP. There are several approaches to download a file from a URL. Some of them are described below:
Using file_get_contents() function:
file_get_contents() function is used to read a file into a string. This feature uses memory mapping techniques supported by the server and thus improves performance, making it a preferred way to read the contents of a file.
<?php
$url = 'https://stackhowto.com/wp-content/uploads/2020/11/cropped-stackhowto.png';
// Use the basename function to return the name of the file.
$file_name = basename($url);
/* Use file_get_contents() function to get the file from the url and
use file_put_contents() function to save the file */
if(file_put_contents( $file,file_get_contents($url))) {
echo "File downloaded successfully.";
}
else {
echo "File download failed.";
}
?>
Output:
File downloaded successfully.
Using PHP Curl:
<?php $url = 'https://stackhowto.com/wp-content/uploads/2020/11/cropped-stackhowto.png'; // Initialize the cURL session $session = curl_init($url); // Initialize the directory name where the file will be saved $dir = './'; $file_name = basename($url); // Save file $save = $dir . $file; // Open file $file = fopen($save, 'wb'); // defines the options for the transfer curl_setopt($session, CURLOPT_FILE, $file); curl_setopt($session, CURLOPT_HEADER, 0); curl_exec($session); curl_close($session); fclose($file); ?>




