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.


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.


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 (eg /login.php ) or fully qualified URI (eg http://example.org/login.php ) is preferred.


For the form validation you have 3 options:

  • Use AJAX to validate - so, there will be no need to redirect at all.
  • Use redirect and session to store the error message along with entered data.
  • 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

    链接地址: http://www.djcxy.com/p/70268.html

    上一篇: 在Access中连接记录和GROUP BY

    下一篇: 在PHP中传递错误消息