PHP cURL HTTP PUT


75

我正在尝试使用cURL创建一个HTTP PUT请求,但无法使其正常工作。我已经阅读了许多教程,但没有一个真正起作用。这是我当前的代码:

$filedata = array('metadata' => $rdfxml);
$ch = curl_init($url);
$header = "Content-Type: multipart/form-data; boundary='123456f'";
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($filedata));
$returned = curl_exec($ch);

if (curl_error($ch))
{
    print curl_error($ch);
}
else
{
    print 'ret: ' .$returned;
}

我也尝试使用PHP PEAR,但是得到了相同的结果。问题在于存储库说尚未设置元数据。我真的需要帮助!谢谢!

Answers:


150

今天我自己正在做...这是我为我工作的代码...

$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

$response = curl_exec($ch);

if (!$response) 
{
    return false;
}

src:http//www.lornajane.net/posts/2009/putting-data-fields-with-php-curl


3
请注意,我尝试使用curl_setopt($curl, CURLOPT_PUT, true);此代码以及该代码,但均无效,因此curl_setopt($curl, CURLOPT_PUT, true);必须将其删除。
Nick M

您如何读取PUT数据?我已经尝试了一切,但没有运气。POST,GET或REQUEST不起作用。
andrebruton

5
我会尝试@andrebrutonfile_get_contents('php://input')
Vojtech Kane,

16

使用适用于Chrome的Postman,选择CODE,即可获得此...并且可以正常工作

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://blablabla.com/comorl",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"jordi@correo.es\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/json",
    "x-api-key: whateveriyouneedinyourheader"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>


3

在POST方法中,可以放置一个数组。但是,在PUT方法中,应该使用http_build_query来构建如下参数:

curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );

1

您混合了2个标准。

错误在 $header = "Content-Type: multipart/form-data; boundary='123456f'";

该功能http_build_query($filedata)仅适用于“内容类型:应用程序/ x-www-form-urlencoded”,或者不适用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.