PHP Curl工具类 有更新!

  hehaitao074

    class Util_CurlUtil
    {
    	/**
    	 * @param $url
    	 * @return mixed
    	 */
    	public static function curlGet($url)
    	{
    		// 1. 初始化
    		$ch = curl_init();
    		// 2. 设置选项,包括URL
    		curlsetopt($ch, CURLOPTURL, $url);
    		curlsetopt($ch, CURLOPTRETURNTRANSFER, 1);
    		curlsetopt($ch, CURLOPTHEADER, 0);
    		// 3. 执行并获取HTML文档内容
    		$output = curl_exec($ch);
    		if ($output === FALSE) {
    			echo "CURL Error:" . curl_error($ch);
    		}
    		// 4. 释放curl句柄
    		curl_close($ch);
    		return $output;
    	}
    
    	/**
    	 * @param $url
    	 * @param $postData
    	 * @return mixed
    	 */
    	public static function curlPost($url, $postData = null)
    	{
    		$ch = curl_init();
    		curlsetopt($ch, CURLOPTURL, $url);
    		curlsetopt($ch, CURLOPTRETURNTRANSFER, 1);
    		curlsetopt($ch, CURLOPTPOST, 1);
    		curlsetopt($ch, CURLOPTPOSTFIELDS, $postData);
    		$charr = array(CURLOPTTIMEOUT => 3, CURLOPT_RETURNTRANSFER => 1);
    		curlsetoptarray($ch, $ch_arr);
    		$output = curl_exec($ch);
    		curl_close($ch);
    		return $output;
    	}
    
    
    	/**
    	 * @param $URL
    	 * @param $type
    	 * @param $params
    	 * @param null $headers
    	 * @return mixed
    	 */
    	public static function curlRequest($URL,$type,$params=null,$headers=null){
    		$ch = curl_init($URL);
    		$timeout = 5;
    		if(isset($headers)){
    			curlsetopt ($ch, CURLOPTHTTPHEADER, $headers);
    		}else {
    			curlsetopt ($ch, CURLOPTHTTPHEADER, array('Content-type: application/json'));
    		}
    		curlsetopt ($ch, CURLOPTRETURNTRANSFER, 1);
    		curlsetopt ($ch, CURLOPTCONNECTTIMEOUT, $timeout);
    		switch ($type){
    			case "GET" : curlsetopt($ch, CURLOPTHTTPGET, true);break;
    			case "POST": curlsetopt($ch, CURLOPTPOST,true);
    				curlsetopt($ch, CURLOPTPOSTFIELDS,$params);break;
    			case "PUT" : curlsetopt ($ch, CURLOPTCUSTOMREQUEST, "PUT");
    				curlsetopt($ch, CURLOPTPOSTFIELDS,$params);break;
    			case "PATCH": curlsetopt($ch, CULROPTCUSTOMREQUEST, 'PATCH');
    				curlsetopt($ch, CURLOPTPOSTFIELDS, $params);break;
    			case "DELETE":curlsetopt ($ch, CURLOPTCUSTOMREQUEST, "DELETE");
    				curlsetopt($ch, CURLOPTPOSTFIELDS,$params);break;
    		}
    		$filecontents = curlexec($ch);//获得返回值
    		return $file_contents;
    		curl_close($ch);
    	}