php 仿asp xmlhttprequest请求数据代码
类名 :httprequest($url="",$method="get",$usesocket=0)
//$url为请求的地址;默认请求方法为get;$usesocket默认为0,使用fsockopen方法,如果设置为1则使用socket_create方法
方法:
open($ip="",$port=-1) //打开同服务器的连接,默认不用设置这两个参数(一个同事在linux用的时候,请求的不是hostname解析的ip,因此加了这两个参数,以连接真实的服务器ip)
settimeout($timeout=0) //设置获取数据的超时时间,必须在send方法调用之前设置才有效,单位秒,默认值0为不限制
setrequestheader($key,$value="") //设置请求头,必须在send方法调用之前设置才有效
removerequestheader($key,$value="") //移除指定键值的请求头,必须在send方法调用之前调用才有效
send($data="") //发送数据$data到服务器
getresponsebody() //获取服务器返回的文本
getallresponseheaders() //获取服务器响应的所有头信息
getresponseheader($key) //获取服务器响应的某个头信息,例如server,set_cookie等
属性:
$url //要请求的url
$method //请求方法(post/get)
$port //请求的端口
$hostname //请求的主机名
$uri //url的文件部分
$protocol //请求协议(http)(包括本属性的以上5个属性均由程序自动通过url分析)
$excption //异常信息
$_headers=array() //请求头array("key"=>"value")
$_senddata //发送到服务器的数据
$status //返回的状态码
$statustext //状态信息
$httpprotocolversion //服务器的http协议版本
注意:
host头由程序自动设置,当用post方法请求时,content-length和content-type已被自动设置。
支持gzip压缩的页面
inc.http.php教程文件
<?php
class httprequest{
public $url,$method,$port,$hostname,$uri,$protocol,$excption,$_headers=array(),$_senddata,$status,$statustext,$httpprotocolversion;
private $fp=0,$_buffer="",$responsebody,$responseheader,$timeout=0,$usesocket;
//构造函数
function __construct($url="",$method="get",$usesocket=0){
$this->url = $url;
$this->method = strtoupper($method);
$this->usesocket = $usesocket;
$this->setrequestheader("accept","*/*");
$this->setrequestheader("accept-language","zh-cn");
$this->setrequestheader("accept-encoding","gzip, deflate");
$this->setrequestheader("user-agent","httprequest class 1.0"); //可调用setrequestheader来修改
}
//连接服务器
public function open($ip="",$port=-1){
if(!$this->_geturlinfo()) return false;
$this->setrequestheader("host",$this->hostname);
$this->setrequestheader("connection","close");
$ip = ($ip=="" ? $this->hostname : $ip);
$port = ($port==-1 ? $this->port : $port);
if($this->usesocket==1){
if(!$this->fp=$socket=socket_create(af_inet,sock_stream,0)) {
$this->excption="can not create socket";return false;
}else{
if(!socket_connect($this->fp,$ip, $port) ){
$this->excption="can not connect to server " . $this->hostname . " on port" . $this->port;return false;
}
}
}else{
if(!$this->fp=fsockopen($ip, $port,$errno,$errstr,10)) {
$this->excption="can not connect to server " . $this->hostname . " on port" . $this->port;return false;
}
}
return true;
}
public function send($data=""){
if(!$this->fp){$this->excption="is not a resource id";return false;}
if($this->method=="get" && $data!=""){
$s_str="?";
if(strpos($this->uri,"?")>0) $s_str = "&";
$this->uri.= $s_str . $data;
$data="";
}
$senddata=$this->method . " " . $this->uri . " http/1.1rn";
if($this->method=="post"){
$this->setrequestheader("content-length",strlen($data));
$this->setrequestheader("content-type", "application/x-www-form-urlencoded");
}
foreach($this->_headers as $keys => $value){
$senddata .= "$keys: $valuern";
}
$senddata .= "rn";
if($this->method=="post") $senddata .= $data;
$this->_senddata = $senddata;
if($this->usesocket==1){
socket_write($this->fp,$this->_senddata);
$buffer="";
$timestart = time();
do{
if($this->timeout>0){
if(time()-$timestart>$this->timeout){break;}
}
$this->_buffer.=$buffer;
$buffer = socket_read($this->fp,4096);
}while($buffer!="");
socket_close($this->fp);
}else{
fputs($this->fp, $senddata);
$this->_buffer="";
$timestart = time();
while(!feof($this->fp))
{
if($this->timeout>0){
if(time()-$timestart>$this->timeout){break;}
}
$this->_buffer.=fgets($this->fp,4096);
}
fclose($this->fp);
}
$this->_splitcontent();
$this->_getheaderinfo();
}
public function getresponsebody(){
if($this->getresponseheader("content-encoding")=="gzip" && $this->getresponseheader("transfer-encoding")=="chunked"){
return gzdecode_1(transfer_encoding_chunked_decode($this->responsebody));
}else if($this->getresponseheader("content-encoding")=="gzip"){
return gzdecode_1($this->responsebody);
}else{
return $this->responsebody;
}
}
public function getallresponseheaders(){
return $this->responseheader;
}
public function getresponseheader($key){
$key = str_replace("-","-",$key);
$headerstr = $this->responseheader . "rn";
$count = preg_match_all("/n$key:(.+?)r/is",$headerstr,$result,preg_set_order);
if($count>0){
$returnstr="";
foreach($result as $key1=>$value){
if(strtoupper($key)=="set-cookie"){
$value[1] = substr($value[1],0,strpos($value[1],";"));
}
$returnstr .= ltrim($value[1]) . "; ";
}
$returnstr = substr($returnstr,0,strlen($returnstr)-2);
return $returnstr;
}else{return "";}
}
public function settimeout($timeout=0){
$this->timeout = $timeout;
}
public function setrequestheader($key,$value=""){
$this->_headers[$key]=$value;
}
public function removerequestheader($key){
if(count($this->_headers)==0){return;}
$_temp=array();
foreach($this->_headers as $keys => $value){
if($keys!=$key){
$_temp[$keys]=$value;
}
}
$this->_headers = $_temp;
}
//拆分url
private function _geturlinfo(){
$url = $this->url;
$count = preg_match("/^http://([^:/]+?)(:(d+))?/(.+?)$/is",$url,$result);
if($count>0){
$this->uri="/" . $result[4];
}else{
$count = preg_match("/^http://([^:/]+?)(:(d+))?(/)?$/is",$url,$result);
if($count>0){
$this->uri="/";
}
}
if($count>0){
$this->protocol="http";
$this->hostname=$result[1];
if(isset($result[2]) && $result[2]!="") {$this->port=intval($result[3]);}else{$this->port=80;}
return true;
}else{$this->excption="url format error";return false;}
}
private function _splitcontent(){
$this->responseheader="";
$this->responsebody="";
$p1 = strpos($this->_buffer,"rnrn");
if($p1>0){
$this->responseheader = substr($this->_buffer,0,$p1);
if($p1+4<strlen($this->_buffer)){
$this->responsebody = substr($this->_buffer,$p1+4);
}
}
}
private function _getheaderinfo(){
$headerstr = $this->responseheader;
$count = preg_match("/^http/(.+?)s(d+)s(.+?)rn/is",$headerstr,$result);
if($count>0){
$this->httpprotocolversion = $result[1];
$this->status = intval($result[2]);
$this->statustext = $result[3];
}
}
}
//以下两函数参考网络
function gzdecode_1 ($data) {
$data = ($data);
if (!function_exists ( 'gzdecode' )) {
$flags = ord ( substr ( $data, 3, 1 ) );
$headerlen = 10;
$extralen = 0;
$filenamelen = 0;
if ($flags & 4) {
$extralen = unpack ( 'v', substr ( $data, 10, 2 ) );
$extralen = $extralen [1];
$headerlen += 2 + $extralen;
}
if ($flags & 8) // filename
$headerlen = strpos ( $data, chr ( 0 ), $headerlen ) + 1;
if ($flags & 16) // comment
$headerlen = strpos ( $data, chr ( 0 ), $headerlen ) + 1;
if ($flags & 2) // crc at end of file
$headerlen += 2;
$unpacked = @gzinflate ( substr ( $data, $headerlen ) );
if ($unpacked === false)
$unpacked = $data;
return $unpacked;
}else{
return gzdecode($data);
}
}function transfer_encoding_chunked_decode($in) {
$out = "";
while ( $in !="") {
$lf_pos = strpos ( $in, "12" );
if ($lf_pos === false) {
$out .= $in;
break;
}
$chunk_hex = trim ( substr ( $in, 0, $lf_pos ) );
$sc_pos = strpos ( $chunk_hex, ';' );
if ($sc_pos !== false)
$chunk_hex = substr ( $chunk_hex, 0, $sc_pos );
if ($chunk_hex =="") {
$out .= substr ( $in, 0, $lf_pos );
$in = substr ( $in, $lf_pos + 1 );
continue;
}
$chunk_len = hexdec ( $chunk_hex );
if ($chunk_len) {
$out .= substr ( $in, $lf_pos + 1, $chunk_len );
$in = substr ( $in, $lf_pos + 2 + $chunk_len );
} else {
$in = "";
}
}
return $out;
}
function utf8togb($str){
return iconv("utf-8","gbk",$str);
}function gbtoutf8($str){
return iconv("gbk","utf-8",$str);
}
?>
response.asp教程文件
<%
response.cookies("a") = "anlige"
response.cookies("a").expires = dateadd("yyyy",1,now())
response.cookies("b")("c") = "wsdasdadsa"
response.cookies("b")("d") = "ddd"
response.cookies("b").expires = dateadd("yyyy",1,now())
response.write "querystring : " & request.querystring & "<br />"
for each v in request.querystring
response.write v & "=" & request.querystring(v) & "<br />"
next
response.write "<br />form : " & request.form & "<br />"
for each v in request.form
response.write v & "=" & request.form(v) & "<br />"
next
response.write "<br />url : " & request.servervariables("url") & "<br />"
response.write "referer : " & request.servervariables("http_referer") & "<br />"
response.write "host : " & request.servervariables("http_host") & "<br />"
response.write "user-agent : " & request.servervariables("http_user_agent") & "<br />"
response.write "cookie" & request.servervariables("http_cookie")
%>
index.php文件
<a href="?action=get">get传数据</a>
<a href="?action=post">post传数据</a>
<a href="?action=header_referer">向服务器发送来路信息</a>
<a href="?action=header_useragent">向服务器发送user-agent</a>
<a href="?action=status">获取服务器返回的状态</a>
<a href="?action=get_headers">获取服务器响应头</a>
<a href="?action=get_image">保存图片</a><br /><br /><br />
<?php
include("inc_http.php");
$responseurl = "http://dev.mo.cn/aiencode/http/response.asp";$act = isset($_get["action"]) ? $_get["action"] : "";
if($act == "get"){ //get传数据$myhttp = new httprequest("$responseurl?a=text");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("杭州"));
echo($myhttp->getresponsebody());
}else if($act == "post"){ //post传数据$myhttp = new httprequest("$responseurl?a=text","post");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("杭州"));
echo($myhttp->getresponsebody());
}else if($act == "header_referer"){ //向服务器发送来路信息$myhttp = new httprequest("$responseurl?a=text","post");
$myhttp->open();
$myhttp->setrequestheader("referer","http://www.baidu.com");
$myhttp->send("name=anlige&city=" . urlencode("杭州"));
echo($myhttp->getresponsebody());
}else if($act == "header_useragent"){ //向服务器发送user-agent$myhttp = new httprequest("$responseurl?a=text","post");
$myhttp->open();
$myhttp->setrequestheader("referer","http://www.baidu.com");
$myhttp->setrequestheader("user-agent","mozilla/4.0 (compatible; msie 7.0; windows nt 6.0; trident/4.0)");
$myhttp->send("name=anlige&city=" . urlencode("杭州"));
echo($myhttp->getresponsebody());
}else if($act == "status"){ //获取服务器返回的状态$myhttp = new httprequest("$responseurl?a=text","post");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("杭州"));
echo($myhttp->status . " " . $myhttp->statustext ."<br /><br />");
echo($myhttp->getresponsebody());
}else if($act == "get_headers"){ //获取服务器响应头$myhttp = new httprequest("$responseurl?a=text","get");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("杭州"));
echo($myhttp->getallresponseheaders()."<br /><br />");
echo($myhttp->getresponseheader("server")."<br /><br />");
}else if($act == "get_image"){
$myhttp = new httprequest("http://www.baidu.com/img/baidu_logo.gif");
$myhttp->open();
$myhttp->send();
$fp = @fopen("demo.gif","w");
fwrite($fp,$myhttp->getresponsebody());
fclose($fp);
echo("<img src="demo.gif" />");
}
?>
php教程自动获取关键字代码
$mincipin=5;//最小词频
$minlen=4;//关键字最小长度
tiqukeyword($tiqustr,$minlen,$mincipin);
function tiqukeyword($tiqustr,$minlen,$mincipin)
{$strlong=strlen($tiqustr);
$arr=array();
$k=-1;
for($i=0;$i<($strlong-$mincipin*$minlen);$i++){
$end=ceil(($strlong-$i)/$mincipin+$i);
for($j=$minlen;$j<$end;$j++){$num=0;
if(($guanjianzi=substr($tiqustr,$i,$j))!==false){
$wz=$i+$j;
$num++;}
else{break;}
while($wz<$strlong){if(($wz=strpos($tiqustr,$guanjianzi,$wz))!==false)
{$num++;
$wz=$wz+strlen($guanjianzi);}
else break;
}
if($j==$minlen){
if($num>=$mincipin){$maxnum=$num;$k++;$str=substr($tiqustr,$i,$j);
$arr[$k]=array($i,$j,$str,$num,0);
}
else{break;}
}else{
if($num>=$maxnum){
$maxnum=$num;
$str=substr($tiqustr,$i,$j);
$arr[$k]=array($i,$j,$str,$num,0);
}
else break;
}
}}
echo '初步得到的数组:';
print_r($arr);
//echo '<br/><br/><br/><br/>';
$arrlong=count($arr);
for($i=0;$i<$arrlong;$i++){
$bjarr=$arr[$i];
$nowid=$i;
if($bjarr[4]==1)continue;
for($j=$i+1;$j<$arrlong;$j++){
if($arr[$j][4]==1)continue;
$qujianks=$bjarr[0];
$qujianjs=$bjarr[1]+$bjarr[0]-1;
$a=$arr[$j][0];
$b=$arr[$j][1]+$arr[$j][0]-1;
if(($bjarr[2]==$arr[$j][2])&&($bjarr[3]>$arr[$j][3]))$arr[$j][4]=1;
if($a<=$qujianks&&$qujianks<=$b&&$a<=$qujianjs&&$qujianjs<=$b)
{if($bjarr[3]<=$arr[$j][3]){
$arr[$nowid][4]=1;$nowid=$j;$bjarr=$arr[$j];
}
}elseif($qujianks<=$a&&$a<=$qujianjs&&$qujianks<=$b&&$b<=$qujianjs){
$arr[$j][4]=1;
}}
}
echo '<br/><br/><br/><br/>重叠加标记后的数组:';
print_r($arr);
$jieguoarr=array();
for($i=0;$i<$arrlong;$i++)
{if($arr[$i][4]==0)$jieguoarr[]=$arr[$i];
}
echo '<br/><br/><br/><br/>';
echo '最后得到的数组:';
print_r($jieguoarr);
}
php教程文件缓存实例代码
缓存在实际使用当中应用很广泛,可以减轻对服务器数据库教程的访问,提高运行速度。目前很多cms内容管理系统中频繁使用缓存机制来提高系统运行的效率
cache.php 代码如下:
php代码
<?
/*
用户需要事先定义的常量:
_cachepath_ 模板缓存路径
_cacheenable_ 自动缓存机制是否开启,未定义或为空,表示关闭自动缓存机制
_recachetime_ 自动重新缓存间隔时间,单位为秒,未定义或为空,表示关闭自动重新缓存
*/
class cache {
var $cachefile;
var $cachefilevar;
function cache() {
//生成当前页的cache组文件名 $this->cachefilevar 及文件名 $this->cachefile
//动态页的参数不同对应的cache文件也不同,但是每一个动态页的所有cache文件都有相同的文件名,只是扩展名不同
$s=array(".","/");$r=array("_","");
$this->cachefilevar=str_replace($s,$r,$_server["script_name"])."_".$_get[_actionvar_];
$this->cachefile=$this->cachefilevar.".".md5($_server["request_uri"]);
}
//删除当前页/模块的缓存
function delete() {
//删除当前页的缓存
$d = dir(_cachepath_);
$strlen=strlen($this->cachefilevar);
//返回当前页的所有cache文件组
while (false !== ($entry = $d->read())) {
if (substr($entry,0,$strlen)==$this->cachefilevar) {
if (!unlink(_cachepath_."/".$entry)) {echo "cache目录无法写入";exit;}
}
}
}
//判断是否已cache过,以及是否需要cache
function check() {
//如果设置了缓存更新间隔时间 _recachetime_
if (_recachetime_+0>0) {
//返回当前页cache的最后更新时间
$var=@file(_cachepath_."/".$this->cachefilevar);$var=$var[0];
//如果更新时间超出更新间隔时间则删除cache文件
if (time()-$var>_recachetime_) {
$this->delete();$ischage=true;
}
}
//返回当前页的cache
$file=_cachepath_."/".$this->cachefile;
//判断当前页cache是否存在 且 cache功能是否开启
return (file_exists($file) and _cacheenable_ and !$ischange);
}
//读取cache
function read() {
//返回当前页的cache
$file=_cachepath_."/".$this->cachefile;
//读取cache文件的内容
if (_cacheenable_) return readfile($file);
else return false;
}
//生成cache
function write($output) {
//返回当前页的cache
$file=_cachepath_."/".$this->cachefile;
//如果cache功能开启
if (_cacheenable_) {
//把输出的内容写入cache文件
fopen($file,'w'">$fp=@fopen($file,'w');
if (!@fputs($fp,$output)) {echo "模板cache写入失败";exit;}
@fclose($fp);
//如果设置了缓存更新间隔时间 _recachetime_
if (_recachetime_+0>0) {
//更新当前页cache的最后更新时间
$file=_cachepath_."/".$this->cachefilevar;
$fp=@fopen($file,'w');
if (!@fwrite($fp,time())) {echo "cache目录无法写入";exit;}
@fclose($fp);
}
}
}
}
?>
使用过程:
php代码
<?php
define("_cachepath_","./cache/");
define("_cacheenable_","1");
define("_recachetime_","43200");
include('cache.php');
$cache=new cache();
if ($cache->check()) {
$template=$cache->read();
}else {
ob_start();
ob_implicit_flush(0);
?>
页面内容。。。。
<?php
$template = ob_get_contents();
$cache->write($template);
}
?>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>关键字百度排名批量查</title>
<base target="_blank" />
<meta http-equiv="x-ua-compatible" content="ie=emulateie7" />
<style type="text/css教程">
body{margin:0;padding:0;background:#fff;color:#000;font:12px 微软雅黑, verdana, tahoma, lucida grande, arial, sans-serif;text-align:center;}
#wrapper{width:990px;margin:0 auto;line-height:20px;text-align:left;}
#header,#main,#footer{clear:both;float:left;margin:10px 0 0 0;width:100%;}
a,a:visited{color:#0196e3;text-decoration:none;}
form{margin:10px;}
.kinput{width:300px;margin:0 5px;padding:2px;text-align:left;border:1px solid #ccc;font-weight:bold;}
.kbutton{width:80px;margin:0 5px;padding:2px;height:20px;}
#kgrid{float:left;width:100%;}
.s_kw,.s_rank,.s_wt,.s_title,.s_cache,.s_feng,.s_baidu,.s_mu{float:left;height:30px;line-height:30px;overflow:hidden;text-align:left;border:1px solid #c2d5e3;}
.s_bar{clear:both;float:left;width:100%;height:30px;line-height:30px;text-align:center;}
.s_kw{clear:both;width:120px;}
.s_rank{width:30px;}
.s_wt{width:50px;color:#0e774a;}
.s_title{width:340px;}
.s_cache{width:80px;}
.s_feng{width:80px;}
.s_baidu{width:150px;}
.s_mu{width:120px;}
</style>
</head><body>
<div id="wrapper">
<?php教程
function tongji()
{
$myhost = $_server['http_host'];
if (preg_match("/(www.)?baiek.com/i", $myhost, $myout))
{
echo '<script language="网页特效" type="text/javascript" src="http://js.users.51.la/4295418.js"></script>';
}
}function libxml_display_error($error)
{
$return = "<br/>n";
switch ($error->level)
{
case libxml_err_warning:
$return .= "<b>warning $error->code</b>: ";
break;
case libxml_err_error:
$return .= "<b>error $error->code</b>: ";
break;
case libxml_err_fatal:
$return .= "<b>fatal error $error->code</b>: ";
break;
}
$return .= trim($error->message);
if ($error->file)
{
$return .= " in <b>$error->file</b>";
}
$return .= " on line <b>$error->line</b>n";
return $return;
}function libxml_display_errors()
{
$errors = libxml_get_errors();
foreach ($errors as $error)
{
print libxml_display_error($error);
}
libxml_clear_errors();
}$kfname = '';
if (isset($_get['kf']))
{
$kfname = trim($_get['kf']);
}
$version = '<script language="javascript" type="text/javascript" src="http://www.111cn.net/version.js"></script>';
echo <<< eoth
<div id="header">
做企业站或认识企业站的朋友,请支持一下我的小站 <a href="http://www.198114.com/"><b>198114产品企业分类目录</b></a>,多谢多谢!!
<a href="http://www.111cn.net/" target="_self"><h1>关键字百度排名批量查询(php网页版) baiek.com</h1></a>
<form method="get" target="_self">
<input id="kf" name="kf" type="text" class="kinput" value="{$kfname}" />
<input id="submitbtn" type="submit" class="kbutton" value="批量查询" />
 <a href="http://www.111cn.net/baiek.rar" target="_self"><b>点击此处下载(更新于{$version})</b></a>
 在线演示:<a href="http://www.111cn.net/?kf=kw1.xml" target="_self">演示1</a> <a href="http://www.111cn.net/?kf=kw2.xml" target="_self">演示2</a> <a href="http://www.111cn.net/?kf=kw3.xml" target="_self">演示3</a>
</form>
</div>eoth;
if (!file_exists($kfname) || !is_readable($kfname))
{
tongji();
exit('请输入正确的关键字清单文件(xml格式,请参考<a href="http://www.111cn.net/readme.txt">readme</a>文件)!!');
}
libxml_use_internal_errors(true);
$doc = new domdocument();
$doc->load($kfname);
if (!$doc->schemavalidate('kw.xsd'))
{
print '<b>关键字列表xml文件发现错误!</b>';
libxml_display_errors();
tongji();
exit;
}//由xml文件提取关键字列表与相应的域名
$kwlist = array(); $g = 1;
$kgroups教程 = $doc->getelementsbytagname("kgroup");
foreach ($kgroups as $kgroup)
{
$kwlist[$g]['domain'] = trim($kgroup->getelementsbytagname("kdomain")->item(0)->nodevalue);
$kwords = $kgroup->getelementsbytagname("kword");
$w = 1;
foreach ($kwords as $kword)
{
if ($kword->haschildnodes())
{
$kwlist[$g]['kword'][$w] = trim($kword->firstchild->nodevalue);
}
$w++;
}
$g++;
}
?>
<div id="main">
<?php
function get_dm_weight($h, $i)
{
//$h表示搜索结果的url,$i表示结果排名
$p = ceil($i / 10); //搜索结果第几页
$i_weight = array(1 => 52, 2 => 15, 3 => 10, 4 => 5, 5 => 5, 6 => 4, 7 => 1, 8 => 3, 9 => 2, 0 => 3);
$h_str = preg_replace("/^.*?://(.*?)(#.*)?$/i", "$1$3", $h); //去除url中的协议(例如http)与#信息片段部分
$h_arr = explode("?", $h_str, 2);
$h0_arr = explode("/", $h_arr[0]);
if ($h0_arr[count($h0_arr) - 1] == '')
{
$level_l = count($h0_arr) - 1;
}
else
{
$level_l = count($h0_arr);
}
if (isset($h_arr[1]))
{
if ($h_arr[1] != '')
{
$level_r = count(explode("&", $h_arr[1]));
}
else
{
$level_r = 0;
}
}
else
{
$level_r = 0;
}
$dw = $i_weight[$i % 10] * pow(0.5, ($level_l + $level_r - 1)) * 9 / pow(10, $p);
return number_format($dw, 1);;
}function fetch_baidu($d, $k)
{
$urlw = urlencode(iconv("utf-8","gbk//ignore",$k));
$max_srh_page = 2; //百度搜索结果50条/页,提取2页,也就是只在前100条搜索结果中检查排名,最大值可以设为16
$baidu_ids = array(); //存储百度系列子站点占据的排名位置
$baidu_mus = array(); //存储百度开放平台等优质站点占据的排名位置
$isrank = 0; //$isrank = 1 当前域名下这个关键词获得排名; $isrank = 0 当前域名下这个关键词没有排名
$all_count = 0; //测试变量,以确认匹配规则不会遗漏任何一条搜索结果
$dm_weight = 0; //分析搜索结果页面中顶级、次级、目录、内页的情况,粗略反映一个关键字的竞争激烈程度,非常不准,仅供参考
for ($page_no = 1; $page_no <= $max_srh_page; $page_no++)
{
if ($page_no > 16) break;
$fail_try = 1;
$pn = ($page_no - 1) * 50;
$url = "http://www.baidu.com/s?wd={$urlw}&pn={$pn}&rn=50";
$snoopy = new snoopy;
// $snoopy->proxy_host = "127.0.0.1"; //采集可选代理ip,以免频繁抓百度反被百度咬
// $snoopy->proxy_port = "80"; //proxy代理所用端口
$snoopy->fetch($url);
$contents = iconv("gbk","utf-8//ignore",$snoopy->results);
unset($snoopy);
// echo $contents;
if (!preg_match("/<span>此内容系百度根据您的指令自动搜索的结果/i",$contents,$out))
{
if ($fail_try > 5)
{
continue;
}
else
{
$fail_try++;
$page_no--;
sleep(30);
continue;
}
}
if (!isset($ebaidu))
{
$ebaidu = array('lt' => 0, 'lb' => 0, 'r' => 0); //记录百度推广数量,分为左上、左下、右侧
if (preg_match_all("/<tr><td class="f ec_pp"><a id="awd+"/i", $contents, $out_lt))
{
$ebaidu['lt'] = count($out_lt[0]);
}
if (preg_match_all("/<table id="40d+".*?class="ec_mr15">/i", $contents, $out_lt))
{
$ebaidu['lt'] = count($out_lt[0]);
}
if (preg_match_all("/<table width="65%".*?class="ec_mr15">/i", $contents, $out_lb))
{
$ebaidu['lb'] = count($out_lb[0]);
}
if (preg_match_all("/<div id="bdfsd+" class="ec_pp".*?><a id=dfsd+/i", $contents, $out_r))
{
$ebaidu['r'] = count($out_r[0]);
}
}
if (preg_match_all("/((<table cellpadding="0" cellspacing="0".*?id="(d+)" mu="(.*?)">)|(<table id="(d+)" cellpadding="0" cellspacing="0" mu="(.*?)">))[s|s]*?((<a.*?href=".*?".*?>(.*?)</a>)|(<div id="app_.*?"></div>))/i", $contents, $out_mu))
{
foreach ($out_mu[0] as $om_key => $om_val)
{
$om_id1 = $out_mu[3][$om_key];
$om_href1 = $out_mu[4][$om_key];
$om_id2 = $out_mu[6][$om_key];
$om_href2 = $out_mu[7][$om_key];
$om_title = strip_tags($out_mu[10][$om_key]);
$baidu_mus[] = $om_id1 . $om_id2;
$dm_weight = $dm_weight + get_dm_weight($om_href1 . $om_href2, $om_id1 . $om_id2);
if (preg_match("/://(w*?.)*?baidu.com//i", $om_href1 . $om_href2, $om_domain))
{
$baidu_ids[] = $om_id1 . $om_id2;
}
if (preg_match("/://(w*?.)*?{$d}//i", $om_href1 . $om_href2, $om_domain))
{
echo '<div style="clear:both"></div><span class="s_kw"><a href="http://www.baidu.com/s?wd=' . $urlw . '">' . $k . '</a></span><span class="s_rank">' . $om_id1 . $om_id2 . '</span><span class="s_wt"></span><span class="s_title"><a href="' . $om_href1 . $om_href2 . '">' . $om_title . '</a></span><span class="s_cache"></span>';
$isrank = 1;
}
}
}
if (preg_match_all("/<table cellpadding="0" cellspacing="0" class="result" id="(d+)"><tr><td class=f><h3 class="t">(<font.*?</font>)?<a.*?href="(.*?)" target="_blank">(.*?)</a></h3><font size=-1>.*?<span class="g">.*? ((d{4}-d{1,2}-d{1,2})|(d+小时前)|(d+分钟前)) .*?</span>.*?<br></font></td></tr></table>/i", $contents, $out_all))
{
foreach ($out_all[0] as $o_key => $o_val)
{
$o_id = $out_all[1][$o_key];
$o_href = $out_all[3][$o_key];
$o_title = strip_tags($out_all[4][$o_key]);
$o_cache = $out_all[6][$o_key] . $out_all[7][$o_key] . $out_all[8][$o_key];
$dm_weight = $dm_weight + get_dm_weight($o_href, $o_id);
if (preg_match("/://(w*?.)*?baidu.com//i", $o_href, $o_domain))
{
$baidu_ids[] = $o_id;
}
if (preg_match("/://(w*?.)*?{$d}//i", $o_href, $o_domain))
{
echo '<div style="clear:both"></div><span class="s_kw"><a href="http://www.baidu.com/s?wd=' . $urlw . '">' . $k . '</a></span><span class="s_rank">' . $o_id . '</span><span class="s_wt">' . $dm_weight . '%</span><span class="s_title"><a href="' . $o_href . '">' . $o_title . '</a></span><span class="s_cache">' . $o_cache . '</span>';
$isrank = 1;
}
}
}
//$all_count用来检查上述正则匹配是否匹配到所有搜索结果,特别关注百度系列站点、百度开放平台以及百度应用等有别于普通搜索结果
if (isset($out_mu[0])) $all_count = $all_count + count($out_mu[0]);
if (isset($out_all[0])) $all_count = $all_count + count($out_all[0]);
// echo '<br />总共找到' . $all_count . '个匹配<br />';
if (!preg_match("/<a href="s?wd=.*?>下一页</a>.*?</p>/i",$contents,$out))
{
break;
}
}
if (count($baidu_mus) >= 1)
{
$bmus = implode(",", $baidu_mus);
}
else
{
$bmus = '';
}
if (count($baidu_ids) >= 1)
{
$bids = implode(",", $baidu_ids);
}
else
{
$bids = '';
}
if ($isrank == 1)
{
echo '<span class="s_feng">上' . $ebaidu['lt'] . '下' . $ebaidu['lb'] . '右' . $ebaidu['r'] . '</span><span class="s_baidu">' . $bids . '</span><span class="s_mu">' . $bmus . '</span>';
}
else
{
echo '<div style="clear:both"></div><span class="s_kw"><a href="http://www.baidu.com/s?wd=' . $urlw . '">' . $k . '</a></span><span class="s_rank">0</span><span class="s_wt">' . $dm_weight . '%</span><span class="s_title"></span><span class="s_cache"></span><span class="s_feng">上' . $ebaidu['lt'] . '下' . $ebaidu['lb'] . '右' . $ebaidu['r'] . '</span><span class="s_baidu">' . $bids . '</span><span class="s_mu">' . $bmus . '</span>';
}
unset($ebaidu);
}
//逐个域名与关键字采集百度排名信息并显示
set_include_path(".");
include "snoopy.class.php";
set_time_limit(0);
ob_flush(); flush(); ob_end_clean(); ob_implicit_flush(1);
echo '<div id="kgrid">';
echo '<span class="s_kw">关键字</span><span class="s_rank">排名</span><span class="s_wt">竞争度</span><span class="s_title">网页标题</span><span class="s_cache">百度快照</span><span class="s_feng">百度推广数量</span><span class="s_baidu">百度占位</span><span class="s_mu">百度mu占位</span>';
foreach ($kwlist as $d_ks)
{
$dm = $d_ks['domain'];
echo '<div style="clear:both"></div><span class="s_bar">域名:' . $dm . '</span>';
foreach ($d_ks['kword'] as $k)
{
fetch_baidu($dm, $k);
}
}
echo '</div>';
?>
</div><!--div main end-->
</div><!--div wrap end-->
<?php
tongji();
?>
</body>
</html>
ajax php教程仿网易文章评论顶一下效果
<div class='plding fr'>
<a href='action.php?id="1&action=top_num'>顶一下</a>[5]
</div>
js ajax
<script language="网页特效" type="text/javascript">
<!--
// ajax检测评论是否已经支持过了
function getcookie(c_name){ //检测cookie
if (document.cookie.length>0){
c_start=document.cookie.indexof(c_name + "=")
if(c_start!=-1){
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexof(";",c_start);
if(c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}function setcookie(c_name,value,expiredays){ //设置cookie
var exdate=new date();
exdate.setdate(exdate.getdate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.togmtstring());
}function createxmlhttprequest(){ //创建xmlhttprequest对象
if(window.activexobject){ //ie
try {
return new activexobject("microsoft.xmlhttp");
} catch(e){
return;
}
}else if(window.xmlhttprequest){ //mozilla,firefox
try {
return new xmlhttprequest();
} catch(e){
return;
}
}
}function get_top_num(id){ //主调函数
var get_top_cookie=getcookie('get_top_'+id+'_cookie');
if(get_top_cookie!=null && get_top_cookie!=""){
alert('此条评论你已经支持过了');
}
else{
var xmlhttp=createxmlhttprequest();
var url = "action.php?action=top_num&id="+id;
if (id==""){
return false ;
}
if (xmlhttp){
callback = getreadystatehandler(xmlhttp,id);
xmlhttp.onreadystatechange = callback;
xmlhttp.open("get", url,true);
xmlhttp.send(null);
}
setcookie('get_top_'+id+'_cookie','istop',1);
}
}function getreadystatehandler(xmlhttp,id){ //服务器返回后处理函数
var top_num = document.getelementbyid("top_num_"+id).innerhtml;
return function (){
if(xmlhttp.readystate == 4){
if(xmlhttp.status == 200){
if (xmlhttp.responsetext==1){
document.getelementbyid("top_num_"+id).innerhtml=number(top_num)+1;
}
}
}
}
}//-->
</script>
相关文章
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
- 这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
Antd-vue Table组件添加Click事件,实现点击某行数据教程
这篇文章主要介绍了Antd-vue Table组件添加Click事件,实现点击某行数据教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-17- 这篇文章主要介绍了详解如何清理redis集群的所有数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-18
- 有一种方法,可以不打开网站而直接查看到这个网站的源代码.. 这样可以有效地防止误入恶意网站... 在浏览器地址栏输入: view-source:http://...2016-09-20
- <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
- 这篇文章主要介绍了vue 获取到数据但却渲染不到页面上的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-19
- 本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
- 本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
- 本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
- 在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
- php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
- 这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18
- php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p> </p> <p> </p> <form name="form1...2016-11-25
- 公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
- 这篇文章主要介绍了postgresql数据添加两个字段联合唯一的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-04
如何在Spring WebFlux的任何地方获取Request对象
这篇文章主要介绍了如何在Spring WebFlux的任何地方获取Request对象,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下...2021-01-26- 本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
- 其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08