Tuesday, June 17, 2014

Use PHP CURL with connection timeout instead of file_get_contents

Most of us uses file_get_contents in PHP for fetching contents from remote locations, but if remote location is down or not reachable the script will continue executing until maximum execution time as defined in php.ini settings.

To prevent this error, you can use CURL with connection timeout in PHP, this will ensure that script will halt when defined connection timeout is reached.

/**
 * Get contents from remote locations with connection timeout
 * @param String $url
 * @param Integer $timeout
 * @return String
 */
function curl_get_contents($url, $timeout = 5) {
    // Initiate the curl session
    $ch = curl_init();
    // Set the URL
    curl_setopt($ch, CURLOPT_URL, $url);
    // follow any "Location: " header that the server sends
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    // Return the output instead of displaying it directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // The number of seconds to wait while trying to connect
    // Use 0 to wait indefinitely. 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    // Execute the curl session
    $data = curl_exec($ch);
    // Close the curl session
    curl_close($ch);
    return $data;
}

// get contents of xyz.com, with connection timeout value of 1 seconds
$html = curl_get_contents("http://www.xyz.com", 1);
echo $html;

To set many other options for PHP CURL refer to this php curl options page.