Skip to content
Related Articles

Related Articles

Download file from URL using PHP
  • Difficulty Level : Hard
  • Last Updated : 07 May, 2019
GeeksforGeeks - Summer Carnival Banner

There are many approaches to download a file from a URL some of them are discussed below:

Method 1: Using file_get_contents() function: The file_get_contents() function is used to read a file into a string. This function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.

Syntax:

file_get_contents($path, $include_path, $context, $start, $max_length)

Program 1:




<?php
  
// Initialize a file URL to the variable
  
// Use basename() function to return the base name of file 
$file_name = basename($url);
   
// Use file_get_contents() function to get the file
// from url and use file_put_contents() function to
// save the file by using base name
if(file_put_contents( $file_name,file_get_contents($url))) {
    echo "File downloaded successfully";
}
else {
    echo "File downloading failed.";
}
  
?>

Output:
Before run the program:

After run the program:



Method 2: Using PHP Curl: The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl.

Steps to download file:

  • Initialize a file URL to the variable
  • Create cURL session
  • Declare a variable and store the directory name where downloaded file will save.
  • Use basename() function to return the file base name if the file path is provided as a parameter.
  • Save the file to the given location.
  • Open the saved file location in write string mode
  • Set the option for cURL transfer
  • Perform cURL session and close cURL session and free all resources
  • Close the file

Example:




<?php
  
// Initialize a file URL to the variable
  
// Initialize the cURL session
$ch = curl_init($url);
  
// Inintialize directory name where
// file will be save
$dir = './';
  
// Use basename() function to return
// the base name of file 
$file_name = basename($url);
  
// Save file into file location
$save_file_loc = $dir . $file_name;
  
// Open file 
$fp = fopen($save_file_loc, 'wb');
  
// It set an option for a cURL transfer
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
  
// Perform a cURL session
curl_exec($ch);
  
// Closes a cURL session and frees all resources
curl_close($ch);
  
// Close file
fclose($fp);
  
?>

Output:
Before run the program:

After run the program:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :