0

I am working on a PHP project and I have a file called login.php. This file contains a HTML code that basically consists of a form that has 2 inputs (used for email and password) and a submit button. Before the HTML there is a PHP script that checks if the inputs are valid (not empty, the user exists in the db). I use an hidden input field (called formsubmitted) to check if the user has pressed the submit button. If the values are valid then the PHP script redirects the user to the home page, if not, the PHP script prints a HTML div in which I store the error message and then the HTML for the form.

I would like to print only the error div, not the rest of the HTML, and for this I could use the exit() function. Now I don't know if this is a good practice, I have searched the web but didn't find any useful. I would appreciate if someone could tell me if it is ok to do so. Thanks!

Here is how my code looks briefly:

<?php
if (isset($_POST['formsubmitted'])) {
    //check if the email and password are valid
    if (valid) {
        header("Location:home.php");
    } else {
        echo "<div id='error-section'>";
        echo "message";
        echo "</div>"
    }
}
exit();
?>
<!DOCTYPE html>
<html>
...............
</html>
MarcoS
  • 17,323
  • 24
  • 96
  • 174
fifth
  • 49
  • 1
  • 1
  • 6
  • The exit() function prints a message and exits the current script. This function is an alias of the die() function. – Krupal Shah Aug 12 '14 at 15:57
  • 2
    I would print the error message in the HTML. – putvande Aug 12 '14 at 15:58
  • 1
    As written, your code will never output any html except maybe that error message, since you're pulling the exit() OUTSIDE of your if() structure. you'll do the if() test, then always exit. – Marc B Aug 12 '14 at 16:01
  • 1
    @krupalshah Going by [the documentation](http://php.net/manual/en/function.die.php), it's actually the other way around: `die` is an alias to `exit`. But your general point is correct. – kojiro Aug 12 '14 at 16:01
  • Of course outputting only partial HTML is not “good practice”. Good practice would be to output that error message surrounded by at least a minimal, yet valid HTML document. – CBroe Aug 12 '14 at 16:02
  • There can be some unexpected behavior with `exit()`, particularly if you're using FastCGI. For that reason, I would just print the error message in a more controlled way within the HTML. – Jonathan M Aug 12 '14 at 16:02
  • 1
    Why the downvotes? It's a good question. He's asking if the practice is good. He's not advocating it. – Jonathan M Aug 12 '14 at 16:03
  • I think it's a perfectly valid question, for those people just picking up programing and PHP coming from the failed US school system (I was taught that `GOTO` statements were ok to use - within the last 5 years). Renaming the question title to: "exit() - best Practices" may be a more suitable title. – Tyler Wall Aug 12 '14 at 16:22

3 Answers3

5

To answer your question: I personally wouldn't use exit() statements anywhere in your code (unless it's after a REST API echo(json_encode(array()) echo statement.) It just can cause a lot of head aches down the road with debugging errors.

(It also can break \ob_*()\ calls as well as the majority of framework's display modules - because the framework won't be able to get to it's echo statements.)


My Practice:

I always have a .errors div in my forms:

<?php if (isset($errors) && !empty($errors): ?>
     <?php foreach ($errors as $error): ?>
          <div class="alert alert-danger" role="alert">
               <strong>Error: </strong> <?php echo $error['message'] ?>
          </div>
     <?php endforeach; ?>
<?php endif; ?>

<form>
     <!--- form here -->
</form>

form errors

This way you just pass the $errors array into your form and everything works honkey dory and you can avoid using exit() - using exit() has it's time and place, but because it doesn't give you a message or log anything it can be a royal pain to debug later on.

As a closing note, this method allows you to pass an array to the errors like so:

array(
     'first_name' => 'First Name Required',
     'last_name' => 'Last Name Required',
     'zip_code' => 'Must enter a valid zip code'
)

Which allows you to, when you're rendering your form add an .error class to your input fields which will help your users locate which input had the problem - always nice:

<input id="first_name" type="text" class="my_input_class<?php (isset($errors) && isset($errors['first_name'])) ? ' error' : '' ?>">
Tyler Wall
  • 3,747
  • 7
  • 37
  • 52
1

try this :(UPDATED)

<?php
    if (isset($_POST['formsubmitted'])) {
        //check if the email and password are valid
        if (valid) {
            header("Location:home.php");
        } else {
            die("<html>
                   <head>
                      <!-- ADD STUFF HERE IF YOU WANT-->
                   </head>
                   <body>
                      <div id='error-section'>message</div>
                   </body>
                 </html>");
           //you can use exit if you want too
        }
    }
    ?>
    <!DOCTYPE html>
    <html>
    ...............
    </html>
Youness
  • 1,468
  • 1
  • 9
  • 19
0

The best practice is to show the form with an error message so the user has opportunity to try again. Not valid credentials can have several meaning. In any case you shouldn't just show error message and dead end for the user. Provide a meaningful error message with opportunity to try again.