Php uses socket to simulate sample code for submitting data through post or get in http _ PHP Tutorial

Source: Internet
Author: User
Php uses socket to simulate the sample code for submitting data through post or get in http. Not much nonsense. Directly run the code: sock_post.php: Copy the code as follows :? Phpfunctionsock_post ($ url, $ data) {$ urlparse_url ($ url); $ url [scheme] | $ url [scheme] not much nonsense. Directly run the code:
Sock_post.php:

The code is as follows:


Function sock_post ($ url, $ data = ''){
$ Url = parse_url ($ url );
$ Url ['scheme '] | $ url ['scheme'] = 'http ';
$ Url ['host'] | $ url ['host'] = $ _ SERVER ['http _ host'];
$ Url ['path'] [0]! = '/' & $ Url ['path'] = '/'. $ url ['path'];

$ Query = $ data;
If (is_array ($ data) $ query = http_build_query ($ data );

$ Fp = @ fsockopen ($ url ['host'], $ url ['port']? $ Url ['port']: 80 );
If (! $ Fp) return "Failed to open socket to $ url [host]";

Fputs ($ fp, sprintf ("POST % s HTTP/1.0/n", $ url ['path'], $ url ['query']? "? ":" ", $ Url ['query']);
Fputs ($ fp, "Host: $ url [host]/n ");
Fputs ($ fp, "Content-type: application/x-www-form-urlencoded/n ");
Fputs ($ fp, "Content-length:". strlen ($ query). "/n ");
Fputs ($ fp, "Connection: close/n ");

Fputs ($ fp, "$ query/n ");

$ Line = fgets ($ fp, 1024 );

If (@! Eregi ("^ HTTP/1/.. 200", $ line) return;

$ Results = "";
$ Inheader = 1;
While (! Feof ($ fp )){
$ Line = fgets ($ fp, 1024 );
If ($ inheader & ($ line = "/n" | $ line = "/r/n ")){
$ Inheader = 0;
} Elseif (! $ Inheader ){
$ Results. = $ line;
}
}
Fclose ($ fp );

Return $ results;
}
$ Re = sock_post ('http: // localhost/direct_post/get_post.php? Id = 1', array ('wel' => 'Hello '));
Echo $ re;
?>


Get_post.php:

The code is as follows:


Echo "post :";
Print_r ($ _ POST );
Echo 'get :';
Print_r ($ _ GET );
?>

Bytes. Directly run the code: sock_post.php: the code is as follows :? Php function sock_post ($ url, $ data = '') {$ url = parse_url ($ url ); $ url ['scheme '] | $ url ['scheme'] =...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.