PHP 要擷取遠端網頁或者傳送 GET 請求可以用 file_get_contents() 函式做, 但如果要發送 POST 請求, 例如自動填寫表單等, 就可以用 CURL 實現。以下 PHP 的 CURL 模組發送 POST 及 GET 的方法:
PHP 傳送 GET 請求
如果只是傳送 GET 請求, 用 file_get_contents() 會較簡單, 只需在網址後面加上 GET 的名稱及值就可以, 例如:
|
1 2 3 4 |
<?php $url = "http://localhost/path.php?get_var=test"; echo file_get_contents($url); ?> |
上面會用 file_get_contents() 函式傳送 GET 請求到 http://localhost/path.php, 名稱是 get_var, 值是 test.
如果用 CURL 是這樣做:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $url = "http://localhost/path.php?get_var=test"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); echo $output; ?> |
PHP 傳送 POST 請求
要用 CURL 多數因為要傳送 POST, 例如自動傳送表單, 以下是簡單例子:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $url = "http://localhost/path.php"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("abc"=>"123", "def"=>"456"))); $output = curl_exec($ch); curl_close($ch); echo $output; ?> |
上面第 6 行用 CURLOPT_POST 宣告啟用 POST 內容, 而第 7 行用到 http_build_query 函式, 將陣列內容轉換成類似 GET 變數的格式, 即 abc=123&def=456。
有種情況是表單禁止用 PHP 等程式傳送, 那便需要用 CURL 自訂 user agent, 只要在 curl_exec 前入這行就可以了:
|
1 |
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0'); |