Home > Net >  Better ways to show authentication errors in php
Better ways to show authentication errors in php

Time:04-12

With the help of this tutorial "OOP PHP login system" I`ve made the authentication part for my project (fixed some problems from the tutorial and everything works as intended.). In the tutorial is used:

 header("location: ../index.php?error=error_name");

to show errors that appear when making an account and when login in, like the username is taken, invalid email, password and repeatPassword dont match, wrong password, etc.. In this way the error is put into the url and I have to use a get method, like:

<?php 
            if(isset($_GET['error']))
            {
                $error = $_GET['error'];
                echo $error;
            }
    
    ?>

It works, but I don`t want to show the error in the url. What methods, functions, ways I have to use to not show the errors in the url? I would like to keep the url clean.

EDIT: I don`t want to use header() function, I want to change the way how errors are send. The header(); function is the problem. I am not experienced enough to know other methods of sending errors to the user.

CodePudding user response:

Sometimes I use a PHP SESSION variable to carry the error from one page to another where I want to show it, and it is nice and transparent.

Here is how you can apply this method - before redirecting a user to the target page (i.e. index.php page), store your error message in a PHP SESSION variable, as follows:

$_SESSION['error'] = $error_name;
header("location: ../index.php");
exit;

Now suppose, you are on index.php page then retrieve the error message, store in a local variable, and set PHP SESSION variable to NULL, as follows:

<?php
if ( isset($_SESSION['error']) ) {
    // Retrieve message from the session variable
    $error              = $_SESSION['error'];
    
    // Reset it to avoid displaying the same message
    $_SESSION['error']  = null;
    
    // Display the error message
    echo $error;
}
?>

That's it! Good luck. :)

CodePudding user response:

You can use POST instead of GET to pass the variables to your script:

https://www.w3schools.com/tags/ref_httpmethods.asp

CodePudding user response:

The header function is simply saying "instead of outputting a response to the user for this request, tell their browser to load this URL". If you don't want to redirect, simply don't use that function.

It's then entirely up to you how and where you show the error - use an echo statement, render a template, or whatever.

The only difference between a "normal" response and an error, particularly an authentication error, is that you want to stop doing anything else after outputting it. The simplest way to do that is to end the request with the exit keyword (which can also be spelled die).

For instance:

echo 'Sorry, you need to be logged in to view this page.';
exit;
  •  Tags:  
  • php
  • Related