PHP的文件操作函數(shù)幾乎都能用來發(fā)送http
請(qǐng)求:
$html = file_get_contents('http://ww.google.com');
var_dump($html);
有些網(wǎng)站會(huì)對(duì)請(qǐng)求頭信息進(jìn)行檢測(cè),這時(shí)候就需要用到curl
了(php.ini
中要啟用curl
擴(kuò)展),貼一個(gè)我一直用的函數(shù):
function fetch_page($site,$url,$params=false)
{
$ch = curl_init();
$cookieFile = $site . '_cookiejar.txt';
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
if($params)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3');
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
//file_put_contents('jobs.html',$result);
return $result;
}
調(diào)用示例:
$html = fetch_page('google','http://googlel.com','key=value');
var_dump($html);
如果請(qǐng)求類型是https
,則只能用curl
了,前者會(huì)報(bào)(至少默認(rèn)情況下):
PHP Warning: file_get_contents()
: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?
如果你說的實(shí)現(xiàn)https接口指的是讓別人可以用https訪問你,那么就需要用openssl
生成公私鑰,然后編譯apache使支持mod_ssl
,然后再配置httpd-ssl.conf
文件,這些讓系統(tǒng)管理員來做吧。。