This article mainly introduces how php uses socketpost to transmit data to other web servers. It involves related skills related to using socket to transmit data in php. For more information, see
This article mainly introduces how php uses socket post data to send data to other web servers. It involves related skills related to using socket to transmit data in php. For more information, see
This example describes how php uses socket post to send data to other web servers. Share it with you for your reference. The specific implementation method is as follows:
Function post_request ($ url, $ data, $ referer = '') {// Convert the data array into URL Parameters like a = B & foo = bar etc. $ data = http_build_query ($ data); // parse the given URL $ url = parse_url ($ url); if ($ url ['scheme ']! = 'Http') {die ('error: Only http request are supported! ');} // Extract host and path: $ host = $ url ['host']; $ 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: fputs ($ fp, "POST $ path HTTP/1.1 \ r \ n"); fputs ($ fp, "Host: $ host \ r \ n "); if ($ referer! = '') Fputs ($ fp," Referer: $ referer \ r \ n "); fputs ($ fp," Content-type: application/x-www-form-urlencoded \ r \ n "); fputs ($ fp," Content-length :". strlen ($ data ). "\ r \ n"); fputs ($ fp, "Connection: close \ r \ n"); fputs ($ fp, $ data ); $ result = ''; while (! Feof ($ fp) {// receive the results of the request $ result. = fgets ($ fp, 128) ;}} else {return array ('status' => 'err', 'error' => "$ errstr ($ errno) ");} // close the socket connection: fclose ($ fp ); // split the result header from the content $ result = explode ("\ r \ n", $ result, 2 ); $ header = isset ($ result [0])? $ Result [0]: ''; $ content = isset ($ result [1])? $ Result [1]: ''; // return as structured array: return array ('status' => 'OK', 'header' => $ header, 'content' => $ content);} // usage // Submit those variables to the server $ post_data = array ('test' => 'foobar ', 'okay' => 'yes', 'number' => 2); // Send a request to example.com $ result = post_request (' http://www.example.com/ ', $ Post_data); if ($ result ['status'] =' OK ') {// Print headersecho $ result ['head']; echo'
'; // Print the result of the whole request: echo $ result ['content'];} else {echo 'a error occured :'. $ result ['error'];}
I hope this article will help you with php programming.
,