简体   繁体   English

PHP的fopen()无法获取url,但是curl可以

[英]PHP's fopen() can't get url, but curl can

A while back, I wrote a little utility function that takes inPath and outPath, opens both and copies from one to the other using fread() and fwrite(). 前一阵子,我写了一个小实用程序函数,它使用inPath和outPath,将两者打开并使用fread()和fwrite()相互复制。 allow_url_fopen is enabled. allow_url_fopen已启用。

Well, I've got a url that I'm trying to get the contents of, and fopen() doesn't get any data, but if I use curl to do the same, it works. 好吧,我有一个要获取其内容的URL,而fopen()却没有任何数据,但是如果我使用curl来执行此操作,它将起作用。

The url in question is: http://www.deltagroup.com/Feeds/images.php?lid=116582497&id=1 有问题的网址是: http : //www.deltagroup.com/Feeds/images.php? lid=116582497& id=1

fopen version: 开放版本:

$in  = @fopen( $inPath, "rb" );
$out = @fopen( $outPath, "wb" );

if( !$in || !$out )
{
    echo 0;
}

while( $chunk = fread( $in, 8192 ) )
{
    fwrite( $out, $chunk, 8192 );
}

fclose( $in );
fclose( $out );

if( file_exists($outPath) )
{
    echo 1;
}
else
{
    echo 0;
}

curl version: 卷曲版本:

$opt = "curl -o " . $outPath . " " . $inPath;
$res = `$opt`;

if( file_exists($outPath) )
{
    echo 1;
}
else
{
    echo 0;
}

Any idea why this would happen? 知道为什么会这样吗?

Even using php's curl, I was unable to download the file- until I added a curlopt_useragent string. 即使使用php的curl,我也无法下载文件-直到添加了curlopt_useragent字符串。 Nothing in the response indicated that it was required (no errors, nothing other than an HTTP 200). 响应中没有任何内容表明它是必需的(没有错误,只有HTTP 200)。

Final code: 最终代码:

$out = @fopen( $outPath, "wb" );

if( !$out )
{
    echo 0;
}

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $inPath );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_FILE, $out );
curl_setopt( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 15 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 18000 );
$data = curl_exec( $ch );
curl_close( $ch );
fclose( $out );

if( file_exists($outPath) )
{
    echo 1;
}
else
{
    echo 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM