Rogare
Rogare

Reputation: 3274

Passing error messages in PHP

I have a login form on my website that checks submitted usernames/passwords. If there's no match, the user is sent back to the login page and an appropriate error message is displayed. The call for this redirect is this:

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

This works fine, but it does look messy in the browser's address bar (especially with descriptive error messages). Is there any way to do this automatic redirect without using the $_GET variable? I had considered using the $_SESSION variable, but that doesn't seem like the best coding practice.

Thanks for reading.

Upvotes: 7

Views: 12895

Answers (5)

Your Common Sense
Your Common Sense

Reputation: 157839

For the form validation you have 3 options:

  1. Use AJAX to validate - so, there will be no need to redirect at all.
  2. Use redirect and session to store the error message along with entered data.
  3. Use redirect as a part of the POST/Redirect/GET patterm

Personally I would implement (1) and (3) for my forms. (1) for the convenience of ordinary user and (3) for backward compatibility with paranoids like myself.

Using sessions is indeed a cleanest way for the redirec-based validations, as it will leave no POSTed page in the history under any circumstances. However, in a presence of AJAX-based validation it seems a bit overkill

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173552

If you don't wish to use sessions, you could 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, you could use a lookup array for error messages instead (can be language dependent).

Btw, using relative URIs in your header redirects is not recommended, an absolute (e.g. /login.php) or fully qualified URI (e.g. http://example.org/login.php) is preferred.

Upvotes: 1

Mahendra
Mahendra

Reputation: 928

Using session is a good option. You can clear session value as soon as you display error. But if you don't want to use session you can modified your url like following.

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

I prefer to use session.

Upvotes: -3

mishmash
mishmash

Reputation: 4458

What about having a simpler GET variable?

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

And then in the page handling the errors:

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

Upvotes: 7

Fred
Fred

Reputation: 1627

You can use session based flash messages.

Look at this example : http://mikeeverhart.net/php/session-based-flash-messages/

Upvotes: 0

Related Questions