我们在使用站长工具会发现有一个获取网站http状态信息了,其实这个功能使用php非常的简单的,我们可以使用curl来实现下面来看一些整理的例子.
使用curl需要在php.ini中设置启用才行 >
extension=php_curl.dll 去掉前面的注释既可.
实现代码如下:
$curl = curl_init(); $url=’http://www.phprm.com’; curl_setopt($curl, curlopt_url, $url); //设置url curl_setopt($curl, curlopt_header, 1); //获取header curl_setopt($curl,curlopt_nobody,true); //body就不要了吧,我们只是需要head curl_setopt($curl, curlopt_returntransfer, 1); //数据存到成字符串吧,别给我直接输出到屏幕了 $data = curl_exec($curl); //开始执行啦~ echo curl_getinfo($curl,curlinfo_http_code); //我知道httpstat码哦~ curl_close($curl); //用完记得关掉他
或者直接使用get_headers函数,get_headers — 取得服务器响应一个 http 请求所发送的所有标头,例子代码如下:
在php中我们如果要取得数据、模拟登陆、post数据等功能第一个想到的肯定是curl函数了,这个函数方便实用并且还可以多线程了下面整理了一个例子,有兴趣的朋友可参考.
例子,使用php curl获取网页数据的方法,代码如下:
syxrrrr,pw => 123456);$ch = curl_init();curl_setopt($ch, curlopt_url, $url);curl_setopt($ch, curlopt_returntransfer, 1);curl_setopt($ch, curlopt_post, 1);curl_setopt($ch, curlopt_postfields, $post_data);$output = curl_exec($ch);curl_close($ch);echo $output;
取得数据、模拟登陆、post数据, 代码如下:
/********************** curl 系列 ***********************///直接通过curl方式取得数据(包含post、header等)/* * $url: 如果非数组,则为http;如是数组,则为https * $header: 头文件 * $post: post方式提交 array形式 * $cookies: 0默认无cookie,1为设置,2为获取*/public function curl_allinfo($urls, $header = false, $post = false, $cookies = 0) { $url = is_array($urls) ? $urls['0'] : $urls; $ch = curl_init(); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_returntransfer, 1); //带header方式提交 if ($header != false) { curl_setopt($ch, curlopt_httpheader, $header); } //post提交方式 if ($post != false) { curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields, $post);}if ($cookies == 1) { curl_setopt($ch, curlopt_cookiejar, cookiefile);} else if ($cookies == 2) { curl_setopt($ch, curlopt_cookiefile, cookiefile);}if (is_array($urls)) { curl_setopt($ch, curlopt_ssl_verifypeer, false); curl_setopt($ch, curlopt_ssl_verifyhost, false);}$data = curl_exec($ch);curl_close($ch);return $data;}
最后附一个模仿搜索引擎蜘蛛来抓取网页, 代码如下:
function get_web_page($url) { $options = array( curlopt_returntransfer => true, // return web page 返回网页 curlopt_header => false, // 不返回头信息 curlopt_followlocation => true, // follow redirects curlopt_encoding => , // handle all encodings curlopt_useragent => spider, // 设置useragent curlopt_autoreferer => true, // set referer on redirect curlopt_connecttimeout => 120, // timeout on connect 连接超时 curlopt_timeout => 120, // timeout on response 回复超时 curlopt_maxredirs => 10, // stop after 10 redirects ); $ch = curl_init($url); curl_setopt_array($ch, $options); $content = curl_exec($ch); $err = curl_errno($ch); $errmsg = curl_error($ch); $header = curl_getinfo($ch); curl_close($ch); $header[''errno''] = $err; $header[''errmsg''] = $errmsg; $header[''content''] = $content; return $header;}
本文链接:
收藏随意^^请保留教程地址.