PHP Socket mock POST request instance code _php tips

Source: Internet
Author: User
Tags curl http post md5 php code php programming strlen port number

We use most of the simulated post requests are almost all using PHP curl to achieve, not to consider the PHP socket can also be implemented, today I saw a friend wrote an article, I would give you to share the PHP socket simulation POST request instance.

I've used a php curl extension for my previous analog post requests, and I didn't think PHP sockets could be implemented. Recently turned over the relevant information to find that the original is not so advanced, but has not fully understand the principle of post and the essence of it, in fact, is sent to the destination program a flag for the post of the Protocol string is as follows:

POST/Destination Program URL http/1.1

Accept: Receive Information Format

Referer: URL Routing

Accept-language: Receiving language

content-type: application/x-www-form-urlencoded

cookie: Web cookie, I don't need to explain it too much, right?

user-agent: User agent, operating system and version, CPU type, browser and version information

Host: Hosting address to send to

content-length: The length of the data sent

Pragma: There is a cache locally

Cache-control: Page caching is required

Connection: Connection Status

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

I think you should be the most familiar with the form of post method submission data, such as we want to send a user name and password to a page, fill out the corresponding input box, click the Submit button, and finally send this form to the action program is the above data. Knowing this, I don't think it's hard.

At this time we only need to use PHP socket open a port, such as 80 ports, the above information to use this port to send to the destination program on the line.

How do we create a socket channel on a single port?

It's so simple in PHP!

The official prototype:

Resource Fsockopen (string $hostname [, int $port =-1 [, int & $errno [, String & $errstr [, float $timeout = ini_ Get ("Default_socket_timeout")]]]

Below is the understanding of mankind:

Fsockopen (host name, port number, error number & variable, error hint & variable, timeout time)
The host name is the destination where you need to send the data;
The port number is the destination where the program will wait for your data;
The & variable of the error number, which is the error number that is returned if the socket is not successfully established;
Error-prompted & variable, is the wrong time to return the error message;
Timeout is the maximum time to wait after post data if the other person has not responded to the message.

If there is no accident (you correctly set the Fsockopen () function parameters), a socket channel is now open, and what we need to do next is to send the POST request protocol to the destination program through this open channel. At this point, you can use either of the fwrite or fputs functions to send the POST request format to the Fsockopen () open resource handle, when a great socket emulation Post request is born.

The code is as follows

<?php/** * Socket extension function * @copyright (c) 2013 * @author Qiufeng <fengdingbo@gmail.com> * @link http://www.jb5
 1.net * @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, $errno, $errstr, 30);
 if ($FP) {//Send the request headers: $length = strlen ($data); $POST = << 

In fact, when the socket channel is open, we pass the cookie correctly, (screenshot of the running of the PHP code from the top, after the return of the Web page appears my user name, stating that the other site has admitted that I have logged in) we can do n many things, such as brush posts, brush reply, etc., you understand, right?

Okay, it's not convincing enough. Let's look at a PHP socket implementation picture upload

This code has two points to note:

One is that he is the HTTP POST request;

The second is form upload protocol,

The request string below is suitable for 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 your  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.