2

I'm trying to get the focal length from an image's EXIF data via PHP.

This is the code I've got so far:

$exif = exif_read_data("$photo"); $length10 = $exif['FocalLength']; $length = eval($length10); 

$length10 in this case returns something like "1050/10" for 105mm. I don't know why. All I want to do is have PHP do the math to return 105. When I run this, though, I get the following error message:

[04-Nov-2012 20:06:39] PHP Parse error: syntax error, unexpected $end in index.php(52) : eval()'d code on line 1 

Why?

1 Answer 1

9

Because 1050/10 is not valid PHP. It has no terminating ; to end the statement, and results in a syntax error.

php > eval("1050/10"); PHP Parse error: syntax error, unexpected end of file in php shell code(1) : eval()'d code on line 1 

Rather than eval() it (which technically is dangerous since you're effectively processing user input even if it comes from EXIF), it is recommended to split on the / or capture the operands with a regular expression and then perform the operation yourself.

// Test if the value matches the division pattern if (preg_match('~^(\d+)/(\d+)$~', $length10, $operands)) { // Following a successful match, $operands is an array // containing the full matched string and the two numbers captured // in indices [1],[2] // Watch for div by zero! if ($matches[2] !== 0) { echo $operands[1] / $operands[2]; } } else { echo $length10; } 
Sign up to request clarification or add additional context in comments.

4 Comments

The images are mine only. There is no user input. Can I just add a ; to the end of the string?
@NaOH The ; will make it valid PHP and the statement will eval(). Officially, I do not advocate doing that unless you at least match it against the regular expression to validate the format.
So the suggestion is to never use eval() ever?
@NaOH Officially, yes, never use it if there is an alternative. In this case, validating the input with preg_match() will make sure it is safe and you could use it against my on-the-record recommendation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.