Simulate HTTP requests and support gzip and chunked formats
Last Update:2018-12-05
Source: Internet
Author: User
<? PHP
/**
* Simulate HTTP requests. gzip and chunked formats are supported.
*
*/
Function http_request ($ URL)
{
$ Urlinfo = parse_url ($ URL );
$ Urlinfo ['path'] = $ urlinfo ['path']! = ''? $ Urlinfo ['path']: '/';
$ Header = "get {$ urlinefo ['path']} HTTP/1.1/R/N ";
$ Header. = "accept: */R/N ";
$ Header. = "Accept-language: ZH-CN/R/N ";
$ Header. = "UA-CPU: x86/R/N ";
$ Header. = "Accept-encoding: gzip, deflate/R/N ";
$ Header. = "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;. Net CLR 2.0.50727; CBA)/R/N ";
$ Header. = "Host: {$ urlinfo ['host']}/R/N ";
$ Header. = "connection: Close/R/N ";
$ Header. = "/R/N ";
$ Header. = "/R/N"; $ fp = fsockopen ($ urlinfo ['host'], isset ($ urlinfo ['Port'])? $ Urlinfo ['Port']: 80, $ errno, $ errstr, 10 );
If (! $ FP)
{
Echo $ errno. $ errstr;
Return false;
}
Fwrite ($ FP, $ header );
$ Head = read_header ($ FP );
$ Content = read_content ($ FP, $ head );
Return $ content;
}
Function read_header ($ FP)
{
$ Header = '';
While (TRIM ($ line = fgets ($ FP, 1024 ))! = "")
{
$ Header. = $ line;
}
Return $ header;
}
Function read_content ($ FP, $ head = '')
{
If (! Strpos ($ head, '2014, 200 OK '))
{
Return false;
}
$ Content = '';
// Only chunked needs to be segmented.
If (strpos ($ head, 'chunk '))
{
$ Chunk_size = chop (fgets ($ FP, 1024 ));
$ Chunk_size = hexdec ($ chunk_size );
$ Block_size = 0;
While (! Feof ($ FP ))
{
// $ Line = fread ($ FP, $ chunk_size );
// Die ($ chunk_size. ":". strlen ($ Line). ':'. bin2hex ($ line); break;
// Output 7873: 2360. fread should have read 7873, and the result is read-only 2360.
If ($ block_size & lt; $ chunk_size)
{
$ Content. = fgetc ($ FP );
$ Block_size ++;
}
Else
{
Echo fread ($ FP, 2 );
$ Chunk_size = hexdec (chopped (fgets ($ FP, 1024 )));
$ Block_size = 0;
// Echo "***** chunk_size: $ chunk_size *****";
If ($ chunk_size = 0)
{
Fclose ($ FP); break;
}
}
}
}
Else
{
// Common Code
While (! Feof ($ FP ))
{
$ Content. = fgetc ($ FP );
}
}
// After N tests, I still cannot use temporary files. Do not understand.
$ Tmpfile = tempnam ('/tmp', 'webcache ');
$ Fp = fopen ($ tmpfile, 'w ');
Fwrite ($ FP, $ content );
Fclose ($ FP );
Ob_start ();
Readgzfile ($ tmpfile );
$ Content = ob_get_contents ();
Ob_end_clean ();
Unlink ($ tmpfile );
Return $ content;
}
?>