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

Source: Internet
Author: User
The following describes the sample code for simulating post or get data submission in http using socket in php. If you need it, refer to it.

The following describes the sample code for simulating post or get data submission in http using socket in php. If you need it, refer to it.

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 );
?>

, Hong Kong Space, Hong Kong Space, U.S. servers

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.