您的位置 首页 php

PHP中CURL方法

bool curl_setopt ( resource $ ch  , int $option , mixed $value )
 

为给定的cURL会话 句柄 设置一个选项

ch

由 curl_init() 返回的 cURL 句柄。

option

需要设置的 CURLOPT_XXX 选项。

value

将设置在 option 选项上的值。

PHP代码实例

<?php
namespace Account\Library;
class Curl{
  private  $_ch = null;
 private $_url = null;
 private $_method = null;
 private $_params = null;
 public function __construct($url,$method,$params){
 $this-> _ch = curl_init();
 $this-> _url = $url;
 $this-> _method = $method;
 $this-> _params = $params;
 }
 public function execute(){
 curl_setopt($this-> _ch,CURLOPT_FAILONERROR, false);
 curl_setopt($this-> _ch,CURLOPT_RETURNTRANSFER, true);
 curl_setopt($this-> _ch,CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($this-> _ch,CURLOPT_SSL_VERIFYPEER, false);
 if($this->_method == 'GET'){//url已经带数据了
 $this-> _url = $this-> _url. '?';
 foreach($this-> _params as $k => $v){
 $this-> _url .= "$k =". urlencode ($v). '&';
 }
 $this-> _url = substr($this-> _url,0,-1);
 curl_setopt($this-> _ch,CURLOPT_URL,$this-> _url);
 }else if($this-> _method == 'POST'){
 curl_setopt($this-> _ch,CURLOPT_URL,$this-> _url);
 curl_setopt($this-> _ch,CURLOPT_POST, true);
 curl_setopt($this->_ch,CURLOPT_POSTFIELDS,$this->_params ); 
 }else{
 throw new Exception( "invalid http method");
 }
 $response = curl_exec($this-> _ch);
 if(curl_errno($this-> _ch)){
 throw new Exception(curl_error($this-> _ch),0);
 }else{
 $retCode = curl_getinfo($this->_ch,CURLINFO_HTTP_CODE);
 if($retCode != '200'){
 throw new Exception($response,$retCode);
 }
 }
 curl_close($this-> _ch);
 return $response;
 }
}

 

文章来源:智云一二三科技

文章标题:PHP中CURL方法

文章地址:https://www.zhihuclub.com/78982.shtml

关于作者: 智云科技

热门文章

网站地图