douxianwu2221 2017-05-30 15:37
浏览 500
已采纳

PHP上的-F Curl选项

I'm trying to run CURL command in PHP to upload image to an API the code mentioned in the doc was:

curl -u 15:tokenkeyiskmzwa8awaa https://api.bukalapak.com/v2/images.json -F file=@product-image.png -X POST

Have tried using mac terminal running this curl command (with proper username and password) and successfully got the result as it is uploading, however was not successfully doing it on PHP. My php code is :

<?php

$data = array('file'=> '@'.$imagePath ); 

// this is an absolute path, give something like D://folder/path/on/my/webserver/image.jpg

$user = '1234567';

$pass = '123456';

$ch = curl_init();

$curl_options[CURLOPT_URL]  = 'https://api.bukalapak.com/v2/images.json';

$curl_options[CURLOPT_CAINFO] = storage_path('app/cacert.pem');

$curl_options[CURLOPT_HEADER] = "Content-Type: application/x-www-form-urlencoded";

$curl_options[CURLOPT_POST] = 1;

$curl_options[CURLOPT_USERPWD] = $user.':'.$pass;

$curl_options[CURLOPT_POSTFIELDS] = http_build_query($data);

curl_setopt_array($ch, $curl_options);

$content = curl_exec($->ch);`

Curl version : 7.47.1 PHP version : 5.6.21 any feedback is very appreciated.

  • 写回答

1条回答 默认 最新

  • doushua7737 2017-05-30 15:49
    关注

    You did not posted the complete script: $curl_options is undefined, storage_path is related to Laravel but there is no import, etc. Something like the following script should work as you expect (I didn't tested it since I don't have an account on this service):

    <?php
    
    $imagePath = 'path/to/your/image.ext';
    $user = 'youruser';
    $pass = 'yourpass';
    
    $file = curl_file_create($imagePath);
    $body = ['file' => $file];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.bukalapak.com/v2/images.json');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
    curl_setopt($ch, CURLOPT_CAINFO, 'path/to/cacert.pem');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    $result = curl_exec($ch);
    curl_close($ch);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同