28

从 PHP 5.5 升级到 5.6 后,我的 cURL 上传失败:

$aPost = array(
    'file' => "@".$localFile,
    'default_file' => 'html_version.html',
    'expiration' => (2*31*24*60*60)
)

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_POSTFIELDS, $aPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$sResponse = curl_exec ($ch);

该文件在目标系统上似乎是空的。

4

3 回答 3

42

实际上,我在开始问题时找到了答案。在 PHP 5.5 中 curl 包含一个新变量:在 PHP 5.5中默认CURLOPT_SAFE_UPLOAD设置为默认值,在 PHP 5.6false中切换为默认值。true

出于安全原因,这将阻止“@”上传修饰符工作 - 用户输入可能包含恶意上传请求。您可以在设置为orCURLFile时使用该类上传文件(如果您确定您的变量是安全的,您可以手动切换到):CURLOPT_SAFE_UPLOADtrueCURLOPT_SAFE_UPLOADfalse

 curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

这是让我朝着正确方向搜索的信息来源:http: //comments.gmane.org/gmane.comp.php.devel/87521

在更改的功能中也提到了它:http: //php.net/manual/en/migration56.changed-functions.php 但不是在向后不兼容的更改中,真的让我失望了......

于 2014-09-19T12:38:06.187 回答
32

只需对 PHP 5.5 或更高版本进行以下更改

而不是"@" . $localFile仅仅使用new CurlFile($localFile)

并设置

curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
于 2015-07-27T13:54:45.610 回答
9

包括运行时检查以使您的代码与较低版本兼容,如下所示

$aPost = array(
    'default_file' => 'html_version.html',
    'expiration' => (2*31*24*60*60)
)
if ((version_compare(PHP_VERSION, '5.5') >= 0)) {
    $aPost['file'] = new CURLFile($localFile);
    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
} else {
    $aPost['file'] = "@".$localFile;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_POSTFIELDS, $aPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$sResponse = curl_exec ($ch);
于 2015-11-17T06:13:02.227 回答