Send POST request//@param string $url request address//@param array $post _data post key value pair data//@return string function Sendpos T ($url, $post _data) {//Http_build_query ()///Generate Url-encode after request string////Remarks:/// The delimiter for the php5.3 is & if the target server is also php5.3, then there will be no error. But if the target server is Java tomcat or something else, then & may handle the error. The following forms can avoid errors//Http_build_query ($post _data, ', ' & '); Stream_context_create ()//Create and return a resource for a stream$username = ' username ';$password = ' password ';$postData = Http_build_query ($post _data, ' & '); $options = Array (' http ' =>array (' method ' = ' "POST", ' header ' = ') ' Accept-la Nguage:en\r\n ". "Cookie:foo=bar\r\n". "Content-type:application/x-www-form-urlencoded\r\n"."Authorization:basic". Base64_encode ("$username: $password"). ' \ r \ n ', ' content ' = $postData, ' timeout ' = 15 * 60,//timeout (in s))); Creates and returns a resource for a stream $context = Stream_context_create ($options); $result = File_get_contents ($url, False, $context); return $result; Note: If the destination address requires login verification, you will need toRed WordPart of the code, if no login verification is required,Red WordPart of the code is not written
- <?php
- /**
- * Socket version
- * How to use:
- * $post _string = "App=socket&version=beta";
- * Request_by_socket (' chajia8.com ', '/restserver.php ', $post _string);
- */
- function Request_by_socket ($remote _server,$remote _path,$post _string,$port =,$timeout = 30) { /c8>
- $socket = fsockopen ($remote _server, $port, $errno, $errstr, $timeout);
- if (! $socket) die ("$errstr ($errno)");
- Fwrite ($socket, "POST $remote _path http/1.0");
- Fwrite ($socket, "User-agent:socket Example");
- Fwrite ($socket, "HOST: $remote _server");
- Fwrite ($socket, "content-type:application/x-www-form-urlencoded");
- Fwrite ($socket, "Content-length:".) (strlen ($post _string) + 8). "");
- Fwrite ($socket, "accept:*/*");
- Fwrite ($socket, "");
- Fwrite ($socket, "mypost= $post _string");
- Fwrite ($socket, "");
- $header = "";
- While ($str = Trim (fgets ($socket, 4096))) {
- $header. = $str;
- }
- $data = "";
- While (! Feof ($socket)) {
- $data. = fgets ($socket, 4096);
- }
- return $data;
- }
- ?>
- <?php
- /**
- * Curl Version
- * How to use:
- * $post _string = "App=request&version=beta";
- * Request_by_curl (' http://www.qianyunlai.com/restServer.php ', $post _string);
- */
- function Request_by_curl ($remote _server, $post _string) {
- $ch = Curl_init ();
- curl_setopt ($ch, Curlopt_url, $remote _server);
- curl_setopt ($ch, Curlopt_postfields, ' mypost= '. $post _string);
- curl_setopt ($ch, Curlopt_returntransfer, true);
- curl_setopt ($ch, curlopt_useragent, "qianyunlai.com's CURL Example beta");
- $data = curl_exec ($ch);
- Curl_close ($ch);
- return $data;
- }
- ?>
PHP three ways to send post, get requests