# PHP cookie problem



## NeoPhyte101 (Sep 27, 2005)

Hi guys,

I'm new to php and having a problem. I have my basic login script which is trying to set a cookie. Once a user logs in they are sent to a welcome page and then they must click again for the cookie to load, and to be sent to the main page. The main page outputs info from user table based on the cookie stored.

From the examining the code it seems that the cookie is not being set so no info is displaying on my main page.


```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<?php
function func_generate_string() {
$auto_string= chr(mt_rand(ord('A'), ord('Z')));
for ($i= 0; $i<8; $i++) {
$ltr= mt_rand(1, 3);
if ($ltr==1) $auto_password .= chr(mt_rand(ord('A'), ord('Z')));
if ($ltr==2) $auto_password .= chr(mt_rand(ord('a'), ord('z')));
if ($ltr==3) $auto_password .= chr(mt_rand(ord('0'), ord('9')));
}
return $auto_string;
}

function FunJavaScriptRedirection($url)

{?>
<script type="text/javascript">

window.location = '<?=$url?>'

</script>
<?}
  if (isset($_POST['submit1'])) {


FunJavaScriptRedirection("http://localhost/register.php");
                              }

 if (isset($_POST['submit'])) { // if form has been submitted



$con = mysql_connect("localhost","root","*******");
    if (!$con)
    {
     die('Could not connect: ' . mysql_error());
    }

     mysql_select_db("ulmundo", $con);





if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {


   $username = $_POST['txtUserId'];
   $password = $_POST['txtPassword'];

   // check if the user id and password combination exist in database
   $sql = "SELECT userid
           FROM `ulmundo`.`users`
           WHERE username = '$username'
                 AND password = '$password'";

   $result = mysql_query($sql);
      //       or die('Query failed. ' . mysql_error());

   if (mysql_num_rows($result) == 1) {
      // the user id and password match,





     $user_obj= mysql_fetch_object($result);
      $user_id= $user_obj->userid;
    // now generate a random 8 char long string, and hash it with MD5
    $logcode= md5(func_generate_string());
    // now update users information in the database
    $result = mysql_query("UPDATE `ulmundo`.`users` SET logcode ='$logcode' WHERE userid = '$user_id'"); // or die('Could not update database.');
    // now, let us setup the identification information that will be passed to users computer via a cookie
    // we will store users ID and LOGCODE in ID:LOGCODE form so that we can later extract it using explode() function
     $newval= "$user_id:$logcode";
          setcookie( cookiename, $newval, time() + 300);




      // after login we move to the main page
      FunJavaScriptRedirection("http://localhost/logincongrat.php");
      exit;
   } else {
      echo("Wrong username or password" );

   }


}
}

?>
```
I have placed the php code at the start of the login page above html tags. When i run the script to check if the cookie has been loaded it does not enter the 

if (isset($_COOKIE['cookiename'])) {

Thanks guys any help would be great


----------



## Onetoomanysodas (Feb 27, 2008)

Well if what you posted is the actual code, `cookiename` is neither a variable nor a string...


----------



## Redcore (Aug 14, 2007)

I'm not sure where you got that code but it's pretty ugly. The first thing I noticed is "FunJavaScriptRedirection" function...you don't need it. "header" is a function already in PHP and it works so long as nothing is printed to the screen before it (the DOCTYPE code at the top should be stripped out).


```
<?php
if(isset($_COOKIE['userid']))
{
header('location: welcome.php');
}
```
If you are redirected, it worked (you can also just echo "$_COOKIE['userid']" but this script should be at the top of the pages you want the cookie to act on anyways).

FYI: cookie login systems are VERY simple...but when I first started with them I absolutely despised how every tutorial and sample script I found was completely over complicated and seemed to lack fundamentals (which creates security risks). One of them is password encryption. Every password should at least be encrypted with md5.



NeoPhyte101 said:


> Once a user logs in they are sent to a welcome page and then they must click again for the cookie to load, and to be sent to the main page.


I'm a bit confused by this process. Why do they need to click anything again? This will create user confusion problems. This is how I do it...

A) The user (in some way) lands on the login page (login.php) which is basically just the basic form with a username and password field.
B) When submitted, the page goes to "login_process.php" - which is pure script (meaning it doesn't have anything printed to the screen - since it's performed in microseconds, the user never sees it). This page goes through the validation process (BTW ideally all passwords stored in a database should be encrypted - I mentioned this before, but it's worth mentioning again) and if the validation checks out it sets the cookie at the bottom of the script and redirects with the "header" function (shown in the above example).
C) The user now lands on the "welcome.php" page or whatever page I want them to be on. They only had to click ONE submit button (with their username/password) and they're logged in and ready to go. There's an extra step with the scripting, but they don't know any better - in their eyes, it was a wham-bam login.



Login systems can be incredibly simple and incredibly complicated. I've built really complicated ones as I've improved as a PHP developer...but the fundamentals are ALWAYS the same (user submits credentials, credentials are validated, cookie is pushed, user goes on their happy way). The only things you can complicate is what happens after and what/how your website interacts with those who are logged in or not.


----------

