Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing error messages in PHP

Tags:

redirect

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.

like image 964
Rogare Avatar asked Mar 26 '13 10:03

Rogare


1 Answers

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.

like image 50
mishmash Avatar answered Nov 24 '22 01:11

mishmash