PHP socket simulates the POST request instance code, socketpost

Source: Internet
Author: User
Tags form post

PHP socket simulates the POST request instance code, socketpost

Most of the POST request simulation we use is implemented using php curl. PHP socket can also be implemented without consideration. Today I saw a friend writing an article, next I will share with you the PHP socket POST request simulation instance.

Previously, PHP curl extensions were used to simulate post requests, and PHP socket can also be used. I recently reviewed the relevant materials and found that it was not so advanced, but I have never fully understood the principles and nature of post, the Protocol string sent to the target program as post is as follows:

POST/destination program url HTTP/1.1

Accept: Receiving information format

Referer: Url

Accept-Language: Receiving Language

Content-Type: Application/x-www-form-urlencoded

Cookie: No need to explain the website cookie too much, right?

User-Agent: User Agent, operating system and version, CPU type, browser and version

Host: Host address to be sent

Content-Length: The length of the sent data

Pragma: Whether the cache exists locally

Cache-Control: Whether webpage cache is required

Connection: Connection status

Username = fengdingbo & password = jb51.net // data sent by post

I think you should not be familiar with submitting data using the form post method. For example, when we want to send the user name and password to a page, fill in the corresponding input box, click the submit button to send the form to the action program. I think it's not hard to understand this.

At this time, we only need to use the php socket to open a port, such as port 80, to send the above information to the target program.

How can we establish a socket channel on a port?

It's so easy in PHP!

Official prototype:

Resource fsockopen (string $ hostname [, int $ port =-1 [, int & $ errno [, string & $ errstr [, float $ timeout = ini_get ("default_socket_timeout")])

Below is human understanding:

Fsockopen (host name, port number, error code & variable, error message & variable, timeout time)
The host name is the destination of the data to be sent;
The port number is the port on which the target program will wait for your data;
Variable of the error code. This is the error number returned when the socket fails to be created;
The error message returned when an error occurs;
The timeout time is the maximum waiting time if the recipient does not respond after the post data.

If there is no accident (you set the fsockopen () function parameter correctly), a socket channel is now open. What we need to do next is, use this open channel to send the post request protocol to the target program. At this time, you can use any of the fwrite or fputs functions to send the post request format to the resource handle opened by fsockopen, at this time, a great socket simulated post request was born.

The Code is as follows:

<? Php/*** SOCKET Extension function * @ copyright (c) 2013 * @ author Qiufeng <fengdingbo@gmail.com> * @ link http://www.bkjia.com * @ version 1.0 * // *** Post Request ** @ param string $ url * @ param array $ data * @ param string $ referer * @ return array */if (! Function_exists ('socket _ Post') {function socket_post ($ url, $ data, $ referer = '') {if (! Is_array ($ data) {return;} $ data = http_build_query ($ data); $ url = parse_url ($ url); if (! Isset ($ url ['scheme ']) | $ url ['scheme']! = 'Http') {die ('error: Only http request are supported! ') ;}$ Host = $ url ['host']; $ path = isset ($ url ['path'])? $ Url ['path']: '/'; // open a socket connection on port 80-timeout: 30 sec $ fp = fsockopen ($ host, 80, $ errno, $ errstr, 30); if ($ fp) {// send the request headers: $ length = strlen ($ data ); $ POST = <HEADERPOST {$ path} HTTP/1.1 Accept: text/plain, text/htmlReferer: {$ referer} Accept-Language: zh-CN, zh; q = 0.8Content-Type: application/x-www-form-urlencodem Cookie: token = value; pub_cookietime = 2592000; Pub_sauth1 = value; pub_sau2= valueUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17 Host: {$ host} Content-Length: {$ length} Pragma: no-cacheCache-Control: no-cacheConnection: closern {$ data} HEADER; fwrite ($ fp, $ POST ); $ result = ''; while (! Feof ($ fp) {// receive the results of the request $ result. = fread ($ fp, 512) ;}} else {return array ('status' => 'error', 'error' => "$ errstr ($ errno) ");} // close the socket connection: fclose ($ fp); // split the result header from the content $ result = explode (" rnrn ", $ result, 2); // return as structured array: return array ('status' => 'OK', 'header' => isset ($ result [0])? $ Result [0]: '', 'content' => isset ($ result [1])? $ Result [1]: '') ;}} print_r (socket_post ('HTTP: // www.bkjia.com/', array ('name =' => 'qiufeng ', 'Password' => md5 ('www .jb51.net');/* e. g: socket_post ('HTTP: // www.bkjia.com ', array ('name =' => 'qiufeng', 'Password' => md5 ('jb51. net '); * // * End of file socket_helper.php */

In fact, when the socket channel is opened, the COOKIE we pass is correct (the running php code comes from the top, and my user name is displayed on the webpage returned after running, it indicates that the website of the other party has admitted that I have logged on. You can do more than N things, for example, post and reply. You understand, right?

Well, the above is not convincing enough. Let's look at a php socket to upload images.

Note the following two points for this Code:

First, it is an http post request;

Second, form upload protocol,

The request string is applicable to any language.

The Code is as follows:

<?php    $remote_server = "jb51.net";    $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);      // Build the header   $header = "POST /api.php?action=twupload HTTP/1.0rn";   $header .= "Host: {$remote_server}rn";   $header .= "Content-type: multipart/form-data, boundary=$boundaryrn";    /*   // attach post vars   foreach($_POST AS $index => $value){    $data .="--$boundaryrn";    $data .= "Content-Disposition: form-data; name="".$index.""rn";    $data .= "rn".$value."rn";    $data .="--$boundaryrn";   }   */  $file_name = "aaa.jpg";   $content_type = "image/jpg";    $data = '';   // and attach the file   $data .= "--$boundaryrn";    $content_file = file_get_contents('aaa.jpg');   $data .="Content-Disposition: form-data; name="userfile"; filename="$file_name"rn";   $data .= "Content-Type: $content_typernrn";   $data .= "".$content_file."rn";   $data .="--$boundary--rn";    $header .= "Content-length: " . strlen($data) . "rnrn";      // Open the connection     $fp = fsockopen($remote_server, 80);   // then just   fputs($fp, $header.$data);   // reader   while (!feof($fp)) {   echo fgets($fp, 128);  }  fclose($fp);

I hope this article will help you with PHP programming.

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.