cURL 文件下载适用于 PHP 5.3 而不是 5.5


cURL file download works on PHP 5.3 not on 5.5

>我有两台服务器在不同的软件版本中运行类似的Web应用程序。

两台服务器都运行 CentOS 6.5

一个有Apache 2.2 php 5.3

另一个运行Apache 2.4 php 5.5

此应用程序的主要功能之一是定期从远程URL下载CSV文件

这是使用 cURL 和以下代码完成的:

$filename = 'export.csv';
$url = 'http://www.someaddress.com/export/' . $filename;
$curl = curl_init();
$fd = fopen(DIR_FS_ADMIN . 'temp/' . $filename , "w");
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FILE, $fd);
curl_exec ($curl);
curl_close ($curl);

正如你所看到的,一段非常简单的代码在 PHP 5.3 中效果很好

这是 curl_getinfo() 的结果

[content_type] => text/csv
[http_code] => 200
[header_size] => 209
[request_size] => 95
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 1.98925
[namelookup_time] => 0.816404
[connect_time] => 0.817009
[pretransfer_time] => 0.831392
[size_upload] => 0
[size_download] => 13564110
[speed_download] => 6818705
[speed_upload] => 0
[download_content_length] => 13564110
[upload_content_length] => -1
[starttransfer_time] => 0.834829
[redirect_time] => 0
[certinfo] => Array
    (
    )
[redirect_url] => 
)
Error Code: 0

这些是在 5.5 上运行的相同代码的结果

[content_type] => 
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 126.332476
[namelookup_time] => 0.000369
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[redirect_url] => 
[primary_ip] => 
[certinfo] => Array
    (
    )
[primary_port] => 0
[local_ip] => 
[local_port] => 0
)
7 Failed to connect to www.someaddress.com/export/: Connection timed out

当然,在这里发布之前,我已经研究并尝试了很多选项,增加了超时时间,尝试了资源的SSL版本,并使用不同的curl_setopt玩了很多,但我总是无法从5.5应用程序连接。

我知道对 5.5 上的 cURL 扩展进行了一些更改,但我可以通过 Google 搜索发现上传问题,我也尝试了完全不同的选项,例如使用 file_get_contents 但仍然什么都没有,只是超时。

两个服务器都位于同一个地方,并且 URL 是完全打开的,所以我真的怀疑问题出在文件位置内,因为当我在 5.3 服务器上运行代码时仍然运行良好。

原来我试图访问的 URL 被阻止了我的服务器的 IP!

我能够联系网站管理员并将我的 IP 地址列入白名单,现在代码可以正常工作,无需任何更改。

要记住的其他事情,是什么使调试变得困难,它只是超时,没有错误消息或任何类型的。

来自 php 手册

现在,仅当CURLOPT_SAFE_UPLOAD选项设置为 FALSE 时,才支持使用 @file 语法的上载。应改用 CURLFile。

curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); 

多部分 POST 请求上存在"@"问题。

    Solution for PHP 5.5 or later:
    - Enable CURLOPT_SAFE_UPLOAD.
    - Use CURLFile instead of "@".
    Solution for PHP 5.4 or earlier:
    - Build up multipart content body by youself.
    - Change "Content-Type" header by yourself.

CURLFile 类