3

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.

3
  • use exit(); or die(); (alias to exit). You can pass a string as an argument if you want a message displayed on the page Commented Aug 2, 2017 at 7:36
  • Add return $message in each if condition. That would break and would return one message at a time. Commented Aug 2, 2017 at 7:36
  • You used the correct word in the question. exit; Commented Aug 2, 2017 at 7:36

7 Answers 7

4

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!
}
Sign up to request clarification or add additional context in comments.

Comments

2

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, ...

2 Comments

While not wrong, this might be a bit overkill for the intended use (and level of OP).
I completely agree
0

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.

Comments

0

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;
}

3 Comments

At least add new line in between the messages.
i just wanted him to show a basic way as he seems new to php. anyway thanks.
If you want to do it a tad more fancy, make a array, add the values. At the end you implode with a newline. This way you can easily change it (say you now want a - in front of each point)
0

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";
}

Comments

-1

you need to add

die()

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

1 Comment

Dont use die! Use proper logic to catch errors. Never die in live code without an exceptional good reason.
-1

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);
}

2 Comments

Dont use exit! Use proper logic to catch errors. Never exit in live code without an exceptional good reason.
nice optimization.

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.