php 仿asp xmlhttprequest请求数据代码_PHP教程
类名 :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教程文件
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_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 & "
"
for each v in request.querystring
response.write v & "=" & request.querystring(v) & "
"
next
response.write "
form : " & request.form & "
"
for each v in request.form
response.write v & "=" & request.form(v) & "
"
next
response.write "
url : " & request.servervariables("url") & "
"
response.write "referer : " & request.servervariables("http_referer") & "
"
response.write "host : " & request.servervariables("http_host") & "
"
response.write "user-agent : " & request.servervariables("http_user_agent") & "
"
response.write "cookie" & request.servervariables("http_cookie")
%>
index.php文件
get传数据
post传数据
向服务器发送来路信息
向服务器发送user-agent
获取服务器返回的状态
获取服务器响应头
保存图片
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 ."
");
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()."
");
echo($myhttp->getresponseheader("server")."
");
}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("");
}
?>

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.
