PHP: Download file using file_get_contents.

This is a PHP tutorial on how to download a file from a remote server using file_get_contents. In this tutorial, we will download the file using file_get_contents and save it using file_put_contents.

Take a look at the following example:

//The URL of the file that you want to download.
$url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

//Download the file using file_get_contents.
$downloadedFileContents = file_get_contents($url);

//Check to see if file_get_contents failed.
if($downloadedFileContents === false){
    throw new Exception('Failed to download file at: ' . $url);
}

//The path and filename that you want to save the file to.
$fileName = 'logo.png';

//Save the data using file_put_contents.
$save = file_put_contents($fileName, $downloadedFileContents);

//Check to see if it failed to save or not.
if($save === false){
    throw new Exception('Failed to save file to: ' , $fileName);
}

In the code above, I am downloading a remote image and saving it as a local file on my server. To do this:

  1. We specified the full HTTP URL of the file that we want to download.
  2. Using PHP’s file_get_contents function, we downloaded the file. Note that this function will read the entire file into a string.
  3. After that, we checked to see if file_get_contents had failed by checking its return value. If its return value is a boolean FALSE value, then the function has failed to download the file.
  4. We specified the path and filename that we want to save this file to. In this case, it will be saved in the same directory as the script that is making the call. If you want to save it to a different folder, then you should specify the full path in the $fileName variable.
  5. We saved the data that we downloaded to the file path in question by using PHP’s file_put_contents function.
  6. Finally, we checked to see if the download was successful or not.

allow_url_fopen

If PHP’s allow_url_fopen directive is set to “0”, then the code above will fail. This is because the file_get_contents function requires allow_url_fopen to be set to “1” in order to be able to access URL objects.

If you are unable or unwilling to change this directive, then you should check out my guide on downloading files with cURL.

Hopefully, this post was of help to you! Happy downloading!