使用cURL使用PHP将文件发送到API

时间:2016-07-11 17:27:10

标签: php api curl

我正在尝试将文件上传到此API:http://www.noelshack.com/api.php 我对cURL一无所知。我找到了示例代码,我试过这个:

<?php

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.noelshack.com/api.php');

// send a file
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt(
    $curl,
    CURLOPT_POSTFIELDS,
    array(
      'fichier' => '@http://cdn.soccerwiki.org/images/player/2386.jpg'
    ));

// output the response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
print_r($result);

curl_close($curl);

?>

任何人都可以解释我当前的代码不起作用吗? 它应该返回一个这样的网址:http://www.noelshack.com/2016-XX-XXXXXXXXXX-2386.png

但它没有返回任何东西。我的代码没有任何错误,文件没有上传,我不知道为什么因为我不知道如何显示api错误!

提前致谢

(对不起我的英语,我是法国人)

1 个答案:

答案 0 :(得分:3)

There are 2 potential issues.

  1. To POST a file using cURL, it must be located on the local filesystem. You can't specify a file over http://.
  2. Depending on your PHP version you may need to use the CURLFile class instead of prepending the filename with an @.

Here is some code that fixes both issues:

<?php

ini_set('display_errors', 1);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.noelshack.com/api.php');
curl_setopt($curl, CURLOPT_VERBOSE, 1);
//curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0');
//curl_setopt($curl, CURLOPT_ENCODING, '');
//curl_setopt($curl, CURLOPT_REFERER, 'http://www.noelshack.com/api.php');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

// download image to temp file for upload
$tmp = tempnam(sys_get_temp_dir(), 'php');
file_put_contents($tmp, file_get_contents('http://cdn.soccerwiki.org/images/player/2386.jpg'));

// send a file
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt(
    $curl,
    CURLOPT_POSTFIELDS,
    array(
      'fichier' => new CURLFile($tmp),
      'submit'  => 'Envoyer',
    ));

// output the response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
var_dump($result, curl_error($curl));

unlink($tmp); // remove temp file

curl_close($curl);

If you don't have PHP 5.5.0 or greater, just remove the CURLFile construction and replace it with '@' . $tmp,