PHP – fsockopen & POST
Today’s tutorial is short but very sweet. When dealing with many of third party APIs or web services in general, you are pretty much required to either GET info or POST data, si?
So yes yes, you are probably chanting CUrl over there, but I’m an old schooler, and kinda like having a bit more control (visual at least) over my HTTP messages. So here’s a simple post message using good ol fsockopen
You first open a socket connection to the end point host – almost same concept as opening a file for writing
if it fails you error out with a friendly message or profanity directed at your network admin (I’d go with a friendly message here)
$fp = fsockopen($api.awesomeblog.com, 80, $errno, $errstr, 30);
if (!$fp) {
echo "no dice $errstr ($errno)\n";
}
If all is good, we move on to our “else” statement
else {
$out = "POST /blog/addpost.json HTTP/1.1\r\n";
$out .= "Host: api.awesomeblog.com\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Content-Length: " . strlen($msg) . "\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
Since we are POSTing the method used in our message is POST - followed by the path of the endpoint responsible. If the complete URL for the endpoint is api.awesomeblog.com/blog/addpost.json, then you would use /blog/addpost.json here
HOST : is the other half of the URL a.k.a the root; in this scenario it is api.awesomeblog.com
$msg : is body of what you are posting e.g ”blog_id=1&subject=good%20times&body=I%20am%awesome
Everything else is pretty much standard HTTP goodness. A wise man once told me to always specify content length, and wise he was. I learned the hard way, that some messages get rejected (evil OAuth)
As promised, short and sweet
-Warebot





