如何使用cURL在php中发布表单数据?

问题描述 投票:0回答:8

我有以下命令,它使用 --form/--F 选项,我知道它正在工作:

curl  --form "file=@/home/USERNAME/import.csv" https://apiprovider.com/api/v0/imports\?token\=[KEY]

我需要通过 php 运行此命令,但我遇到了麻烦,大概是表单文件数据。我尝试了以下操作,但是 echoing 或 var_dumping 结果似乎没有显示任何内容,只是一个空白页或一个空白字符串。

<?php 
$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]'
$file_name_with_full_path ='/home/USERNAME/import.csv';
$post = array('file'=>'@'.$file_name_with_full_path);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result=curl_exec ($ch);
curl_close ($ch);
var_dump($result);?>

如何让该命令在 PHP 中运行?

php curl
8个回答
17
投票

由于到目前为止还没有答案(至少没有在 php 5.6+ 中工作的方法),所以这里是:等效的 php curl_ 代码将是:

$ch = curl_init ( 'https://apiprovider.com/api/v0/imports?token=[KEY]' );
curl_setopt_array ( $ch, array (
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => array (
                'file' => new CURLFile ( '/home/USERNAME/import.csv' ) 
        ) 
) );
curl_exec ( $ch );

(我还建议将 CURLOPT_ENCODING 设置为空字符串,特别是如果您希望响应可压缩,这相当于将

--compressed
添加到curl 命令行,并且可能会加快速度)


4
投票

试试这个:

<?php 
$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]'
$file_name_with_full_path ='/home/USERNAME/import.csv';
$post = array('file'=>'@'.$file_name_with_full_path);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec ($ch);

$curlresponse = json_decode($result, true);

var_dump($curlresponse);
?>

3
投票

对于 5.5 以上的 PHP 版本,一种方法是使用

CURLFile
代替 @

$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]'
$file_name_with_full_path ='/home/USERNAME/import.csv';
// Create a CURLFile object
$cfile = new CURLFile($file_name_with_full_path,mime_content_type($file_name_with_full_path),'imported_csv');    
// Assign POST data
$post = array('imported_csv_file' => $cfile);    
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result=curl_exec ($ch);
curl_close ($ch);
var_dump($result);

1
投票

也许这样的东西可以工作:

<?php 
$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]'
$file_name_with_full_path ='/home/USERNAME/import.csv';
$post = array('file'=>'@'.$file_name_with_full_path);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$target_url);
curl_setopt($curl, CURLOPT_POST,1);
curl_setopt($curl, CURLOPT_POST, count($post)
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_VERBOSE,true);
$result = curl_exec($curl)
if(!$result){
    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
curl_close($curl);
var_dump($result);
?>

1
投票

这对我有用。你可以试试

  $authHeader = array('Accept: application/form-data');

  $post_fields =  "client_id=" . $client_id . "&client_secret=" . $client_secret;

  send_curl_request("POST", $authHeader, $url, $post_fields);

function send_curl_request($method, $headers, $url, $post_fields){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url);
  if(count($headers) > 0){
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //echo '<br> HEADER ADDED<br><br>';
  }
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
  if($method == "POST"){
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    //echo '<br> POST FIELDS ADDED<br><br>';
  } 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_VERBOSE,true);
  $result = curl_exec($ch);
curl_close($ch);
return $result;
}

0
投票

使用这个库 https://github.com/php-curl-class/php-curl-class 然后

$curl = new Curl();
$curl->post('https://www.example.com/login/', array(
    'username' => 'myusername',
    'password' => 'mypassword',
));

0
投票

您需要读取文件数据,然后将数据附加到帖子字段上。

试试这个,应该可以。如果不起作用,请确保

fread()
可以读取您的文件。由于多种原因,读取可能会失败。

$target_url = 'https://apiprovider.com/api/v0/imports?token=[KEY]'

$file_name_with_full_path ='/home/USERNAME/import.csv';
$fileHandler = fopen($file_name_with_full_path, 'r');
$fileData = fread($fileHandler, filesize($file_name_with_full_path));

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

$headers = array('file'=>'@'.$file_name_with_full_path);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_INFILE, $fileHandler);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_name_with_full_path));

curl_setopt($ch, CURLOPT_POSTFIELDS, $fileData);

$result = curl_exec($ch);

curl_close ($ch);
var_dump($result);

0
投票
 $data = array(
                            'auth'=>'Manual',
                            'confirmed'=>1, 
                            'mnethostid'=>1,
                            'username' =>$email_address,
                           'password'=>password_hash('$password', PASSWORD_DEFAULT),
                           'firstname'=>$first_name,
                           'lastname'=>$last_name,
                           'email'=>$email_address,
                           'country'=>$country,
                           'address'=>$full_address
                          );
                          echo "<pre>"; print_r($data); 
                          $data_json = json_encode($data);
                          echo "<pre>"; print_r($data_json);
                          $url = 'http://localhost/moodles/server/moodle/user/editadvanced.php?id=-1';
                          $body = '--BOUNDARY
                                  Content-type: application/x-ups-binary
                                  Content-length: 7190200942011R02014093000000012939600400909000000001*AA111111US0
                                                 0129396004000001*BA1Z111111030000209500001+0000000000000070+0000000000000000LBS03PRE103INUSD000001
                                                 *CA18TESTORDERTESTORDER10800E45THAVEDENVERCO80239US15555555555*PA1Z111111030000209502+
                                                 0000070+0000000+00000000+00000000+00000000*SA000004--BOUNDARY--';


                          $header[] = "Host: www.pld-certify.ups.com";
                          $header[] = "MIME-Version: 1.0";
                          $header[] = "Content-type: multipart/mixed; boundary=BOUNDARY";
                          $header[] = "Content-length: ".strlen($body);
                          $header[] = "Cache-Control: no-cache";
                          $header[] = "Connection: close \r\n";
                          $header[] = $body;
                          $ch = curl_init();
                          curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);    // follow redirects
                          curl_setopt($ch,CURLOPT_ENCODING, "");     // handle all encodings
                          curl_setopt($ch,CURLOPT_USERAGENT, "spider"); // who am i
                          curl_setopt($ch,CURLOPT_AUTOREFERER, true);     // set referer on redirect
                          curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,15);     // timeout on connect
                          curl_setopt($ch,CURLOPT_TIMEOUT,15);      // timeout on response
                          curl_setopt($ch,CURLOPT_MAXREDIRS,10);       // stop after 10 redirects
                          curl_setopt($ch, CURLOPT_URL, $url);
                          curl_setopt($ch, CURLOPT_HEADER,true);
                         // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                          //'Content-Length: ' . strlen($data_json)));
                          curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                          //'Authorization: Basic '. base64_encode("username:password")
                          //curl_setopt($ch, CURLOPT_USERPWD, $email_address . ":" . $password);
                          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                          curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
                          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                          $response  = curl_exec($ch);
                          var_dump($response); exit;
                          curl_close($ch);
                          $json_a2 = json_decode($response, true);



I have tried like this, but getting the issue bool(false) can you please let me know that what will be the issue?
© www.soinside.com 2019 - 2024. All rights reserved.