You are here: Home / Topics / How to Download file from URL using PHP

How to Download file from URL using PHP

Filed under: PHP on 2023-07-02 21:07:35

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://www.mcqbuddy.com/img/user.jpg.'; 
   
 // 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.


About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.