PHP CURL多表单上传图片至Pass Slot失败,求技术解决方案
修复PHP CURL上传Pass Slot凭证图片的问题
你的代码存在几个关键错误,导致API无法识别上传的图片字段,以下是修复方案:
核心错误点及修正
- 过时的文件上传方式:PHP 5.5+已废弃
@前缀的文件上传写法,必须使用CURLFile类构造文件参数。 - 错误的Content-Type设置:手动指定
text/plain会覆盖curl自动生成的multipart/form-data头部,导致API无法解析表单数据,需移除该自定义头。 - 表单数据格式混乱:
$data1数组中image字段的格式错误,无需拼接远程URL和多余参数,仅需用CURLFile指定本地文件路径即可。 - 冗余的CURL初始化:代码末尾重复执行
curl_init属于无效操作,需删除。
修正后的完整代码
$passId = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"; $pass_generate_url = "pass.xxxxxxxxxxxx"; $url1 = 'https://api.passslot.com/v1/passes/'.$pass_generate_url.'/'.$passId.'/images/strip/normal'; // 本地图片的绝对路径,确保PHP有读取权限 $logo_file_location = __DIR__ . '/uploads/image.png'; // 构造符合要求的表单数据 $data1 = [ 'image' => new CURLFile($logo_file_location, 'application/octet-stream', 'image.png') ]; // 仅保留授权头,移除错误的Content-Type设置 $auth1 = [ 'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=' ]; $ch1 = curl_init($url1); curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch1, CURLOPT_POST, 1); curl_setopt($ch1, CURLOPT_POSTFIELDS, $data1); curl_setopt($ch1, CURLOPT_HEADER, 0); curl_setopt($ch1, CURLOPT_HTTPHEADER, $auth1); $response1 = curl_exec($ch1); // 可选:检查CURL运行错误 if(curl_errno($ch1)) { echo 'CURL错误:' . curl_error($ch1); } // 关闭CURL资源 curl_close($ch1); var_dump($response1);
额外注意事项
- 确保
$logo_file_location是正确的本地绝对路径,且PHP进程对该文件拥有读取权限。 CURLFile的第二个参数对应API要求的application/octet-stream,第三个参数是传给API的文件名。
内容的提问来源于stack exchange,提问作者Renegade Rob
相关产品推荐
相关产品推荐

