PHP Curl请求附加CurlFile不起作用

时间:2019-06-29 12:59:49

标签: php http curl php-curl

我正在尝试向后端发送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
)

有人可以指出我在做什么错吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

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

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