php curl詳細解析和常見大坑


1. 拿來先試試手

比如我們以著名的“測試網絡是否連接”的網站——百度為例,來嘗試下curl

<?php // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, "baidu.com"); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); //echo output echo $output; // close curl resource to free up system resources curl_close($ch); ?>

當你在本地環境瀏覽器打開這個php文件時,頁面出現的是百度的首頁,特么我剛才輸入的“localhost”呢?

上面的代碼和注釋已經充分說明了這段代碼在干啥。

$ch = curl_init(),創建了一個curl會話資源,成功返回一個句柄; 
curl_setopt($ch, CURLOPT_URL, "baidu.com"),設置URL,不用說;

上面兩句可以合起來變一句$ch = curl_init("baidu.com")

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0)這是設置是否將響應結果存入變量,1是存入,0是直接echo出;

$output = curl_exec($ch)執行,然后將響應結果存入$output變量,供下面echo;

curl_close($ch)關閉這個curl會話資源。

PHP中使用curl大致就是這么一個形式,其中第二步,通過curl_setopt方法來設置參數是最復雜也是最重要的,感興趣可以去看官方的關於可設置參數的詳細參考,長地讓你看得想吐,還是根據需要熟能生巧吧。

小結一下,php中curl用法就是:創建curl會話 -> 配置參數 -> 執行 -> 關閉會話。

下面我們來看一些常用的情景,我們需要如何“打扮自己”(配置參數)才能正確“撩妹”(正確撩到服務器)。

2.GET和POST請求以及HTTPS協議處理

2.1 GET請求

我們以“在某網站github中搜索關鍵詞”為例

//通過curl進行GET請求的案例 <?php // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, "https://github.com/search?q=react"); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); //echo output echo $output; // close curl resource to free up system resources curl_close($ch); ?>

好像和之前那個例子沒啥差別,但這里有2個可以提的點: 
1.默認請求方式是GET,所以不需要顯式指定GET方式; 
2.https請求,非http請求,可能有人在各個地方看到過HTTPS請求需要加幾行代碼繞過SSL證書的檢查等方式來成功請求到資源,但是這里好像並不需要,原因是什么?

The two Curl options are defined as:

CURLOPT_SSL_VERIFYPEER - verify the peer's SSL certificate CURLOPT_SSL_VERIFYHOST - verify the certificate's name against host

They both default to true in Curl, and shouldn't be disabled unless you've got a good reason. Disabling them is generally only needed if you're sending requests to servers with invalid or self-signed certificates, which is only usually an issue in development. Any publicly-facing site should be presenting a valid certificate, and by disabling these options you're potentially opening yourself up to security issues.

即,除非用了非法或者自制的證書,這大多數出現在開發環境中,你才將這兩行設置為false以避開ssl證書檢查,否者不需要這么做,這么做是不安全的做法。

2.2 POST請求

那如何進行POST請求呢?為了測試,先在某個測試服務器傳了一個接收POST的腳本:

//testRespond.php <?php $phpInput=file_get_contents('php://input'); echo urldecode($phpInput); ?>

發送普通數據

然后在本地寫一個請求:

<?php $data=array( "name" => "Lei", "msg" => "Are you OK?" ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://測試服務器的IP馬賽克/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>

瀏覽器運行結果是:

name=Lei&msg=Are you OK?

這里我們是構造了一個數組作為POST數據傳給服務器:

  • curl_setopt($ch, CURLOPT_POST, 1)表明是POST請求;

  • curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60)設置一個最長的可忍受的連接時間,秒為單位,總不能一直等下去變成木乃伊吧;

  • curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data))設置POST的數據域,因為這里是數組數據形式的(等會來講json格式),所以用http_build_query處理一下。

對於json數據呢,又怎么進行POST請求呢?

<?php $data='{"name":"Lei","msg":"Are you OK?"}'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://測試服務器的IP馬賽克/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length:' . strlen($data))); curl_setopt($ch, CURLOPT_POSTFIELDS , $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>

瀏覽器執行,顯示:

{"name":"Lei","msg":"Are you OK?"}

3. 如何上傳和下載文件

3.1 POST上傳文件

同樣遠程服務器端我們先傳好一個接收腳本,接收圖片並且保存到本地,注意文件和文件夾權限問題,需要有寫入權限:

