PHP imitation asp xmlhttprequest request data code_PHP tutorial
Class name: httprequest($url="",$method="get",$usesocket=0)
//$url is the requested address; the default request method is get; $usesocket defaults to 0, Use the fsockopen method. If set to 1, use the socket_create method
method:
open($ip="",$port=-1) //Open a connection to the same server. By default, you do not need to set these two parameters (when a colleague used it in Linux, he requested an IP that was not resolved by hostname, so he added these two parameters to connect to the real server IP)
settimeout($timeout=0) //Set the method for obtaining data The timeout period must be set before the send method is called to be effective. The unit is seconds. The default value is 0 for no limit.
setrequestheader($key,$value="") //Set the request header and must be set before the send method is called. Valid
removerequestheader($key,$value="") //Remove the request header of the specified key value. It must be called before the send method is called to be valid
send($data="") //Send data $data to server
getresponsebody() //Get the text returned by the server
getallresponseheaders() //Get all header information of the server response
getresponseheader($key) //Get a certain header information of the server response, For example, server, set_cookie, etc.
attributes:
$url //URL to be requested
$method //Request method (post/get)
$port //Requested port
$hostname //The requested host name
$uri //The file part of the url
$protocol //The request protocol (http) (the above 5 attributes including this attribute are automatically analyzed by the program through the url)
$excption //Exception information
$_headers=array() //Request header array("key"=>"value")
$_senddata //Data sent to the server
$status //Returned status code
$statustext //Status information
$httpprotocolversion //The http protocol version of the server
Note: The
host header is automatically set by the program when requesting using the post method , content-length and content-type have been automatically set.
Page that supports gzip compression
inc.http.php tutorial file
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 transfer data
post transfer data> ;
Send source information to the server
Send user-agent to the server< ;/a>
Get the status returned by the server
Get the server response headers
Save image
< ;?php
include("inc_http.php");
$responseurl = "http://dev.mo.cn/aiencode/http/response.asp";$act = isset($_get["action"]) ? $_get["action"] : "";
if($act == "get"){ //get transfer data$myhttp = new httprequest("$responseurl?a=text");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("Hangzhou"));
echo($myhttp->getresponsebody());
}else if($act == "post"){ //Post data$myhttp = new httprequest ("$responseurl?a=text","post");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("Hangzhou") );
echo($myhttp->getresponsebody());
}else if($act == "header_referer"){ //Send source information to the server$myhttp = new httprequest("$responseurl?a=text","post");
$myhttp->open();
$myhttp->setrequestheader("referer","http:/ /www.baidu.com");
$myhttp->send("name=anlige&city=" . urlencode("Hangzhou"));
echo($myhttp->getresponsebody());
}else if($act == "header_useragent"){ //Send user-agent to the server$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("Hangzhou" ));
echo($myhttp->getresponsebody());
}else if($act == "status"){ //Get the status returned by the server$myhttp = new httprequest("$responseurl?a=text","post");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode ("Hangzhou"));
echo($myhttp->status . " " . $myhttp->statustext ."
");
echo( $myhttp->getresponsebody());
}else if($act == "get_headers"){ //Get server response headers$myhttp = new httprequest("$responseurl ?a=text","get");
$myhttp->open();
$myhttp->send("name=anlige&city=" . urlencode("Hangzhou"));
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("}
?>

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.