This article mainly introduces how php uses the fsockopen function to send post and get requests to obtain webpage content. it is a typical PHP application of socket programming, for more information about how php uses the fsockopen function to send a post request and get the webpage content, see the example in this article. Share it with you for your reference.
The specific implementation code is as follows:
The code is as follows:
$ Post = 1;
$ Url = parse_url ($ url );
$ Host = 'http: // www.jb51.net ';
$ Path = '/';
$ Query = '? Action = phpfensi.com ';
$ Port = 80;
If ($ post ){
$ Out = "post $ path http/1.0 ";
$ Out. = "accept :*/*";
// $ Out. = "referer: $ boardurl ";
$ Out. = "accept-language: zh-cn ";
$ Out. = "content-type: application/x-www-form-urlencoded ";
$ Out. = "user-agent: $ _ server [http_user_agent]";
$ Out. = "host: $ host ";
$ Out. = 'content-length: '. strlen ($ post )."";
$ Out. = "connection: close ";
$ Out. = "cache-control: no-cache ";
$ Out. = "cookie: $ cookie ";
$ Out. = $ post;
} Else {
$ Out = "get $ path http/1.0 ";
$ Out. = "accept :*/*";
// $ Out. = "referer: $ boardurl ";
$ Out. = "accept-language: zh-cn ";
$ Out. = "user-agent: $ _ server [http_user_agent]";
$ Out. = "host: $ host ";
$ Out. = "connection: close ";
$ Out. = "cookie: $ cookie ";
}
$ Fp = @ fsockopen ($ ip? $ Ip: $ host), $ port, $ errno, $ errstr, $ timeout );
If (! $ Fp)
{
Return ''; // note $ errstr: $ errno
} Else {
Return 'Access successful ';
}
Fsockopen syntax:
The code is as follows:
Resource fsockopen (string $ hostname [, int $ port =-1 [, int & $ errno [, string & $ errstr [, float $ timeout = ini_get ("default_socket_timeout")])
Start a socket to connect to the resources of the specified host. php supports the targets in the Internet field and the description of the socket transmission list supported by unix, the supported transmission list can also be retrieved using stream_get_transports ().
This socket is enabled by default in blocking mode. you can switch to non-blocking mode and use stream_set_blocking (). If the above instance does not understand it, let's take a look. the code is as follows:
The code is as follows:
$ Fp = fsockopen ("www.jb51.net", 80, $ errno, $ errstr, 30 );
If (! $ Fp ){
Echo "$ errstr ($ errno )";
} Else {
$ Out = "get/http/1.1 ";
$ Out. = "host: www.jb51.net ";
$ Out. = "connection: close ";
Fwrite ($ fp, $ out );
While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
}
Fclose ($ fp );
}
I hope this article will help you with PHP programming.