Yes, I know you can do this via cURL. This was explicitly written for a case when that particular luxury was not available to me.
So… it’s been a while since I’ve written a post, and I’m feeling the withdrawals. I’ve got 16 half-written posts waiting in the queue and two more that I want to write but haven’t even started. It’s also time for another round of anime reviews; I’ve got two video games I want to review…
And I am having to play the “too busy with RL” card.
In stead, I present a function that I wrote this morning. It’s been done countless times before, and you can probably find incredibly similar code out there already, but it’s the first time I’ve ever actually needed something quite like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/** * Send post data somewhere ;) * * @param $host The domain name of the host to send the data to. * @param $path The path of the script to receive the post. * @param $data An array of key/value pairs to send. * @return The HTTP response, headers and all. */ function http_post( $host, $path, $data ) { // build a query string from the data array $arr = array(); foreach( $data as $key => $val ) array_push( $arr, "$key=".urlencode($val) ); $data = implode( "&", $arr ); // send that post $fh = fsockopen( $host, 80 ); fwrite( $fh, "POST $path HTTP/1.1\\\r\\\n" ); fwrite( $fh, "Host: $host\\\r\\\n" ); fwrite( $fh, "Content-type: application/x-www-form-urlencoded\\\r\\\n" ); fwrite( $fh, "Content-length: ".strlen($data)."\\\r\\\n" ); fwrite( $fh, "Connection: close\\\r\\\n\\\r\\\n" ); fwrite( $fh, $data ); // get the response while( !feof($fh) ) $buf .= fgets( $fh ); fclose( $fh ); return $buf; }// end: http_post |
This method could easily be modified to send GET data or to talk over a different port. It could also probably actually do something with the response buffer (check for 200, etc…). It could be a bit more fault tolerant, etc… but that’s not what I need for the application at hand.
For other examples of how people have done similar/related things, take a look at the comments on the fsockopen() documentation page.
One thought on “php post method”