php curl使用 常用操作

1. http Get

简单的只需要 这四行 就

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, "http://site" );
$output = curl_exec($ch);
curl_close ( $ch ); 

复杂的

public static function curlGet($url,$cookiefile,$header=null){
        try{
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL, $url );
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            //不知道如何看发出去的数据是什么样子的 使用这句话 可通过抓包工具查看到
            // 需要抓包工具配合使用
            curl_setopt($ch,CURLOPT_PROXY,'192.168.2.221:8889');
            if($header){
//                 curl_setopt ( $ch, CURLOPT_HEADER, 1 );
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
//                 curl_setopt ( $ch, CURLOPT_COOKIE,$header['Cookie'] );
//                 curl_setopt ( $ch, CURLOPT_COOKIESESSION,$header['Cookie'] );
            }
            else{
                curl_setopt ( $ch, CURLOPT_HEADER, 0 );
            }
    
            if($cookiefile){
                curl_setopt ( $ch, CURLOPT_COOKIEFILE, $cookiefile ); // 读取cookie
                curl_setopt ( $ch, CURLOPT_COOKIEJAR, $cookiefile ); // 设置Cookie信息保存在指定的文件中
            }
        
        
            $output = curl_exec($ch);
// 获取curl 信息 $information = curl_getinfo($ch); curl_close ( $ch ); }catch(Exception $e){ print_r($e->getMessage()); } return $output; }

  

2. http Post

public static function curlPost($url,$data,$cookiefile=null,$header=null){
        try{
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL, $url );
        
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt ( $ch, CURLOPT_POST, 1 );
            curl_setopt($ch,CURLOPT_PROXY,'192.168.2.221:8889');
            if($header){
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
            else{
                curl_setopt ( $ch, CURLOPT_HEADER, 0 );
            }
            if($cookiefile){
          curl_setopt ( $ch, CURLOPT_COOKIEFILE, $cookiefile ); // 读取cookie curl_setopt ( $ch, CURLOPT_COOKIEJAR, $cookiefile ); // 设置Cookie信息保存在指定的文件中 }       //!!!注意data的格式 curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data); //设置响应超时时间 curl_setopt($ch, CURLOPT_TIMEOUT, 120); $output = curl_exec($ch); if($output === false){ if(curl_errno($ch) == CURLE_OPERATION_TIMEDOUT){ //处理逻辑 } } $information = curl_getinfo($ch); curl_close ( $ch ); }catch(Exception $e){ print_r($e->getMessage()); } return $output; }

  

3. https Get (未完待续)

4. https Post(未完待续)

5. curl 使用过程中 发现不足的地方(未完待续)

原文地址:https://www.cnblogs.com/ISeeYouBlogs/p/7482724.html