Passing error messages in PHP

I have a login form on my website that checks for submitted usernames / passwords. If there are no matches, the user returns to the login page and a corresponding error message appears. The call for this redirect is:

header("location:../login.php?error_message=$error_message"); 

This works fine, but it looks randomly in the address bar of the browser (especially with descriptive error messages). Is there a way to do this automatic redirection without using the $ _GET variable? I have considered using the $ _SESSION variable, but this does not seem to be the best coding practice.

Thank you for reading.

+6
source share
5 answers

How about having a simpler GET variable?

 // something.php header ("Location: foo.php?err=1"); 

And then on the error handling page:

 // foo.php $errors = array ( 1 => "Hello, world!", 2 => "My house is on fire!" ); $error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0; if ($error_id != 0 && in_array($error_id, $errors)) { echo $errors[$error_id]; } 

Hope this helps.

+4
source

If you do not want to use sessions, you can use error codes instead:

 header('Location: ../login.php?error=' . urlencode($error_code)); 

Then inside login.php :

 if (isset($_GET['error'])) { switch ($_GET['error']) { case 123: // ... break; } } 

Instead of a bulky switch, instead, you can use the search array for error messages (it may be language dependent).

Btw, using relative URIs in header redirection is not recommended; an absolute (e.g. /login.php ) or full URI (e.g. http://example.org/login.php ) is preferred.

+1
source

You have 3 options for checking the form:

  • Use AJAX for validation - so no redirects at all.
  • Use redirection and session to save the error message along with the entered data.
  • Use redirect as part of POST / Redirect / GET patterm

Personally, I would implement (1) and (3) for my forms. (1) for the convenience of the average user; and (3) for backward compatibility with paranoids such as myself.

Using sessions is indeed the cleanest way for redirec-based validation, since under any circumstances it will not leave a POSTed page in history. However, in the presence of AJAX-based validation, it seems to overdo it a bit

+1
source

You can use session-based flash messages.

Have a look at this example: http://mikeeverhart.net/php/session-based-flash-messages/

0
source

Using a session is a good option. You can clear the session value as soon as an error occurs. But if you do not want to use a session, you can change your URL as follows.

 // login failed header("location:../login.php?status=0"); 

I prefer to use a session.

-3
source

All Articles