2

I have the following code that to which the file is an ajax call:

try {
    echo json_encode(exif_read_data($_POST["url"]));
} catch (Exception $e) {
    echo "Invalid URL";
}

Its purpose is to accept an image url and return the JSON-encoded EXIF data, and when there is a "correct" url, the json_encode(exif_read_data($_POST["url"])); works just fine.

However, when I intentionally pass it a "bad" url in the jQuery ajax call "url" : "url1", or in the php file directly ..exif_read_data("bob"), I receive this error in my console log:

Warning: exif_read_data() [function.exif-read-data]: Unable to open file in ../public_html/_photos/ajax/exif.php on line 3
false
Matt
  • 1,500
  • 8
  • 23
  • 38
  • 4
    PHP standard function don't throw exceptions. EVER. There's nothing to try/catch, because nothing gets thrown. That's a **WARNING** as well, not an error – Marc B May 27 '14 at 19:11
  • I see, is there a way then to "catch" these warnings? – Matt May 27 '14 at 19:15
  • This may help - http://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning – Jay Blanchard May 27 '14 at 19:16
  • quick/dirty/ugly hack, use the `@` operator. better solution: don't try to open urls directly with php functions. – Marc B May 27 '14 at 19:16

3 Answers3

1

Function json_encode() doesn't throw exceptions if you want to throw warnings as exceptions you can override default behavior with set_error_handler()

Here you will find nice example how to do it

Community
  • 1
  • 1
Robert
  • 19,800
  • 5
  • 55
  • 85
1

Function exif_read_data($sUrl) doesn't throw exceptions.

try to do this:

   $sUrl = $_POST['url'];

   if ((isset($sUrl )) AND (file_exists($sUrl)))
   {

      echo json_encode(exif_read_data($sUrl ));
   }
   else
   {
     echo "Invalid URL";
   }  
1

As Marc mentioned in the comments, native PHP functions don't throw exceptions. To properly handle invalid urls, you can manually validate the file, then pass exif_read_data() a data-uri of the contents.

Here's how you might accomplish that.

// acceptable file extensions
$ext_whitelist = array('jpg', 'jpeg', 'tiff');

// extension for this file name
$extension = strtolower( pathinfo($_POST['url'], PATHINFO_EXTENSION) );

// make sure we will be able to get the exif data
if (!in_array($extension, $ext_whitelist)) {
    echo 'Invalid URL';
} else {
    $contents = file_get_contents($_POST['url']);

    // we couldn't open the file
    if ($contents === false) {
        echo 'Invalid URL';
    } else {
        // build the data uri
        $uri = "data://image/$extension;base64,". base64_encode($contents);

        echo json_encode( exif_read_data($uri) );
    }
}
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61