Wednesday 29 October 2014

Managing errors with cURL library access

Having one URL ($sURL), we would like to get the associated file content (this can be any file, not only an  XML file):

Here is the PHP code using cURL library with the 'cur_exec' function to get the content, and the 'curl_errno' function to get the possible error message !!!

<?php
$sUrl = "http://tycaron.blogspot.fr/2014/10/managing-errors-with-curl-library-access.ht";
$bError = false;
$sXml = GetCurl_Response($sUrl);
 if ($sXml === false)
{
        $bError = true;
        $aErrors[] = GetCurl_Error($sUrl);
}

if ($bError) var_dump($aErrors);

/*
 * get the file content related to an URL
* @param  string $url
* @return string
*/
function GetCurl_Response($url)
{
  // create curl resource
  $curl = curl_init($url);

  // var_dump($curl);
  curl_setopt($curl, CURLOPT_FAILONERROR, true);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  $result = curl_exec($curl);


  //close curl resource to free up system resources
  curl_close($curl);
  return $result;
}

/*
 * get cURL error (return 'false' if no error)
 * @return string
*/
function GetCurl_Error($url)
{
  // create curl resource
  $curl = curl_init($url);

  // var_dump($curl);
  curl_setopt($curl, CURLOPT_FAILONERROR, true);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  $result = curl_exec($curl);
 if ($result===false)
   $error_curl = 'Erreur Curl : ' .curl_error($curl).' ('.curl_errno($curl).')';
  else
   $error_curl = false;

  //close curl resource to free up system resources
  curl_close($curl);
  return $error_curl ;
}
?>

Having made volontarily an error when writing URL, the output error message will then be :
array(1) { [0]=> string(66) "Erreur Curl : The requested URL returned error: 404 Not Found (22)" }