3

My host doesn't allow fsockopen, but it does allow curl. I'm happy using curl from the cli, but haven't had to use it with PHP much. How do I write this using curl instead?

$xmlrpcReq and Length are defined earlier.

$host = "http://rpc.pingomatic.com/";
$path = "";

$httpReq  = "POST /" . $path . " HTTP/1.0\r\n";
$httpReq .= "User-Agent: My Lovely CMS\r\n";
$httpReq .= "Host: " . $host . "\r\n";
$httpReq .= "Content-Type: text/xml\r\n";
$httpReq .= "Content-length: $xmlrpcLength\r\n\r\n";
$httpReq .= "$xmlrpcReq\r\n";   

if ($pinghandle = fsockopen($host, 80)) {
    fputs($pinghandle, $httpReq);
    while (!feof($pinghandle)) { 
        $pingresponse = fgets($pinghandle, 128);
    }
    fclose($pinghandle);
}

Thanks a lot!

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
  • How do you know your host doesn't allow fsockopen? It's kind of uncommon for hosters to do, since it disables all the nice http libraries (= not curl). Which error message did you get? (Otherwise I would assume the error originates from the invalid Host: header.) – mario Jan 30 '11 at 21:15
  • Yeah, I've confirmed with host that fsockopen isn't allowed. Rubbish! – Rich Bradshaw Jan 30 '11 at 21:22

1 Answers1

2

Try this:

$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'My Lovely CMS');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlrpcReq);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curl, CURLOPT_URL, "http://rpc.pingomatic.com/");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$pingresponse = curl_exec($curl);
Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • Haven't completely tested yet, but this is basically on the right lines by the looks of it. I found I had to pass $curl to curl_setopt as the first argument each time, and add a CURLOPT_URL line to get it working, but looks like it's going to work - thanks! – Rich Bradshaw Jan 30 '11 at 21:23