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

phpian picture phpian · Apr 30, 2010 · Viewed 11.2k times · Source

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!!!

Answer

wimvds picture wimvds · Apr 30, 2010

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 (:).