using php Download File From a given URL by passing username and password for http authentication

12,191

Solution 1

The easiest way probably will be using http://username:password@host/path/file with fopen (if url wrappers are enabled), but if you don't like that I would use curl. Not tested, but it should probably be something like :

$out = fopen($localfilename, 'wb');
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_exec($ch);
curl_close($ch);
fclose($out);

$localfilename should contain the local file you want to write to, username:password have to be replaced with the actual username and password used for basic authentication, separated by a column (:).

Solution 2

Here is the simplest way to download a file using cURL method with HTTP authentication

<?php
/*** DOWNLOAD FILE FROM CURL ****/

//API KEY AND PASSWORD
$username='user';
$password='pass';
$usernamePassword = $username . ':' . $password;
$headers = array('Authorization: Basic ' . base64_encode($usernamePassword), 'Content-Type: application/json');

//URL
$url= 'https://yoururl.com';

//FILE NAME
$filename = 'my_file.pdf';

//DOWNLOAD PATH
$path = 'downloads/'.$filename;

//FOLDER PATH
$fp = fopen($path, 'w');

//SETTING UP CURL REQUEST
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);

//CONNECTION CLOSE
curl_close($ch);
fclose($fp);


//DOWNLOAD PDF LINK
echo '<div id="download-pdf"> <a href="'.$path.'" download>DOWNLOAD AS PDF</a></div>';

/*** DOWNLOAD FILE FROM CURL ****/
?>
Share:
12,191
phpian
Author by

phpian

Updated on June 28, 2022

Comments

  • phpian
    phpian almost 2 years

    I need to download a text file using php code. The file is having http authentication. What procedure I should use for this. Should I use fsocketopen or curl or Is there any other way to do this?

    I am using fsocketopen but it does not seem to work.

    $fp=fsockopen("www.example.com",80,$errno,$errorstr);
    
    $out = "GET abcdata/feed.txt HTTP/1.1\r\n";
    
    $out .= "User: xyz \r\n";
    
    $out .= "Password: xyz \r\n\r\n";
    fwrite($fp, $out);
    
    while(!feof($fp))
    {
    
     echo fgets($fp,1024);
    
    }
    
    fclose($fp);
    

    Here fgets is returning false.

    Any help!!!