道者编程


PHP通过CURL实现RESTful风格

<?php

class Curl
{
	private static $instance;

	public static function get_instance()
	{
		if (empty(self::$instance)) {
			self::$instance = new Curl();
		}
		return self::$instance;
	}
	
	//POST方式
	public static function post($url,$curlData)
	{
		return self::get_instance()->execute([
			'url'=>$url,
			'curlData'=>$curlData,
			'type'=>'POST'
		]);
	}
	
	//GET方式
	public static function get($url)
			return  self::get_instance()->execute([
			'url'=>$url,
			'type'=>'GET'
		]);
	}
	
	//json方式
	public static function json($url,$curlData)
	{
		return  self::get_instance()->execute([
			'url'=>$url,
			'curlData'=>$curlData,
			'type'=>'JSON'
		]);
	}
	
	//put
	public static function put($url,$curlData='')
	{
		return  self::get_instance()->execute([
			'url'=>$url,
			'curlData'=>$curlData,
			'type'=>'PUT'
		]);
	}
	
	//delete
	public static function delete($url,$curlData='')
	{
		return  self::get_instance()->execute([
			'url'=>$url,
			'curlData'=>$curlData,
			'type'=>'DELETE'
		]);
	}
	
	private function execute($list)
	{
		$ch = curl_init();   
		curl_setopt($ch, CURLOPT_URL,$list['url']);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	// https请求 不验证证书
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);   // https请求 不验证hosts
		curl_setopt($ch, CURLOPT_TIMEOUT,60); //60秒超时
		if($list['curlData']){
			$fields = self::get_instance()->urlStr($list['curlData']); 
			curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);


		}
		
		switch ($list['type']){ 
			
			case "JSON": 
			curl_setopt($ch, CURLOPT_POST,true);   
			curl_setopt($ch, CURLOPT_POSTFIELDS,$list['curlData']);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json',
			));
			break; 


			case "GET": 
			curl_setopt($ch, CURLOPT_HTTPGET, true);
			break;  


			case "POST": 
			curl_setopt($ch, CURLOPT_POST,true);   
			break;  
			
			case "PUT": 
			curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");   
			break;  


			case "DELETE":  
			curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");   
			break;  
		}
		$result=curl_exec ($ch);
		curl_close ($ch);
		return $result;
	}


	private function urlStr($fields)
	{
		return (is_array($fields)) ? http_build_query($fields) : $fields; 
	}
}

调用

<?php
require('Curl.php');

//数组调用
$list = ['name'=>'lijie','sex'=>13];
echo Curl::put('127.0.0.1/520/get.php',$list);

//delete和put也可以这样调用
echo Curl::put('127.0.0.1/520/get.php?name=lijie&sex=13');
 

PHP判断请求方式

<?php
$type = $_SERVER['REQUEST_METHOD'];

parse_str(file_get_contents('php://input'), $data);

$data = array_merge($_GET, $_POST, $data);

echo '发起方式:'.$type;
//参数
print_r($data);


最新评论:
我要评论:

看不清楚


链接