CURL

 

0. curl是個什麼東西

這是PHP對於curl的一個解釋,簡單地說就是,curl是一個庫,能讓你通過URL和許多不同種的服務器進行勾搭、搭訕和深入交流,並且還支持許多協議。並且人家還說了curl可以支持https認證、http post、ftp上傳、代理、cookies、簡單口令認證等等功能啦。

在正式講怎麼用之前啊,先提一句,你得先在你的PHP環境中安裝和啓用curl模塊,具體方式我就不講了,不同系統不同安裝方式,可以google查一下,或者查閱PHP官方的文檔,還挺簡單的。

1. 拿來先試試手

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<?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協議處理

先和服務器打個招呼吧,給服務器發個Hello看她怎麼回,這裏最方便的方式就是向服務器發出GET請求,當然POST這種小紙條也OK咯。

2.1 GET請求

我們以“在某著名同性交友網站github中搜索關鍵詞”爲例

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

//通過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:

1

2

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的腳本:

1

2

3

4

5

//testRespond.php

<?php 

    $phpInput=file_get_contents('php://input');

    echo urldecode($phpInput);

?>

發送普通數據

然後在本地寫一個請求:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?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);     

?>

瀏覽器運行結果是:

1

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請求呢?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?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);     

?>

瀏覽器執行,顯示:

1

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

3. 如何上傳和下載文件

已經和服務器勾搭上了,這時候得要個照片來看一看了吧,你也得把自己的照片發上去讓人看一看了,雖然兩個人在一起外貌不重要,但是男俊女靚總是最棒的。

3.1 傳一張自己的照片過去表表誠意 —— POST上傳文件

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

1

2

3

4

5

6

7

8

9

10

<?php

    if($_FILES){

        $filename = $_FILES['upload']['name'];

          $tmpname = $_FILES['upload']['tmp_name'];

          //保存圖片到當前腳本所在目錄

          if(move_uploaded_file($tmpname,dirname(__FILE__).'/'.$filename)){

            echo ('上傳成功');

          }

    }

?>

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?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及以後的實現,:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?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,現在我要去獲取這張照片。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<?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認證怎麼搞

這個時候呢,服務器的家長說這個我們女兒還太小,不能找對象,就將她女兒關了起來,並且上了一個密碼鎖,所謂的HTTP認證,服務器呢偷偷託信鴿將HTTP認證的用戶名和密碼給了你,要你去見她,帶她私奔。

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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模擬登陸到信息頁面獲取信息,大致的框架是這樣的。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?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)

1

2

3

4

5

6

7

8

9

10

11

//模擬登錄 

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);

}

1

2

3

4

5

6

7

8

9

10

11

//登錄成功後獲取數據 

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開發中最常用的幾種場景做一個整理和歸納。最後一句話,具體問題具體分析。

相關推薦:

php curl帶有csrf-token驗證模擬提交方法

PHP CURL與java http如何使用

php curl錯誤排查的方法詳解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章