【问题标题】:Send file to API with PHP using cURL使用 cURL 使用 PHP 将文件发送到 API
【发布时间】:2016-07-11 17:27:09
【问题描述】:

我正在尝试将文件上传到此 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);

?>

谁能解释我当前的代码不起作用? 它应该返回一个这样的 url:http://www.noelshack.com/2016-XX-XXXXXXXXXX-2386.png

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

提前致谢

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

【问题讨论】:

  • 我已添加此代码以查看 curl 是否返回错误: if(curl_exec($curl) === false) { echo 'curl error : '.curl_error($curl); } else { echo "没问题"; } 并返回“没问题”!

标签: php api curl


【解决方案1】:

有 2 个潜在问题。

  1. 要使用 cURL 发布文件,它必须位于本地文件系统上。您不能指定超过 http:// 的文件。
  2. 根据您的 PHP 版本,您可能需要使用 CURLFile 类,而不是在文件名前加上 @

这里有一些代码可以解决这两个问题:

<?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);

如果您没有 PHP 5.5.0 或更高版本,只需删除 CURLFile 结构并将其替换为 '@' . $tmp,

【讨论】:

  • 嗨@drew010 我正在使用 php 7.1.1 并尝试使用 CURL 上传图像。但这里没有成功是我的代码 $cFile); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, $sheader); curl_exec($ch); ?>
猜你喜欢
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 2018-01-09
  • 1970-01-01
  • 2015-08-23
  • 2015-04-22
  • 2019-06-26
相关资源
最近更新 更多