: This article mainly introduces the source code for simulating ajax requests using PHP. For more information about PHP tutorials, see. I have tried it and it is very useful.
/*** Construct ajax requests. https */functionajax_http_request ($ url, $ data = array (), $ type = "post", $ params = array (), $ accept = "", $ ua = "", $ referer = "", $ file = false) {$ http = strtolower (substr ($ url, 0, 7 )); $ type = strtolower ($ type); $ url_params = parse_url ($ url); if (! $ Url_params) {echo 'URL error'; returnfalse;} $ hostip = gethostbyname ($ url_params ['host']); if (! $ Hostip) {echo 'server inaccessible '; returnfalse;} $ fp = fsockopen ($ url_params ['host'], 80, $ errno, $ errstr, 30 ); if (! $ Fp) {echo "$ errstr ($ errno)
"; Returnfalse;} $ query_string = http_build_query ($ data); if ($ type = 'post') {$ out = 'post '. $ url_params ['path']. "HTTP/1.1 \ r \ n";} else {if (strpos ($ url ,'? ')! = False) {$ path = $ url. '&'. $ query_string;} else {$ path = $ url .'? '. $ Query_string;} $ out = 'get '. $ path. 'HTTP/1.1 '. "\ r \ n" ;}$ out. = 'host :'. $ url_params ['host']. "\ r \ n"; $ out. = "Connection: Close \ r \ n"; if ($ type = 'post') {if ($ file) {$ out. = ("Content-Type: multipart/form-data \ r \ n"); // This function is not available for ajax file uploads Currently} else {$ out. = ("Content-Type: application/x-www-form-urlencoded \ r \ n");} $ out. = ("Content-Length :". strlen ($ query_string ). "\ r \ n");} if (isset ($ ua) {$ Out. = ('User-Agent :'. $ ua. "\ r \ n");} else {$ out. = ("User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) chrome/41.0.2272.118 Safari/537.36 \ r \ n ");} if (isset ($ referer) {$ out. = ('referer: http ://'. $ url_params ['host']. '/'. $ referer. "\ r \ n");} else {$ out. = ('referer: http ://'. $ url_params ['host']. "\ r \ n");} $ out. = ("Origin: http ://". $ url_params ['H Ost']. "\ r \ n"); $ out. = ("X-Requested-With: XMLHttpRequest \ r \ n"); $ out. = ("Accept: application/json, text/javascript, */* \ r \ n"); $ out. = "Accept-Language: zh-CN, zh; q = 0.8, en; q = 0.6 \ r \ n "; if ($ type = 'post') {// Next is the message body information $ out. = $ query_string;} fwrite ($ fp, $ out); $ output = ""; while (! Feof ($ fp) {$ output. = fgets ($ fp, 128);} fclose ($ fp); $ result = explode ("\ r \ n", $ output ); $ result = explode ("\ r \ n", $ result [1]); array_pop ($ result); array_shift ($ result ); return implode ("\ r \ n", $ result );}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.
The above describes the source code for simulating ajax requests using PHP, including the relevant content, and hope to be helpful to friends who are interested in PHP tutorials.