<?php if($_FILES){ $filename = $_FILES['upload']['name']; $tmpname = $_FILES['upload']['tmp_name']; //保存圖片到當前腳本所在目錄 if(move_uploaded_file($tmpname,dirname(__FILE__).'/'.$filename)){ echo ('上傳成功'); } } ?>

然后我們再來寫我們本地服務器的php curl部分:

<?php $data = array('name'=>'boy', "upload"=>"@boy.png"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://遠程服務器地址馬賽克/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_POSTFIELDS , $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>

瀏覽器中運行一下,什么都米有,去看一眼遠程的服務器,還是什么都沒有,並沒有上傳成功。

為什么會這樣呢?上面的代碼應該是大家搜索curl php POST圖片最常見的代碼,這是因為我現在用的是PHP5.6以上版本,@符號在PHP5.6之后就棄用了,PHP5.3依舊可以用,所以有些同學發現能執行啊,有些發現不能執行,大抵是因為PHP版本的不同,而且curl在這兩版本中實現是不兼容的,上面是PHP5.3的實現。

下面來講PHP5.6及以后的實現,:

<?php $data = array('name'=>'boy', "upload"=>""); $ch = curl_init(); $data['upload']=new CURLFile(realpath(getcwd().'/boy.png')); curl_setopt($ch, CURLOPT_URL, "http://115.29.247.189/test/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_POSTFIELDS , $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>

這里引入了一個CURLFile對象進行實現,關於此的具體可查閱文檔進行了解。這時候再去遠程服務器目錄下看看,發現有了一張圖片了,而且確實是我們剛才上傳的圖片。

3.2 獲取遠程服務器的圖片

遠程服務器在她自己的目錄下存放了一個圖片叫girl.jpg,地址是她的web服務器根目錄/girl.jpg,現在我要去獲取這張圖片。

<?php $ch = curl_init(); $fp=fopen('./girl.jpg', 'w'); curl_setopt($ch, CURLOPT_URL, "http://遠程服務器地址馬賽克/girl.jpg"); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_FILE, $fp); $output = curl_exec($ch); $info = curl_getinfo($ch); fclose($fp); $size = filesize("./girl.jpg"); if ($size != $info['size_download']) { echo "下載的數據不完整,請重新下載"; } else { echo "下載數據完整"; } curl_close($ch); ?>

現在,在我們當前目錄下就有了一張剛拿到的照片啦,是不是很激動呢!

這里值得一說的是curl_getinfo方法,這是一個獲取本次請求相關信息的方法,對於調試很有幫助,要善用。

4. HTTP認證怎么搞

那么拿到了用戶名和密碼,我們怎么通過PHP CURL搞定HTTP認證呢?

PS:這里偷懶就不去搭HTTP認證去試了,直接放一段代碼,我們分析下。

function curl_auth($url,$user,$passwd){ $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_USERPWD => $user.':'.$passwd, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true ]); $result = curl_exec($ch); curl_close($ch); return $result; } $authurl = 'http://要請求HTTP認證的地址'; echo curl_auth($authurl,'vace','passwd');

這里有一個地方比較有意思: 
curl_setopt_array 這個方法可以通過數組一次性地設置多個參數,防止有些需要多處設置的出現密密麻麻的curl_setopt方法。

5.利用cookie模擬登陸

首先我們先來分析一下,這個事情分兩步,一是去登陸界面通過賬號密碼登陸,然后獲取cookie,二是去利用cookie模擬登陸到信息頁面獲取信息,大致的框架是這樣的。

<?php //設置post的數據 $post = array ( 'email' => '賬戶', 'pwd' => '密碼' ); //登錄地址 $url = "登陸地址"; //設置cookie保存路徑 $cookie = dirname(__FILE__) . '/cookie.txt'; //登錄后要獲取信息的地址 $url2 = "登陸后要獲取信息的地址"; //模擬登錄 login_post($url, $cookie, $post); //獲取登錄頁的信息 $content = get_content($url2, $cookie); //刪除cookie文件 @ unlink($cookie); var_dump($content); ?>

然后我們思考下下面兩個方法的實現:

  • login_post($url, $cookie, $post)

  • get_content($url2, $cookie)

//模擬登錄 function login_post($url, $cookie, $post) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post)); curl_exec($curl); curl_close($curl); } 
//登錄成功后獲取數據 function get_content($url, $cookie) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); $rs = curl_exec($ch); curl_close($ch); return $rs; } 

至此,總算是模擬登陸成功,一切順利啦,通過php CURL“撩”服務器就是這么簡單。

當然,CURL的能力遠不止於此,本文僅希望就后端PHP開發中最常用的幾種場景做一個整理和歸納。最后一句話,具體問題具體分析。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM