Passing error messages in PHP - 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 (e.g. /login.php) or fully qualified URI (e.g. 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

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

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.

Related

Is it possible for a page to know that it has been redirected to using header()?

I'm creating a form. There is some server-side validation being executed in a php file separate from the html file containing the form. If the validation fails, I want to redirect back to the original html page with a error message saying what went wrong.
Right now, I am able to successful validate and redirect back to the html page with header(), but I'm not sure how to create and place the error message. Is it possible to check at the top of the html page with php if it's been redirected to through header()? If so, that would solve the problem...
Thanks!
there are several methods to do this i think.
1 add get parameters like:
<input type="hidden" name="formsent" value="1" />
then add method get to your <form>
when you redirect from the other page,, the get would be in the link so you could send it back
header("Location: http://localhost/yourform.php/?{$_GET['formsent']}");
or you could do the validation in the post
if (isset($_POST) && !empty($_POST)) {
do stuff here.. if all is ok go to next page otherwise show errors
}
or you could add a var into a session using $_SESSION['formsent'] = 1 after the post then u could check that also.
its up 2 u
You should set a variable using PHP sessions.
Form page
session_start();
$_SESSION["formerror"] = "Error code here";
header("Location: http://www.example.com");
Redirected to page
session_start();
$errorcode = $_SESSION["formerror"];
// Now convert the error code to something readable and print it out if needed.
IMO this is much cleaner than a GET variable.
As #Mark wrote, you can send a message in a variable by the url in your header() (I mean url + "?variable=$variable") and capture the message in your page (now php page) by $_GET. The message will depend on your validation
Of course you can check: https://stackoverflow.com/a/872522/2737474 (#Jrgns)
Different ways to pass one variable between pages.
In my opinion, you must be careful in choose one of those:
-If you would use one value for many pages (keeping in mind it would be store on server), it would be better to use SESSION.
-If you would use one value for only two pages, it would be better to use GET or POST (depending on your situation, url/form).
-If you would use one value for many pages and want to keep it between sessions (keeping in mind it would be store on client), it would be better to use COOKIE.
You can do this with using $_GET[] method
If validation is successful then redirect to url like
form.php?status=1 // 1 for success
If validation is failed then redirect to
form.php?status=0 // 0 for fail
In form.php which is your form page.
use simple if-else condition
if(isset($_GET['status']))
{
if($_GET['status']==0)
echo'something went wrong';
//else nothing
}
As many clever users wrote you have several methods how to achive this (I won't write all of these):
1st Use sessions check Daniel's answer
2nd Use GET check Sanket Shembekar's answer
3rd Use rZaaaa's answer, but you can enchant it :D
Enchant:
Page 1
header('error: true');
Page 2
print_r(headers_list()); //and find your error

php security for location header injection via $_GET

I've got this code on my page:
header("Location: $page");
$page is passed to the script as a GET variable, do I need any security? (if so what)
I was going to just use addslashes() but that would stuff up the URL...
I could forward your users anywhere I like if I get them to click a link, which is definitely a big security flaw (Please login on www.yoursite.com?page=badsite.com). Now think of a scenario where badsite.com looks exactly like your site, except that it catches your user's credentials.
You're better off defining a $urls array in your code and passing only the index to an entry in that array, for example:
$urls = array(
'pageName1' => '/link/to/page/number/1',
'pageNumber2' => '/link/to/page/number/2',
'fancyPageName3' => '/link/to/page/number/3',
);
# Now your URL can look like this:
# www.yoursite.com?page=pageName1
This is a code injection vulnerability by the book. The user can enter any value he wants and your script will obey without any complaints.
But one of the most important rules – if even not the most important rule – is:
Never trust the user data!
So you should check what value has been passed and validate it. Even though a header injection vulnerability was fixed with PHP 4.4.2 and 5.1.2 respectivly, you can still enter any valid URI and the user who calls it would be redirected to it. Even such cryptic like ?page=%68%74%74%70%3a%2f%2f%65%76%69%6c%2e%65%78%61%6d%70%6c%65%2e%63%6f%6d%2f what’s URL encoded for ?page=http://evil.example.com/.
Yes, you do. Just because you or I can't immediately think of a way to take advantage of that little bit of code doesn't mean a more clever person can't. What you want to do is make sure that the redirect is going to a page that you deem accessible. Even this simple validation could work:
$safe_pages = array('index.php', 'login.php', 'signup.php');
if (in_array($page, $safe_pages)) {
header("Location: $page");
}
else {
echo 'That page is not accessible.';
}
Or, at the very least, define a whitelist of allowed URLs, and only forward the user if the URL they supplied is in the GET variable is in the list.

PHP Login System problem... Sending errors from page to page

I have a login form in every page of a website so the user can login from everywhere. I have a login.php file that I refer to it from the form (using 'action').
I use $_SERVER['HTTP_REFERER'] to redirect the user to the same page he logged in from when he succesfully log in or when he logs out.
But if there was a problem logging in, how can I send an error to the same page he is trying to log in?? I have tried sending the error using $_GET, like this:
// process the script only if the form has been submitted
if (array_key_exists('login', $_POST)) {
// Login code goes here...
// If there was a problem, destroy the session and prepare error message
else {
$_SESSION = array();
session_destroy();
header('Location: '.$_SERVER['HTTP_REFERER'].'?error');
exit;
}
But the problem is that a lot of pages in the website are like this details.php?mid=0172495. They already recive information from the $_GET method and for security reasons I cant use another $_GET method...
So, How can I pass the error???
Thanks...
Since you're already using sessions, after you destroy the session why not create a new one with $_SESSION['error'] or something similar set? Or alternatively simply don't delete the session at all but set the error which you can immediately check in other pages?
To add to what Chad Birch said...
In your login script where you redirect, check the HTTP_REFERER value for the character '?'. If it is present, append '&error' to the HTTP_REFERER and redirect to that. Otherwise append '?error' to the HTTP_REFERER and redirect to that.
I'm not sure what exactly you mean by "for security reasons I cant use another $_GET method", but in the case that there's already something in the query string, you just need to append another variable to it, instead of replacing it.
That is, if the address is like details.php?mid=0172495, you should be sending them to details.php?mid=0172495&error, whereas if it was just details.php, you send them to details.php?error.
Another way of doing what you need is to include your login.php file in every page that has the login form and just post to that same page. So you won't need any redirection at all.
This maybe is not a good scalable and maintainable solution, but it is simple. It all depends what kind of app you are writing. But you are saying that you are new to php so you can start like this. You can always go fancy later...

Is this method good/secure enough for showing errors to users? - PHP

I'm developing a website, and due to user-input or by other reason, I need to show some error messages.
For this, I have a page named error.php, and I get the error number using $_GET. All error messages are stored in a array.
Example:
header( 'Location: error.php?n=11' );
But I don't want the users to the enter the error code in the URL and see all the other error messages.
For preventing that, I thought I could whitelist the referer page, and only show the error message if the referer is found in my whitelist.
It should be fair similar to this (haven't tested yet ;) )
$accept = false;
$allowedReferer = array (0=>'page1.php', 'page2.php');
if (in_array($_SERVER['HTTP_REFERER'], $allowedReferer )) {$accept = true;}
if ($accept) { $n=$_GET['n'];echo "Error: " . $errorList[$n];}
Is this method good enough to avoid the spy-users?
I'm doing this with PHP5
Thanks
No, it isn't remotely secure: the HTTP Referer header is trivial to spoof, and is not a required header either. I suggest you read this article for an example of exploiting code (written in PHP), or download this add-on for Firefox to do it yourself from the comfort of your own browser.
In addition, your $allowedReferer array should contain full URL's, not just the script name, otherwise the code will also be exploitable from remote referrals, e.g. from
http://www.example.org/page1.php
To summarise: you cannot restrict access to any public network resource without requiring authentication.
Rather than redirect, you could simply display the error "in place" - e.g. something as simple as adapting your present code with something like
if ($error_condition)
{
$_GET['n']=11;
include "/path/to/error.php";
exit;
}
In practice it might be a little more sophisticated, but the idea is the same - the user is presented with an error message without redirecting. Make sure you output some kind of error header, e.g. header("HTTP/1.0 401 Bad Request") to tell the browser that it's not really seeing the requested page.
If you do want to redirect, then you could create a "tamperproof" URL by including a hash of the error number with a salt known only to your code, e.g.
$n=11;
$secret="foobar";
$hash=md5($n.$secret);
$url="http://{$_SERVER['HTTP_HOST']}/error.php?n={$n}&hash={$hash}";
Now your error.php can check whether the supplied hash was correctly created. If it was, then in all likelihood it was created by your code, and not the user.
You shouldn't use an external redirect to get to an error page. How I structure my PHP is like this:
I have a common file that's included in every page, with common functions: handle login/logout, set up constants and the like. Have an error() function there you can pass error information to that will show an error page and exit. An alternative is to use the index.php?include=pagename.php idiom to achieve common functionality but I find this far more flaky and error prone.
If you externally redirect the client (which you obviously need to do sometimes) never rely on the information passed via that mechanism. Like all user input it's inherently untrustworthy and should be sanitized and treated with extreme caution. Don't use cookies either (same problem). Use sessions if you need to persist information between requests.
HTTP_REFERER can be spoofed trivially by those with enough incentives (telnet is the tool of choice there), and shouldn't be trusted.
Error messages should never reveal anything critical anyhow, so I'd suggest you to design your error messages in such a way that they can be showed to anyone.
That, or use random hashes to identify errors (instead of 11, use 98d1ud109j2, etc), that would be stored in a central place in an associative array somewhere:
$errors[A_VERY_FATAL_ERROR] => "308dj10ijd"
Why don’t you just include the error message script? And to get rid of previous output data, use the output control to buffer it and clear it on error:
if ($error) {
ob_clear();
$errorCode = 11;
include 'error.php';
exit;
}
Instead of redirecting to an error page why not include an error page. You can restrict access to a directory containing the php files that contain the error content with .htaccess:
RedirectMatch 404 ^error-pages/*$
and inside the error-pages you can have include-able pages which display errors.
With this method you can be sure that no one can directly access the pages in the error-pages directory yet you can still include them within scripts that are publicly accessible.
If you handle errors before sending headers, you can easily create a function that outputs a basic html page with content, and exit right after it. That way there is no specific need for any other page (apart from the functions page, I guess).
It's as simple as checking if there's a problem, and if there is a problem, just call the function.
I use a function like this that even writes data away when it is called, so I have my own error logs...

php/html - http_referer

I am creating a website and on one particular page, am wanting to send the user back to the previous page. I am fairly new to PHP/HTML and have been using some existing code for ideas and help.
The existing code uses the following method:
if (! empty($HTTP_REFERER))
{
header("Location: $HTTP_REFERER");
} else
{
header("Location: $CFG->wwwroot");
}
However, when I use this code the HTTP_referer is always treated as empty and the user redirected to the root page. Any obvious flaws in this code?
Don't rely on the HTTP Referrer being a valid or even non-empty field. People can choose to not have this set leaving any checks for that variable going to the empty side of the IF-ELSE clause.
You can guard against this by sending along a parameter in either the URL or POST parameters that would hold a value that you can use to redirect the user back to.
You need to use:
$_SERVER['HTTP_REFERER']
isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
If you wanted to send the person back to the previous page and have it work regardless of the referrer being set correctly, you can append a GET parameter to the URL (or POST).. you will need to encode the URL.. Something like
http://www.domain.com.au/script.php?return=http%3a%2f%2fwww.domain.com.au%2fthis-is-where-i-was%2f
You can use PHP's urlencode() function.
Also note that the referer header might be empty or missing anyway, so you shouldn't rely on it at all..
You should use
$_SERVER['HTTP_REFERER']
However look at the register_globals configuration in php.ini, it should be turned off due to security reasons. You can read more on PHP Manual site.

Categories