在PHP中使用CURL发出PUT请求

时间:2012-02-08 08:06:22

标签: php curl php-5.3

我使用的是PHP 5.3.6,看起来我无法使用CURL进行PUT请求只是为了输入一个字符串。

function put_data($url, $data)
{   
  $useragent="SimpleAgent-1.0";
  $fh = fopen('php://memory', 'rw');
  fwrite($fh, $data);
  rewind($fh);$ch = curl_init();
  curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  curl_setopt($ch, CURLOPT_INFILE, $fh);
  curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_PUT, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $result = curl_exec($ch);
  curl_close($ch);
  fclose($fh);

  return $result;
}

这里,$ data是我想要PUT的字符串。 不起作用并返回以下错误:

  

500内部服务器错误服务器出错或无法执行   执行请求的操作。

     

预期的字符串或缓冲区

2 个答案:

答案 0 :(得分:0)

我使用你的代码如此定义了一个url并用字符串填充数据,并且所有工作都按预期工作。由于没有可以处理看跌期权的接收端,我被网站拒绝了。要轻松获取信息,只需添加该行即可     curl_setopt($ch, CURLOPT_VERBOSE, true);

你会得到类似的东西:

* About to connect() to yyyy.xxxx.com port 80 (#0)
*   Trying 62.221.196.28...
* connected
* Connected to yyyy.xxxx.com (zz.221.196.28) port 80 (#0)
> PUT / HTTP/1.1
User-Agent: SimpleAgent-1.0
Host: yyyy.xxxx.com
Accept: */*
Content-Length: 14
Expect: 100-continue

< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 405 Method Not Allowed
< Date: Thu, 09 Feb 2012 19:46:28 GMT
< Server: Apache
< Allow: GET,HEAD,POST,OPTIONS
< Vary: Accept-Encoding
< Content-Length: 231
< Content-Type: text/html; charset=iso-8859-1
< 
* Connection #0 to host yyy.xxxx.com left intact
* Closing connection #0

从日志记录中可以看出请求已经消失,但是当您想要放置数据时,apache设置不允许您将数据放入该URL。因此,根据服务器,您必须处理接受PUT的接收URL。

答案 1 :(得分:0)

我只能将数组作为数据传递给我正在使用的版本。所以这就是我现在正在做的事情:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_COOKIE, $curl_cookie);
$arr = array();
if (isset($data)) {
    $arr['my_data'] = $data;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arr));
curl_exec($ch);