Welcome to the Linux community forum and interact with 2 million technical staff. In this article, we will share three methods and sample code for php to send post requests, using curl, file_get_content, and fsocket to submit post data, for your reference. Php sends post requests using curl, file_get_content, and fsock
Welcome to the Linux community forum and interact with 2 million technical staff> in this article, we will share three methods and sample code for php to send post requests, use curl, file_get_content, and fsocket to submit data for post. Php sends post requests using curl, file_get_content, and fsock
Welcome to the Linux community forum and interact with 2 million technicians>
This article describes three methods and sample code for php to send a post request. Use curl, file_get_content, and fsocket to submit data in post mode.
Php uses curl, file_get_content, and fsocket to send post data.
Instance code:
Sample Code:
// Send post request data
Class Request {
Public static function post ($ url, $ post_data = '', $ timeout = 5) {// curl
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_POST, 1 );
If ($ post_data! = ''){
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data );
}
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
Curl_setopt ($ ch, CURLOPT_HEADER, false );
$ File_contents = curl_exec ($ ch );
Curl_close ($ ch );
Return $ file_contents;
}
Public static function post2 ($ url, $ data) {// file_get_content
// Www.jbxue.com
$ Postdata = http_build_query (
$ Data
);
$ Opts = array ('http' =>
Array (
'Method' => 'post ',
'Header' => 'content-type: application/x-www-form-urlencoded ',
'Content' => $ postdata
)
);
$ Context = stream_context_create ($ opts );
$ Result = file_get_contents ($ url, false, $ context );
Return $ result;
}
Public static function post3 ($ host, $ path, $ query, $ others = '') {// fsocket
$ Post = "POST $ path HTTP/1.1 \ r \ nHost: $ host \ r \ n ";
$ Post. = "Content-type: application/x-www-form -";
$ Post. = "urlencoded \ r \ n $ {others }";
$ Post. = "User-Agent: Mozilla 4.0 \ r \ nContent-length :";
$ Post. = strlen ($ query ). "\ R \ nConnection: close \ r \ n $ query ";
$ H = fsockopen ($ host, 80 );
Fwrite ($ h, $ post );
For ($ a = 0, $ r = '';! $ ;){
$ B = fread ($ h, 8192 );
$ R. = $ B;
$ A = ($ B = '')? 1-0 );
}
Fclose ($ h );
Return $ r;
}
}