curl POST 上传文件请求 returns false

Curl POST upload file request returns false

我正在尝试使用 gfycat API 创建一个 gfycat,通过 curl 使用 php 上传文件,但它不起作用 var_dump($response)给我 bool(false).

我的代码:

$file_path = $target_dir.$newfilename;
$cFile = curl_file_create($file_path);
$data = array(
     "file" => $cFile,
);
$target_url = "https://filedrop.gfycat.com";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     "Content-Type: multipart/form-data"
));            

$response = curl_exec($ch);
var_dump($response); // bool(false) here

curl_close($ch);

非常感谢您的帮助。谢谢

调试 curl 代码时,启用 CURLOPT_VERBOSE 并检查 stderr 日志通常是个好主意。此外,如果 curl_exec reutrned bool(false),则表示传输存在问题,您可以使用 curl_error() 函数来获取错误消息。最后,不要手动设置 header "Content-Type: multipart/form-data",curl 会为你设置 header,与你不同的是,curl 不会在这样做时出现任何拼写错误,更糟糕的是,你冒 overwriting/removing header 的边界参数的风险。

尝试

$file_path = $target_dir . $newfilename;
$cFile = curl_file_create ( $file_path );
$data = array (
        "file" => $cFile 
);
$target_url = "https://filedrop.gfycat.com";

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $target_url );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
try {
    $stderrh = tmpfile ();
    curl_setopt_array ( $ch, array (
            CURLOPT_VERBOSE => 1,
            CURLOPT_STDERR => $stderrh 
    ) );
    $response = curl_exec ( $ch );
    if ($response === false) {
        throw new \RuntimeException ( "curl error " . curl_errno ( $ch ) . ": " . curl_error ( $ch ) . " - verbose log: " . file_get_contents ( stream_get_meta_data ( $stderrh ) ['uri'] ) ); // https://bugs.php.net/bug.php?id=76268
    }
} finally{
    curl_setopt_array ( $ch, array (
            CURLOPT_VERBOSE => 0,
            CURLOPT_STDERR => STDERR 
    ) );
    fclose ( $stderrh );
}
var_dump ( $response ); // bool(false) here
curl_close ( $ch );

现在,如果出现错误,它应该会在异常错误日志中为您提供一个很好的详细日志,说明发生 curl 错误的情况。

顺便说一句,我得到它来处理这个:

$file_path = "ABSOLUTE_FILE_PATH".$newfilename;
$cFile = curl_file_create(realpath($file_path));
$data = array(
"key" => $newfilename,
"file" => $cFile,
);
$target_url = "https://filedrop.gfycat.com";

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: multipart/form-data"
));

$response = curl_exec($ch);

curl_close($ch);