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

北战南征 提交于 2019-12-12 18:42:42

问题


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


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




回答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 ****/
?>


来源:https://stackoverflow.com/questions/2742654/using-php-download-file-from-a-given-url-by-passing-username-and-password-for-ht

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!