php*_*ian 2 php curl fsockopen
我需要使用php代码下载文本文件.该文件具有http身份验证.我应该用什么程序来做这件事.我应该使用fsocketopen或卷曲还是有其他方法可以做到这一点?
我正在使用fsocketopen但它似乎不起作用.
$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);
Run Code Online (Sandbox Code Playgroud)
这fgets是假的.
任何帮助!!!
最简单的方法可能是使用http:// username:password @ host/path/file with fopen(如果启用了url包装器),但如果你不喜欢,我会使用curl.没有经过测试,但应该是这样的:
$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);
Run Code Online (Sandbox Code Playgroud)
$ localfilename应该包含要写入的本地文件,username:password必须替换为用于基本身份验证的实际用户名和密码,用列(:)分隔.