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