Download file from URL using PHP - GeeksforGeeks (2024)

Improve

In this article, we will see how to download & save the file from the URL in PHP, & will also understand the different ways to implement it through the examples. There are many approaches to download a file from a URL, some of them are discussed below:

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 that are supported by the server and thus enhances the performance making it a preferred way of reading the contents of a file.

Syntax:

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

Example 1: This example illustrates the use of file_get_contents() function to read the file into a string.

PHP

<?php

// Initialize a file URL to the variable

$url =

// 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 running the program:

Download file from URL using PHP - GeeksforGeeks (1)

php source folder

After running the program:

Download file from URL using PHP - GeeksforGeeks (2)

File downloaded after successful execution

Download file from URL using PHP - GeeksforGeeks (3)

Downloaded image file

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 the file:

  • Initialize a file URL to the variable.
  • Create cURL session.
  • Declare a variable and store the directory name where the downloaded file will save.
  • Use the basename() function to return the file basename 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: This example illustrates the use of the PHP Curl to make HTTP requests in PHP, in order to download the file.

PHP

<?php

// Initialize a file URL to the variable

$url =

// Initialize the cURL session

$ch = curl_init($url);

// Initialize 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 running the program:

Download file from URL using PHP - GeeksforGeeks (4)

php source folder

After running the program:

Download file from URL using PHP - GeeksforGeeks (5)

Downloaded image file

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Last Updated : 17 Jan, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment...

Download file from URL using PHP - GeeksforGeeks (2024)

FAQs

How to download file from URL in PHP? ›

Steps to download the file:
  1. Initialize a file URL to the variable.
  2. Create cURL session.
  3. Declare a variable and store the directory name where the downloaded file will save.
  4. Use the basename() function to return the file basename if the file path is provided as a parameter.
  5. Save the file to the given location.
Jan 17, 2022

How to get PHP file content from URL? ›

To get the contents of a file from a URL in PHP, you can use the file_get_contents function. This function reads data from a file or URL, and returns it as a string.

How to download file from API response in PHP? ›

Here's the snippet that tries to download the file:
  1. $ch = curl_init($fileURL);
  2. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  4. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //follow redirects.
  5. curl_setopt ($ch, CURLOPT_HTTPHEADER, array ( 'Authorization: Bearer '.
Feb 14, 2020

How to download an image from a URL and save it in PHP? ›

Using file_get_contents() and file_put_contents() is a straightforward method to save an image from a URL in PHP. $url = "https://example.com/image.jpg"; $image = file_get_contents($url); file_put_contents("path/to/save/image.

How do I download a file directly from a URL? ›

How to Download File from URL Online?
  1. Copy the URL of the file you want to download.
  2. Paste the URL into the input field on our webpage.
  3. Click on the 'Download' button.
  4. Wait for a few moments while our tool processes the file.
  5. Once the file is ready, click on the 'Download File' button to save it to your device.

How to download file from URL using command line? ›

Download File Using CMD Windows 11, 10 and 7
  1. curl <URL>
  2. curl http://example.com/file.zip.
  3. curl <URL> -o <output_filename>
  4. curl http://example.com/file.zip -o downloaded_file.zip.
  5. wget <URL>
  6. wget http://example.com/file.zip.
Dec 10, 2023

How to get the content of a PHP file in PHP? ›

What is `file_get_contents()`? The `file_get_contents()` function in PHP is a simple and efficient way to read a file's contents as a string. It can read local and remote files, such as HTML pages or JSON data, making it a versatile option for developers.

How to download file on button click in PHP? ›

How to automatically start a download in PHP ?
  1. Creating a download button:
  2. Output:
  3. Output:
  4. PHP code to download: When the user clicks the above button, the code will be redirected to the “downloadFile. php” file. Now, use the URL of the file and PHP file_get_contents() function to download the file.
  5. Output:
Sep 14, 2020

How to access data sent through URL with POST method in PHP? ›

In PHP, we can use the $_POST method as a superglobal variable that is operated to manage form data. After we click on submit button and the page will send the data through the post method. We can use the data after storing it in a variable according to our requirements.

Can we download PHP file from server? ›

6 Answers. If the server is configured correctly, you cannot download a PHP file. It will be executed when called via the webserver. The only way to see what it does is to gain access to the server via SSH or FTP or some other method.

How to create a text file and download in PHP? ›

$file = fopen("test. txt", "w") or die("Unable to open file!"); fwrite($file, "lorem ipsum"); fclose($file); header("Content-Disposition: attachment; filename=\"" . basename($file) .

How to make a PDF file downloadable in HTML link using PHP? ›

  1. HTML code: <! DOCTYPE html> < html > < head > < title >Download PDF using PHP from HTML Link</ title > </ head > < body > < center > ...
  2. PHP code: <? php. header( "Content-Type: application/octet-stream" ); $file = $_GET [ "file" ] . ". pdf" ; header( "Content-Disposition: attachment; filename=" . ...
  3. Output:
Aug 1, 2021

How to download any file using PHP? ›

PHP Download File
  1. Syntax.
  2. $filename: represents the file name.
  3. $use_include_path: it is the optional parameter. It is by default false. You can set it to true to the search the file in the included_path.
  4. $context: represents the context stream resource.
  5. int: it returns the number of bytes read from the file.

How to save file using PHP? ›

PHP code: saving a file with fopen / fwrite

'myfile1. txt'; $fp = fopen($file, "w") or die("Couldn't open $file for writing!"); fwrite($fp, $data) or die("Couldn't write values to file!"); fclose($fp); echo "Saved to $file successfully!"; ?>

How to download an image file in PHP? ›

Saving an Image from URL in PHP
  1. Declaring two variables named as $url and $img, representing the source URL and destination file respectively.
  2. Use file_put_contents() function to write a string to a file that takes two arguments. ...
  3. Use file_get_contents() function to read a file into a string.
Jul 31, 2021

How to download PDF from link in PHP? ›

  1. HTML code: <! DOCTYPE html> < html > < head > < title >Download PDF using PHP from HTML Link</ title > </ head > < body > < center > ...
  2. PHP code: <? php. header( "Content-Type: application/octet-stream" ); $file = $_GET [ "file" ] . ". pdf" ; header( "Content-Disposition: attachment; filename=" . ...
  3. Output:
Aug 1, 2021

How to download a file from database in PHP? ›

php $name= $_GET['nama']; download($name); function download($name) { $file = $nama_fail; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.

How to download and upload file in PHP? ›

PHP File Upload
  1. Configure The "php.ini" File. First, ensure that PHP is configured to allow file uploads. ...
  2. Check if File Already Exists. Now we can add some restrictions. ...
  3. Limit File Size. The file input field in our HTML form above is named "fileToUpload". ...
  4. Limit File Type. ...
  5. Complete Upload File PHP Script.

Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6098

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.