我自己封装了curl工具类,测试表现:get,post,delete方式后台都能正确接收到前面传的参数,但是put方式就是获取不到参数.
1.相关代码:
index.php 入口请求文件
require_once 'MyCurl.class.php';
$data = ['param' => '成功', 'param1' => '这是神马'];
$res = MyCurl::send('http://localhost/servername/admin/test/ceshi', $data, 'put');
MyCurl.class.php curl工具类文件
class MyCurl
{
private static $url = ''; //请求url
private static $method = 'get'; //请求方式
private static $oriUrl = ''; //形式如 http://localhost
private static $data = []; //请求参数
public static function send($url, $data = [], $method = 'get')
{
$url or die('url can\'t be null');
self::$url = $url;
self::$method = strtoupper($method);
$urlArr = parse_url($url);
self::$oriUrl = $urlArr['scheme'] . '://' . $urlArr['host']; //形式为 http://localhost
self::$data = $data;
in_array(strtoupper(self::$method), array('GET', 'POST', 'PUT', 'DELETE')) or exit('error request method type!');
return self::doRequest();
}
/**
* 基础发起curl请求函数
* @return boolean
*/
private static function doRequest()
{
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //设置发起连接前的等待时间,如果设置为0,则无限等待。
curl_setopt($ch, CURLOPT_URL, self::$url);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override:' . self::$method));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //为1:curl_exec()有返回值,为0:curl_exec()无返回值,直接输出.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//4)"User-Agent: "头的字符串。
curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'); // 模拟用户使用的浏览器
switch (self::$method) {
case 'GET':
break;
case 'POST':
curl_setopt($ch, CURLOPT_POST, true); //POST方式
break;
case 'PUT':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); //PUT方式
break;
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); //DELETE方式
break;
default:
die('error :no method type');
break;
}
if (self::$data) {
if (self::$method == 'GET') {
curl_setopt($ch, CURLOPT_URL, self::$url . '?' . http_build_query(self::$data));
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(self::$data));
}
} else {
self::$method != 'GET' && die('POST/PUT/DELETE请求需要参数');
}
$data = curl_exec($ch); //运行curl
if (!$data) {
echo curl_error($ch);
}
curl_close($ch);
return $data;
}
}
处理请求文件,基于tp3.2
<?php
/**
* 测试类
*/
namespace Admin\Controller;
use Think\Controller;
class TestController extends Controller\RestController
{
public function ceshi()
{
$param = I('param.param');
echo '请求方法:'.$_SERVER['REQUEST_METHOD'];
echo '请求方法:'.$this->_method.'<br/>';
echo '请求参数:';
echo $param;
print_r($_REQUEST);
parse_str(file_get_contents('php://input'), $data);
print_r($data);
$test= file_get_contents('php://input');
print_r($test);
}
}
无论怎么做都接收不了put请求方式传送过来的参数,让我很纳闷,在这上面也纠结很久了.想请fault的网友们帮忙
试试这个 http://php.net/manual/zh/rese...