问题描述
我需要使用php代码下载文本文件。该文件具有http身份验证。我应该为此使用什么程序。我应该使用 fsocketopen
还是curl或还有其他方法吗?
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?
我正在使用fsocketopen但它似乎不起作用。
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);
此处 fgets
返回false。
任何帮助!
推荐答案
最简单的方法可能是使用与fopen(如果启用了URL包装器),但如果您不喜欢,我会使用curl。未经测试,但可能应该是这样的:
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应该包含要写入的本地文件,username:password必须替换为用于基本身份验证的实际用户名和密码,用一列(:)分隔。
$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 (:).
这篇关于使用php通过传递用于HTTP身份验证的用户名和密码从给定的URL下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!