2

In PHP, I can use die() to kill the whole script. However, I want the script to execute up to a certain point and quit without the whole script dying.

Something like this:

echo "Hello, what is your name?";
if($name == $blacklist)
{
   echo "I don't talk to strangers";
   die(); // This will break all the echos
}
else
  // Stuff

I just want the script to terminate (and print the echos up to the point of termination), and using die() will actually make the script print nothing.

Any ideas? Maybe "return 0" like in C?

3
  • 1
    The sample works just fine for me. It echos everything until die() is called. What version of PHP are you using? Commented Sep 10, 2011 at 8:55
  • @Tarek wow, how in the heck did I make that mistake... some reason I thought the whole script didn't execute when die was called. Commented Sep 10, 2011 at 9:03
  • my bad everyone, sorry for wasting your time Commented Sep 10, 2011 at 9:04

2 Answers 2

6

You can do:

die("I don't talk to strangers");

Or:

echo "I don't talk to strangers";exit;

Or simply "return" return;

Or throw new Exception("I don't talk to strangers");

Sign up to request clarification or add additional context in comments.

2 Comments

but this won't print the "Hello, what is your name?"
@dulkevin to print that you need to check weather that parameter isset in GET/POST request or not . If not then simply echo "Hellow , what is your name" otherwise do the blacklist check.
0

There is no "script execution" as you imagine it.

There are actually two instances of the same script running, not one. The first one to ask the question and the second one to check the answer.

PHP scripts' execution is atomic. It's not like a desktop application constantly running in your browser, and not even a demon with persistent connection to your desktop application. It's more like a command line utility - doing its job and exits. It runs discrete.

So, you have to choose the proper branch of code to terminate, not the whole script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.