LX DevBlog

About

Download file by URL

11/25/2022
PHP

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

    1. Using “file_get_contents()”
    2. Using “curl”

    <?php
      
        // Initialize a file URL to the variable
        $url = 
        'https://www.myserver.com/uploads/gfg-40.png';
          
        // 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.";
        }
    ?>

    <?php
      // Initialize a file URL to the variable
      $url = 
      'https://www.myserver.com/uploads/gfg-40.png';
      
      // 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);
    ?>