首页 > 解决方案 > PHP Curl 请求附加 CurlFile 不工作

问题描述

我正在尝试向我的后端发出 POST 请求,我需要附加一个 token和一个或多个图像files

我的 PHP 版本是 5.6,我正在使用 CurlFile 创建文件。服务器上永远不会收到请求。

PHP 代码

$file_name_with_full_path = $_FILES["file-0"]["tmp_name"]; //tested all good
$target_url = $app_engine_url."images/upload";
$accessToken = $_SESSION['token'];
$imageName = basename($_FILES["file-0"]["name"]);
$filesize = $_FILES['file-0']['size'];


$postfields = array("file" =>  makeCurlFile($file_name_with_full_path), "filename" => $imageName,"access_token"=>$accessToken);

$headers = array("Content-Type:multipart/form-data");
$ch = curl_init();
$options = array(
    CURLOPT_URL => $target_url,
    CURLOPT_HEADER => true,
    CURLOPT_POST => 1,
    CURLOPT_SAFE_UPLOAD => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_INFILESIZE => $filesize,
    CURLOPT_POSTFIELDS => $postfields,
    CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
$resp = curl_exec($ch);

echo $resp;


if(!curl_errno($ch)) {
    $info = curl_getinfo($ch);
    if ($info['http_code'] == 200)
        $errmsg = "File uploaded successfully";
}
else
{
    $errmsg = curl_error($ch);
}

print_r(curl_getinfo($ch));

curl_close($ch);

echo stripslashes($errmsg);

return null;



}

function makeCurlFile($file){
    $info   = getimagesize($file);
    $mime   = $info['mime'];  etc.
    $name = basename($_FILES["file-0"]["name"]);
    $output = new \CURLFile($file, $mime, $name);

    return $output; //Object is also created successfully (tested by calling 
                                                                 //methods) 
}

PHP 响应

 Array
(
    [url] => someurl.com          //URL is correct (double checked)
    [content_type] => 
    [http_code] => 0
    [header_size] => 0
    [request_size] => 0
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.031
    [namelookup_time] => 0.015
    [connect_time] => 0.031
    [pretransfer_time] => 0
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => -1
    [upload_content_length] => -1
    [starttransfer_time] => 0
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => 172.217.212.153
    [certinfo] => Array
        (
        )

    [primary_port] => 443
    [local_ip] => 10.128.0.3
    [local_port] => 49858
)

谁能指出我在这里做错了什么?谢谢。

标签: phphttpcurlphp-curl

解决方案


$_FILES["file-0"]["tmp_name"] 我的问题是由于我假设的权限问题而找不到 CurlFile 。我通过在 www-root 文件夹中手动放置一个文件并$file_name_with_full_path使用该文件路径进行硬编码来调试它,在这种情况下它可以工作。但是,所有临时文件都存储在该Windows文件夹中,cURL 找不到它。我不确定这可能是一个可能的错误。

我所做的是upload_tmp_dirphp.ini文件中的位置更改为 www-root 目录,cURL 可以在其中访问临时文件。


推荐阅读