curl_setopt()在尝试通过php中的curl上传文件时抛出错误异常

时间:2014-10-09 07:13:52

标签: php curl

我发现了一些与上述相关的问题,但我没有得到任何适当的答案。这是我的代码:

$requestUrl = <MY_URL>;
$filePath = <MY_FILE_PATH>;
$post = array('extra_info' => '123456','file_contents'=>'@'.$filePath);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$requestUrl);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
curl_close($ch);

echo $response;

我收到错误异常,如:

curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead.

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

从PHP 5.5.0开始,不推荐使用@前缀,可以使用CURLFile发送文件。您可以查看手册here

试试这个:

$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,  
array('Authorization: Bearer XXXXXXXXXXXXXXXYYYYYzzzzzz', 'Accept-Version: ~1', 'Except: 100-continue', 'Content-type: multipart/form-data')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

$args['file'] = new CurlFile('<file_path>', 'text/plain', 'myfile');

curl_setopt($ch, CURLOPT_POSTFIELDS, $args); 

$response = curl_exec($ch);

答案 1 :(得分:0)

请参阅此内容,愿这可以帮助您http://pdfcrowd.com/forums/read.php?4,1930

PHP 5.5引入了一个CurlFile对象,该对象弃用了旧的@filename语法 另见:https://wiki.php.net/rfc/curl-file-upload

public function getCurlValue()
{

    if (function_exists('curl_file_create')) {
        return curl_file_create($this->filename, $this->contentType, $this->postname);
    }

    // Use the old style if using an older version of PHP
    $value = "@{$this->filename};filename=" . $this->postname;
    if ($this->contentType) {
        $value .= ';type=' . $this->contentType;
    }

    return $value;
}