php - 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
)
谁能指出我在这里做错了什么?谢谢。
解决方案
$_FILES["file-0"]["tmp_name"]
我的问题是由于我假设的权限问题而找不到 CurlFile 。我通过在 www-root 文件夹中手动放置一个文件并$file_name_with_full_path
使用该文件路径进行硬编码来调试它,在这种情况下它可以工作。但是,所有临时文件都存储在该Windows
文件夹中,cURL 找不到它。我不确定这可能是一个可能的错误。
我所做的是upload_tmp_dir
将php.ini
文件中的位置更改为 www-root 目录,cURL 可以在其中访问临时文件。
推荐阅读
- javascript - 如果向下滚动并在某个宽度大小上触发 Javascript
- php - 如何将 PHP 5.5 安装到 Homestead?
- javascript - ES 模块:将命名导出作为模块导入?
- c - 如何声明大小为 2^18 的结构数组
- sql - Oracle中如何修剪不同列中的文本
- html - 将 OTF 字体添加到网页
- android - 尽管设备已注册且 API 显示成功,如何解决 Android 不显示 Firebase 推送通知的问题
- c++ - 如何实现像 a>b?c:d 这样的原子条件运算符函数?
- selenium - ExpectedConditions.presenceOfAllElementsLocatedBy 有多少?
- node.js - 如何卸载无服务器?“npm uninstall -g serverless”不起作用