Archive

Posts Tagged ‘php cookies fail’

php session/cookies failed on certain page

August 18, 2008 Leave a comment

Ever faced a situation where your supposed to be authenticated-by-session or cookie failed? it works initially, but on certain page, it fails.. and you don’t know what went wrong because you cold swear that the exact same piece of code works on the previous page but not on another page..!

Well, most probably here’s how your php authentication code look like, where you included it in every part of your php page, either using session or cookie. The example below uses session:
=======================================
session_start();

if ($_POST){
$_SESSION[‘user’]=$_POST[“user”];
$_SESSION[‘pass’]=$_POST[“pass”];
}

include (“dbconf.php”);    //the php file that contains the database settings
// query for a user/pass match
$result = mysql_query(“select status from login
where user='” . $_SESSION[‘user’] . “‘ and pass='” . $_SESSION[‘pass’] . “‘ “) or die (mysql_error());
=======================================

Then the code above works for first page, second page… but on the 3rd page it returns an error. Or sometimes the session/cookie suddenly disappeared, and it returns invalid username/password! Let me tell you two thing:

1) The page before the session/cookie fails have a Submit button with the method set as POST.
2) Now let me tell you where it went wrong. See the line if ($_POST){ above? THAT’s WHERE it went wrong. Instead of writing only $_POST, you should write something like ($_POST[‘username’] || $_POST[‘password’]) or whatever your username and password box named in the previous page. Because if you wrote only $_POST, and a page has a Submit button with method POST, the line if ($_POST) will trigger and passes the now empty $_POST[“USER”] to $_SESSION[‘user’] since there are no input box named as USER or PASSWORD in the page (and even if they do, most probably it’s not meant for password authentication), and of course, the sql query below it will return an error since it now queries using an empty or wrong $_SESSION[‘user’] and $_SESSION[‘pass’]!

I faced the above problem because I tend to copy paste codes from supposed-to-be session tutorial. IMHO, it’s a bad practise to write a tutorial which can complicate matters in the future, although probably they only meant to simplify things.

In summary, here’s how your session authentication should look like:

==============================

if ($_POST[‘username’] || $_POST[‘password’])
{
$_SESSION[‘username’]=$_POST[‘username’];
$_SESSION[‘password’]=$_POST[‘password’];
}
==================================

Hope this post helps someone out there!

Advertisements