简体   繁体   中英

How to stop execution of PHP script when a certain condition is met in IF statement?

I am developing an application using PHP. And I have an HTML form with three input fields: username, password and confirm password. I want to prevent empty inputs. I have this PHP code for that:

if (empty($firstname)) {
    $message = "Please enter first name";
}
if (empty($password)) {
    $message = "Please enter password";
}
if (empty($confirm_password)) {
    $message = "Please confirm password";
}

Now what it does is that it check for all 3 inputs at once and displays 3 messages. But I want it to check if first name is empty first. And if empty displays the message and exit (terminates the rest of the code, not only within the IF statement but the whole PHPcode. And if not empty then that is when it supposed to jump to the next field which is password in this case.

Please help me to achieve that.

Although the most simplest of solutions, like stated above, would indeed be to just call exit() or die() (which is actually an alias of exit() ), it is also the worst solution . By simply killing your script you might prevent from a zombie apocalypse flooding the earth and other realms, but there's virtually not a single good use of exit outside of cli scripts. As a rule of the thumb; if somewhere in your code you've written either exit() or die() , you've done something wrong. Most primarily; the fact that something isn't quite as expected doesn't mean you can't handle it. You don't stay in your bed the whole day because you forgot to buy breakfast, don't you? You go to the supermarket and get some. If something 'unexpected' happens, in this particular case, you report back to your user so he can fix the problem (eg. by filling in the fields he forgot about)

In your case; properly separate your code into relevant parts, and you can handle exceptions (in every sense) like you should handle them. A little script as an example;

function handleForm() {
    $formInput = sanitizePostData( $_POST );
    if ( ! formValidated( $formInput ) ) {
        return false;
    }

    doWhateverYouWantWithYourPostData();
}

function sanitizePostData( $postData ) {
    // do something magical and return clean data
    return $sanitizedData;
}

Ideally, you let your handleForm() function throw an Exception , or throw a custom FormException (by extending the Exception class). But if you don't want to, call this handleForm() function something like this;

if ( ! handleForm() ) {
    // Present a meaningful message to the user
} else {
    // Go and grab a pina colada!
}

You can use die() or exit() - to terminate all, but why do you want to go this way? As i understand you are doing registration- You should do it this way -

 $message = '';
 if (empty($firstname)){
    $message.="Please enter first name";
}
if (empty($password)){
    $message.="Please enter password";
}
if (empty($confirm_password)){
    $message.="Please confirm password";
}

if($message=='')
{
 // your code here
}
else
{
  echo $message;
}

You might also want to use try catch syntax, which avoid pyramidal codes of conditionnal statements :

<?php

try {
    if (empty($firstname)){
        throw new Exception("Please enter first name");
    }

    if (empty($password)){
        throw new Exception("Please enter password");
    }

    if (empty($confirm_password)){
        throw new Exception("Please confirm password");
    }

    // Everything is fine, logic continues here...
}
catch( Exception $e ) {
    $message = $e->getMessage();

    die( $message );
}

?>

At the first throw statement, the program automatically jump to the next catch statement. In this case, you throw a Exception , and as we catch them, the first error will be displayed (instead of accumulating all the errors).

As every folks put die for displaying the message I put it too, but you can return a nice HTML error if you would like.

When you read the code again, exceptions let the developper better understand that these conditionnal failures are really exceptions and that the code should stops. It is less easy to undertsand it when we only set up if else statements. That one of the advantages of exceptions.

But exceptions are far more powerful, they make it easy to know which lines thrown the exception, in which file, you can also provide an error code to make it more reliable, ...

Why don't you try else if

if (empty($firstname)){
    $message="Please enter first name";
}
else if (empty($password)){
    $message="Please enter password";
}
else if (empty($confirm_password)){
    $message="Please confirm password";
}

in such code if first condition met then it will skip rest of conditions to check.

You also can try something like this

$error = 0; 
if (empty($firstname)) {
    $error = 1;
    $message = "Please enter first name";
}
if (empty($password)) {
    $error = 1;
    $message = "Please enter password";
}
if (empty($confirm_password)) {
    $error = 1;
    $message = "Please confirm password";
}

if($error === 0){
     // Do whatever you wanna
     $message = "Successful message";
}

you need to add

die()

After returning each message. Pasting the whole code could help me give you a much better answer.

I suggest following...

function doSomething($message) {

    echo $message;

    exit();
}

if (empty($firstname)){
    $message="Please enter first name";
    doSomething($message);
}
if (empty($password)){
    $message="Please enter password";
    doSomething($message);
}
if (empty($confirm_password)){
    $message="Please confirm password";
    doSomething($message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM