1

Possible Duplicate:
How to catch curl errors in PHP

I have got some lines of code:

<?php
try {
    $my_curl = curl_init();

    curl_setopt($my_curl, CURLOPT_URL, $one_url); 
    curl_setopt($my_curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($my_curl, CURLOPT_BINARYTRANSFER, 1);
    $datum = curl_exec($my_curl);
    curl_close($my_curl);

    $my_image = imagecreatefromstring($datum);

} catch(Exception $e) {
    var_dump($e->getMessage());
}       
?>

When running in real environment, some sites which contain images (as $one_url) cannot access or died or ... cause one/ or many of lines of code turn into errors.

How can I try - catch if any statement cannot be done successfully? In other words, I like try - catch works like... switch - case (not if else).

Any advice will be greatly appreciated! Thank you very much.

Community
  • 1
  • 1
SuperThin
  • 65
  • 5

3 Answers3

1

You can do it with curl_error:

$datum = curl_exec($my_curl);
if($datum === false) {
    echo 'Curl error: '.curl_error($ch);
}
dan-lee
  • 14,365
  • 5
  • 52
  • 77
0

Why don't you throw an Exception when false is returned?
i.e.

if ($curlResp === FALSE) {
    throw new Exception(); 
}

Check this
Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Wazy
  • 8,822
  • 10
  • 53
  • 98
0

Try this:

if(curl_errno($my_curl))
{
    echo 'error:' . curl_error($my_curl);
}
Engineer
  • 5,911
  • 4
  • 31
  • 58