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" />");
}

?>

时间: 2024-11-08 19:04:29

php 仿asp xmlhttprequest请求数据代码的相关文章

asp横向显示数据代码

<%  sql="select * from serr where order by id asc" set rs=server.createobject("adodb.recordset") rs.open sql,conn,1,1 %><style type="text/css"> <!-- body,td,th { font-size: 12px; } --> </style>  <ta

asp添加数据代码

这是一款简单的asp教程添加数据代码程序,接受用户提交过来的数据,再保存到数据库教程中很方便等的哦,下面来看个详细的说明实例吧. 举例: 如:在字段名处输入:username,password,email,telphone 注意:不同的字段名用英文逗号隔开,且不支持星号 表名处输入要查询的表名:如:table1 生成后的代码是: username = request("username") password = request("password") email =

Jquery异步请求数据实例代码_jquery

一.Jquery向aspx页面请求数据 前台页面JS代码: 复制代码 代码如下: $("#Button1").bind("click", function () { $.ajax({ type: "post", url: "default.aspx", data: "name=" + $("#Text1").val(), success: function (result) { aler

asp.net c#.net Tcp socket 接收数据代码

asp教程.net c#.net tcp socket 接收数据代码  //监听网络          public bool opennet(string sport)        {             processor = new thread(new threadstart(startlistening));//新建监听线程             processor.priority = threadpriority.normal;             processor.

ios 代码 视频-rtmp协议的数据流,在iOS中怎么请求数据,然后怎么播放;求发demo

问题描述 rtmp协议的数据流,在iOS中怎么请求数据,然后怎么播放:求发demo 要做一款直播类的app这个协议以前没用过:在github没找到第三方:很多地方搜了也只说原理:没有代码:求大牛发个demo,感激不尽 解决方案 上面的答案有帮助吗?如果还有问题,请提出来,如果对答案满意,请顶一下,并标记为采纳答案,谢谢! 解决方案二: 开源项目 rtmp-video-player-for-ios

asp.net sqlserver2005数据库存入和读取二进制文件数据代码 该如何实现呢

问题描述 asp.netsqlserver2005数据库存入和读取二进制文件数据代码文件包括pdf文档,.Doc.Excel.Zip.Rar等.该如何实现呢QQ:282617226并提供在线阅读和下载功能. 解决方案 解决方案二:给个e-mail发个源码给你,我公司上不成qq解决方案三:weidazhe@163.com

asp.net生成数据饼图实现代码

在实现数据Pie图之前,首先要确保在C盘的根目录存在"db.mdb"数据库,并且此数据库已经设定完毕,并且存在<在ASP.NET页面中实现数据棒图>一文中的数据.下面是ASP.NET实现数据Pie图的具体步骤,开发工具使用的是Visual Studio .Net,采用的是C#语言. 1. 启动Visual Studio .Net. 2. 选择菜单[文件]|[新建]|[项目]后,弹出[新建项目]对话框. 3. 将[项目类型]设置为[Visual C#项目]. 4. 将[模板]

asp.net中数据excel导入,并马上显示出来。另外还可以导出,求完整代码谢谢

问题描述 asp.net中数据excel导入,并马上gridview显示出来.另外还可以导出为excel,本人刚刚才学习asp.net.求完整代码谢谢. 解决方案 解决方案二:我有,不过贴代码挺麻烦的,我可以通过邮件传给你解决方案三: 解决方案四:能给我也发一份吗?我也正在找这个.谢谢啊!邮箱:766191920@qq.com引用1楼lyy19901101的回复: 我有,不过贴代码挺麻烦的,我可以通过邮件传给你 解决方案五:谢谢了.我的邮箱634585@qq.com解决方案六:yefeng858

asp.net c serialPort显示数据代码

asp教程.net c serialport显示数据代码 //serial port就是所谓的串口,或者串行口.是电脑的接口之一,连接某些设备用的,如果你不需要仔细了解它的话,把它当成跟usb类似的接口就可以了.只是有时候串口不支持热插拔 void comm_datareceived(object sender, serialdatareceivedeventargs e)     {     int n = comm.bytestoread;//先记录下来,避免某种原因,人为的原因,操作几次之