PHP curl 实现RESTful PUT DELETE 实例

原创
2013/07/18 22:03
阅读数 2W

客户端

client.php

<?php

//PUT

$curl_handle = curl_init ();
// Set default options.
curl_setopt ( $curl_handle, CURLOPT_URL, 'http://my.focus.cn/test/socket.php');
curl_setopt ( $curl_handle, CURLOPT_FILETIME, true );
curl_setopt ( $curl_handle, CURLOPT_FRESH_CONNECT, false );


curl_setopt ( $curl_handle, CURLOPT_HEADER, true );
curl_setopt ( $curl_handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curl_handle, CURLOPT_TIMEOUT, 5184000 );
curl_setopt ( $curl_handle, CURLOPT_CONNECTTIMEOUT, 120 );
curl_setopt ( $curl_handle, CURLOPT_NOSIGNAL, true );
curl_setopt ( $curl_handle, CURLOPT_HEADER, true );
curl_setopt ( $curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
$aHeader[] = "Content-Type:text/xml;charset=UTF-8";
$aHeader[] = "x-bs-ad:private";
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $aHeader);
$file = 'client.php';
$file_size = filesize($file);
$h = fopen($file,'r');
curl_setopt ( $curl_handle, CURLOPT_INFILESIZE, $file_size);
curl_setopt ( $curl_handle, CURLOPT_INFILE, $h);
curl_setopt ( $curl_handle, CURLOPT_UPLOAD, true );
$ret = curl_exec ( $curl_handle );
print_r($ret);

?>

DELETE 只要将

$curl_handle = curl_init ();
// Set default options.
curl_setopt ( $curl_handle, CURLOPT_URL, 'http://my.focus.cn/test/socket.php?file=socket.txt');
curl_setopt ( $curl_handle, CURLOPT_FILETIME, true );
curl_setopt ( $curl_handle, CURLOPT_FRESH_CONNECT, false );


curl_setopt ( $curl_handle, CURLOPT_HEADER, true );
curl_setopt ( $curl_handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curl_handle, CURLOPT_TIMEOUT, 5184000 );
curl_setopt ( $curl_handle, CURLOPT_CONNECTTIMEOUT, 120 );
curl_setopt ( $curl_handle, CURLOPT_NOSIGNAL, true );
curl_setopt ( $curl_handle, CURLOPT_CUSTOMREQUEST, 'DELETE' );


$ret = curl_exec ( $curl_handle );



服务端

server.php

<?php

$raw_post_data = file_get_contents('php://input', 'r');

$method = $_SERVER['REQUEST_METHOD'];

if('PUT' == $method)

{
    $headers = apache_request_headers();
    file_put_contents('socket.txt',$raw_post_data.print_r($headers,true));

}

else if('DELETE'==$method)

{

       unlink($_GET['file']);

}


echo '<?xml version="1.0" encoding="UTF-8"?><RET>OK</RET>';

展开阅读全文
打赏
0
12 收藏
分享
加载中
delete其实只要设置为delete就行了,对于https的链接要加CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST这俩参数,还有的要设置header头
2015/11/04 16:53
回复
举报
刘德生博主

引用来自“子弹兄”的评论

能说一下,到底这个东东有什么作用吗?加个描述吧。好像很不错的样子!!

谢谢你的留言,好久没登陆了,不好意思。我写这篇文章,是因为前一段时间公司一些图片存储统一使用restful接口,同时又看了一下百度的云平台接口,就上网查资料研究了一下restful接口,其实这个应该就是http协议的一中规范吧,个人感觉,上面的代码是我对这个规范的理解。现在好像还没有使用php开发restful服务端的,http://www.oschina.net/p/prest 这篇文章似乎说的更明白一些。
2013/09/10 11:08
回复
举报
能说一下,到底这个东东有什么作用吗?加个描述吧。好像很不错的样子!!
2013/07/19 13:09
回复
举报
更多评论
打赏
3 评论
12 收藏
0
分享
返回顶部
顶部