使用cURL传递$ _POST值

Sco*_*reu 92 php post curl

如何$_POST使用值将值传递给页面cURL

Ros*_*oss 166

应该工作正常.

$data = array('name' => 'Ross', 'php_master' => true);

// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
Run Code Online (Sandbox Code Playgroud)

我们这里有两个选项,CURLOPT_POST可以打开HTTP POST,CURLOPT_POSTFIELDS其中包含我们要提交的帖子数据数组.这可用于向POST <form>s 提交数据.


重要的是要注意curl_setopt($handle, CURLOPT_POSTFIELDS, $data);以两种格式获取$ data,这决定了后期数据的编码方式.

  1. $dataas array():将发送数据multipart/form-data,服务器并不总是接受该数据.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    
    Run Code Online (Sandbox Code Playgroud)
  2. $dataas url encoded string:数据将作为application/x-www-form-urlencoded提交的html表单数据的默认编码发送.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
    
    Run Code Online (Sandbox Code Playgroud)

我希望这能帮助别人节省时间.

看到:


Mar*_*iek 30

Ross有正确的想法将通常的参数/值格式发布到网址.

我最近遇到了一种情况,我需要将一些XML作为Content-Type"text/xml"发布而不需要任何参数对,所以这里是你如何做到的:

$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>';
$httpRequest = curl_init();

curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type:  text/xml"));
curl_setopt($httpRequest, CURLOPT_POST, 1);
curl_setopt($httpRequest, CURLOPT_HEADER, 1);

curl_setopt($httpRequest, CURLOPT_URL, $url);
curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);

$returnHeader = curl_exec($httpRequest);
curl_close($httpRequest);
Run Code Online (Sandbox Code Playgroud)

在我的情况下,我需要解析HTTP响应头中的一些值,因此您可能不一定需要设置CURLOPT_RETURNTRANSFERCURLOPT_HEADER.