Which is better approach between fsockopen and curl?

Gaurav picture Gaurav · May 9, 2011 · Viewed 12k times · Source

I am creating an app for Automated Recurring Billing.
Please let me know which option should I opt for sending the request to server

  • fsockeopen
  • curl

and why one is better than another?

Answer

Femi picture Femi · May 9, 2011

I would recommend using PHP's stream contexts with the built in functions: http://us3.php.net/manual/en/book.stream.php . Full HTTP/S functionality and integrates nicely with fopen/file_get_contents functions. You can (for example) do a POST like this:

$chunk = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=".FACEBOOK_APP_ID."&client_secret=".FACEBOOK_SECRET."&grant_type=client_credentials");
if ($request_ids && $chunk) {
    $cookie = explode('=', $chunk);
    if (count($cookie) == 2) $cookie = $cookie[1];
    else $cookie = $cookie[0];

    // flush it
    foreach ($request_ids as $request_id) {
        $context = stream_context_create(array(
            'http' => array(
                'method'        => 'POST',
                'content'       => 'method=DELETE',
                'user_agent'    => "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)",
                'max_redirects' => 0
            )
        ));
        @file_get_contents('https://graph.facebook.com/' . $request_id . '?access_token=' . $cookie, false, $context);
    }
}

This code logs into Facebook, fetches an App Login token and then uses a secure HTTP POST to delete a number of objects using the graph API.

If you need to do fancier things, you can as well.

$context = stream_context_create(array('http' => array(
   // set HTTP method
   'method'         => 'GET',
   'user_agent'     => "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)",
   'max_redirects'  => 0
)));

// extract the cookies
$fp      = fopen(URL, "r", false, $context);
$meta    = stream_get_meta_data($fp);
$headers = $metadata['wrapper_data'];
fclose($fp);

Will log Will fetch you the headers returned by the URL. No external libraries required.