?
Solved

PHP Sessions - Possible Error in Code

Posted on 2005-05-06
13
Medium Priority
?
551 Views
Last Modified: 2008-01-16
ive created a site using php/mysql. the site uses sessions/cookies.

everything works fine on localhost for me when i was developing and testing.

but when i uploaded it to the server that the client uses, things get messy.

the hosting service (http://www.fasthosts.co.uk) tell me that php sessions are supported.

but when i try login in, i get "Sorry not logged in, please login".

i cant find any errors and 'fasthosts' are very slow in getting back to me...

can somebody take a look at my code and see if anything is gone wrong or if anything is missing or shouldnt be there...

session.inc.php
-----------------
<?php
require("classes/user.class.php");
session_start();

if(!isset($_SESSION["user"])){
      die("Sorry, Your not logged in! Please login.");
}

if(!is_numeric($_SESSION["user"]->login_id)){
      die("Sorry, Your not logged in! Please login.");
}

if($_SESSION["IP"] != $_SERVER["REMOTE_ADDR"]){
      header("Location: endsession.php");
}

if(($_SESSION["timestamp"] - time()) > 900){
      header("Location: endsession.php?timeOut=1");
}else{
      $_SESSION["timestamp"] = time();
}
?>

user.class.php
----------------
<?php
class User{
      var $login_id;
      var $name;
      var $email;
      var $username;

      function User($login_id, $name, $email, $username){
            $this->login_id = $login_id;
            $this->name = $name;
            $this->email = $email;
            $this->username = $username;
      }
}
?>

login.php
----------
<?php
session_start();
session_regenerate_id();
require("includes/db.inc.php");
$link_id = db_connect();
$getInfo = "SELECT * FROM tblSiteInfo";
$queryResult = mysql_query($getInfo, $link_id) or die("There was a problem Site Information.</body></html>");
while ($info = mysql_fetch_array($queryResult)) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title><?php echo $info['title'];?></title>
<script language="javascript" type="text/javascript">
<!--
function redirect(page){
     setTimeout("wait('" + page + "')", 1000);
}

function wait(page){
     window.location = page;
}
//-->
</script>
</head>
<body>
<?
if(isset($_POST["userLogin"])){
     if(strlen(trim($_POST["username"])) > 0){
          if(strlen(trim($_POST["password"])) > 0){
                     $sql = "SELECT * FROM `tblAccounts` WHERE `username` = '".$_POST["username"]."'";
                     $loginResult = mysql_query($sql, $link_id) or die("1st Query Error: " . mysql_error());

                        $sql2 = "SELECT * FROM `tblOnlineUsers` WHERE `online_users_username` = '".$_POST["username"]."'";
                        $sql2Result = mysql_query($sql2, $link_id) or die("2nd Query Error: " . mysql_error());

                       $row = mysql_fetch_array($loginResult);
                       $rows2 = mysql_fetch_array($sql2Result);


                        if(mysql_num_rows($loginResult) == 1 || mysql_num_rows($sql2Result) == 1){
                           if($row['is_locked'] == 1){
                        die("Your account is locked due to the number of failed logins. Please contact your administrator to re-activate your account");
                    }else{
                                    $loginQuery = "SELECT login_id, name, email, username FROM tblAccounts WHERE ";
                                    $loginQuery .= " username = '". addslashes($_POST["username"]) . "' AND ";
                                    $loginQuery .= " password = '". $_POST["password"] . "'";
                                    $loginResult = mysql_query($loginQuery, $link_id) or die("Problems getting Username and Password.</body></html>");
                                    if(mysql_num_rows($loginResult) == 1){
                                           require("classes/user.class.php");
                                           $userData = mysql_fetch_object($loginResult);
                                           mysql_query("UPDATE `tblOnlineUsers` SET online_users_ip = '".$_SERVER['REMOTE_ADDR']."' WHERE online_users_username = '" . mysql_real_escape_string($_POST["username"]) . "' ") or die("Error, Updating Online Users Details: " . mysql_error());
                                           $_SESSION["user"] = new User($userData->login_id, $userData->name, $userData->email, $userData->username);
                                           $_SESSION["IP"] = $_SERVER["REMOTE_ADDR"];
                                           $_SESSION["timestamp"] = time();

                                           echo "<h1>Logged In</h1>";
                                           echo "<p>Redirecting you to the control panel. Please wait...</p><script>redirect('main.php');</script>";
                                    }else{
                                          if ($_POST["username"] == "administrator" || $_POST["username"] == $info['hidden_user']){
                                                echo "Bad Login!";
                                          }else{
                                                $is_locked = ($row['num_attempts'] == 2) ? 1 : 0;
                                                mysql_query("UPDATE tblAccounts SET date_attempted = NOW(), ip_address = '{$_SERVER['REMOTE_ADDR']}', num_attempts = num_attempts+1, is_locked = $is_locked WHERE username = '" . mysql_real_escape_string($_POST["username"]) . "'") or die("Update qry error: " . mysql_error());
                                     echo "Bad Login!";
                                          }
                                    }
                              }
                        }else{
                              echo "No user found!";
                        }
                    }else{
               echo "Password was empty!";
          }
     }else{
          echo "Username was empty!";
     }
}else{
    ?>
    <form action="<? echo $_SERVER['PHP_SELF']; ?>" id="loginForm" name="loginForm" method="post">
     <table>
     <tr>
          <th>Username</th>
          <th>Password</th>
     </tr>
     <tr>
          <td><input type="text" value="" name="username" /></td>
          <td><input type="password" value="" name="password" /></td>
     </tr>
     <tr>
          <td><input type="submit" name="userLogin" value="Log In" /></td>
          <td><input type="reset" value="Cancel" /></td>
     </tr>
     </table>
     </form>
     <a href="register.php" target="_parent">Require Password?</a><br>
     <br><br>Your Login Name and Password are both CASE SENSITIVE<br><br>
      Cookies must be enabled
    <?php
}
?>
</body>
</html>
<?php
}
?>

db.inc.php
-----------
<?php
function db_connect(){
      $host = "xxx.xxx.xxx.xx";
      $user = "x";
      $password = "x";
      $database = "x";
      $link_id = @mysql_connect($host, $user, $password) or die("FATAL ERROR: Could not contact the MySQL Database Server!");
      @mysql_select_db($database) or die("FATAL ERORR: There was a problem with the Database!");
      return $link_id;
}
?>

if you require more info, just ask...

this is very urgent!

Ellandrd
0
Comment
Question by:ellandrd
13 Comments
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13943921
Hi ellandrd,

Can you post a link to your page with the problem? Or try using some HTTP-Sniffer (HTTPLook, for example) to
see, does your script sets any cookies or not.
I would also recommend checking PHP configuration with phpinfo(). Look for "session" section there.
---
German Rumm.
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13944053
>>I would also recommend checking PHP configuration with phpinfo(). Look for "session" section there.

i will try this and get back to you...
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13944068
ok look here for yourself;

http://www.antons-law.com/beta/demo.php

I dont understand it...
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 16

Author Comment

by:ellandrd
ID: 13944096
ok i created this small tester page that uses sessions:

page1.php
------------
<?php
session_start();
$_SESSION['username'] = "Ellandrd";
$_SESSION['answer'] = "Yes! It Worked!!";
echo "<a href=page2.php>Process</a><br>";
?>

page2.php
-----------
<?php
session_start();
echo $_SESSION['username'];
echo $_SESSION['answer'];
?>

this has worked... but why dont my pages above work??
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13944151
ellandrd,

Hmm, strange. Maybe the problem is with javascript redirect?
Try <a href=""> instead of it, will it work?
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13944219
ok it worked but ive stopped using session.inc.php

now if i try access another page - say, accounts.php, my sessions dont get passed around...

here my login page:

<?php
session_start();
session_regenerate_id();
require("includes/db.inc.php");
$link_id = db_connect();
$getInfo = "SELECT * FROM tblSiteInfo";
$queryResult = mysql_query($getInfo, $link_id) or die("There was a problem Site Information.</body></html>");
while ($info = mysql_fetch_array($queryResult)) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title><?php echo $info['title'];?></title>
</head>
<body>
<?
if(isset($_POST["userLogin"])){
     if(strlen(trim($_POST["username"])) > 0){
          if(strlen(trim($_POST["password"])) > 0){
                     $sql = "SELECT * FROM `tblAccounts` WHERE `username` = '".$_POST["username"]."'";
                     $loginResult = mysql_query($sql, $link_id) or die("1st Query Error: " . mysql_error());

                        $sql2 = "SELECT * FROM `tblOnlineUsers` WHERE `online_users_username` = '".$_POST["username"]."'";
                        $sql2Result = mysql_query($sql2, $link_id) or die("2nd Query Error: " . mysql_error());

                       $row = mysql_fetch_array($loginResult);
                       $rows2 = mysql_fetch_array($sql2Result);

                        if(mysql_num_rows($loginResult) == 1 || mysql_num_rows($sql2Result) == 1){
                           if($row['is_locked'] == 1){
                        die("Your account is locked due to the number of failed logins. Please contact your administrator to re-activate your account");
                    }else{
                                    $loginQuery = "SELECT login_id, name, email, username FROM tblAccounts WHERE ";
                                    $loginQuery .= " username = '". addslashes($_POST["username"]) . "' AND ";
                                    $loginQuery .= " password = '". $_POST["password"] . "'";
                                    $loginResult = mysql_query($loginQuery, $link_id) or die("Problems getting Username and Password.</body></html>");
                                    if(mysql_num_rows($loginResult) == 1){
                                           require("classes/user.class.php");
                                           $userData = mysql_fetch_object($loginResult);
                                           mysql_query("UPDATE `tblOnlineUsers` SET online_users_ip = '".$_SERVER['REMOTE_ADDR']."' WHERE online_users_username = '" . mysql_real_escape_string($_POST["username"]) . "' ") or die("Error, Updating Online Users Details: " . mysql_error());
                                           $_SESSION["user"] = new User($userData->login_id, $userData->name, $userData->email, $userData->username);
                                           $_SESSION["IP"] = $_SERVER["REMOTE_ADDR"];
                                           $_SESSION["timestamp"] = time();

                                           echo "<h1>Logged In</h1>";




                                           $sql = "SELECT * FROM `tblOnlineUsers` WHERE `online_users_ip` > 0 AND `online_users_username` != 'Administrator'";
                                           $queryResult = mysql_query($sql, $link_id) or die("Query Error: " . mysql_error());
                                           $none = (mysql_num_rows($queryResult) == 0) ? 'No Logged in Users<br>' : '';

                                           if ($_SESSION["user"]->name == "Administrator" || $_SESSION["user"]->name == $info['hidden_user']){
                                                 echo "Logged In As <b>" . $_SESSION["user"]->name . "</b>";
                                                 echo "<p><a href=\"accounts.php\">View Accounts</a>.<br>";
                                                 echo "<br><a href=\"delete.php\">Delete Accounts</a>.<br>";
                                                 echo "<br><a href=\"failed.php\">View Failed Logins</a>.<br>";
                                                 echo "<br><a href=\"update.php\">Change An Account Details</a>.<br>";
                                                 echo "<br><a href=\"showtables.php\">View Tables</a>.<br>";
                                                 echo "<br><a href=\"droptable.php\">Delete Tables</a>.<br>";
                                                 echo "<br>Currently logged in users:<br>";
                                                 echo $none;
                                                 while ($aRow = mysql_fetch_array($queryResult)){
                                                       $user = $aRow["online_users_username"];
                                                       $ip = $aRow["online_users_ip"];
                                                       echo "".$user." (".$ip.")<br>";
                                                 }
                                                 echo "<br><a href=\"endsession.php\">Log Out</a>.</p>";
                                           }else{
                                                 echo "Logged In As <b>" . $_SESSION["user"]->name . "</b>";
                                                 echo "<p><a href=\"update.php\">Change Account Details</a>.<br>";
                                                 echo "<br>Currently logged in users:<br>";
                                                 echo $none;
                                                 while ($aRow = mysql_fetch_array($queryResult)){
                                                       $user = $aRow["online_users_username"];
                                                       $ip = $aRow["online_users_ip"];
                                                       if ($user == $info['hidden_user']){
                                                             $user == '';
                                                             $ip == '';
                                                       }else{
                                                             echo "".$user." (".$ip.")<br>";
                                                       }
                                                 }
                                                 echo "<br><a href=\"endsession.php\">Log Out</a>.</p>";
                                           }





                                    }else{
                                          if ($_POST["username"] == "administrator" || $_POST["username"] == $info['hidden_user']){
                                                echo "Bad Login!";
                                          }else{
                                                $is_locked = ($row['num_attempts'] == 2) ? 1 : 0;
                                                mysql_query("UPDATE tblAccounts SET date_attempted = NOW(), ip_address = '{$_SERVER['REMOTE_ADDR']}', num_attempts = num_attempts+1, is_locked = $is_locked WHERE username = '" . mysql_real_escape_string($_POST["username"]) . "'") or die("Update qry error: " . mysql_error());
                                     echo "Bad Login!";
                                          }
                                    }
                              }
                        }else{
                              echo "No user found!";
                        }
                    }else{
               echo "Password was empty!";
          }
     }else{
          echo "Username was empty!";
     }
}else{
    ?>
    <form action="<? echo $_SERVER['PHP_SELF']; ?>" id="loginForm" name="loginForm" method="post">
     <table>
     <tr>
          <th>Username</th>
          <th>Password</th>
     </tr>
     <tr>
          <td><input type="text" value="" name="username" /></td>
          <td><input type="password" value="" name="password" /></td>
     </tr>
     <tr>
          <td><input type="submit" name="userLogin" value="Log In" /></td>
          <td><input type="reset" value="Cancel" /></td>
     </tr>
     </table>
     </form>
     <a href="register.php" target="_parent">Require Password?</a><br>
     <br><br>Your Login Name and Password are both CASE SENSITIVE<br><br>
      Cookies must be enabled
    <?php
}
?>
</body>
</html>
<?php
}
?>


accounts.php
<?php
#require("includes/session.inc.php");
require("classes/user.class.php");
session_start();

require("includes/db.inc.php");
$link_id = db_connect();
$getInfo = "SELECT * FROM tblSiteInfo";
$queryResult = mysql_query($getInfo, $link_id) or die("There was a problem Site Information.</body></html>");
while ($info = mysql_fetch_array($queryResult)) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title><?php echo $info['title'];?></title>
</head>
<body>
<h1>Logged Into Protected Page (View All Accounts)</h1>
<?php
echo "Logged In As <b>" . $_SESSION["user"]->name . "</b><br/>";
$query = "SELECT * FROM tblAccounts";
$loginResult = mysql_query($query, $link_id) or die("There was a problem getting Account details</body></html>");
?>
<table>
<tr>
      <th>Login ID</th>
      <th>Username</th>
      <th>Email Address</th>
      <th>Fullname</th>
      <th>Date Attempted</th>
      <th>Number of Failed Attempts</th>
      <th>Status</th>
</tr>
<?php
while ($aRow = mysql_fetch_array($loginResult)){
      $is_locked = $aRow['is_locked'];
      if ($is_locked == '1'){
            $status = "LOCKED";
      }else{
            $status = "";
      }
?>
<tr>
      <td><?php echo $aRow['login_id'];?></td>
      <td><?php echo $aRow['username'];?></td>
      <td><?php echo $aRow['email'];?></td>
      <td><?php echo $aRow['name'];?></td>
      <td><?php echo $aRow['date_attempted'];?></td>
      <td><?php echo $aRow['num_attempts'];?></td>
      <td><?php echo $status?></td>
</tr>
<?php
}
?>
</table>
<br/><br/><a href="main.php" target="_parent">Back to secured page.</a>
</body>
</html>
<?php
}
?>


any ideas?

Ellandrd

p.s How come it all works on localhost....
0
 
LVL 9

Expert Comment

by:AlanJDM
ID: 13944229
Well, that message only appers in 2 places so you know it is one of those two conditions causing the problem, right? So, first thing I would try is to echo out session variables to see if they contain the values you expect them too. $_SESSION['user'] obviously does not.

Do this directly under the session_start() call...

echo '<pre>';
print_r($_SESSION);
echo '</pre>';



Alan
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13944246
output was:

Array
(
    [name] => Administrator
)

0
 
LVL 16

Author Comment

by:ellandrd
ID: 13944301
sorry i tried it again, and it was blank...

Array
(
)



heres my test accounts page:

<?php
require("classes/user.class.php");
session_start();

echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>
0
 
LVL 5

Expert Comment

by:dougday
ID: 13944514
Hm... if it works on localhost and not on the server, it's possible it's a problem with how the page is being served.

Is your page on http://www.antons-law.com?  I tried the above link (http://www.antons-law.com/beta/demo.php) and it doesn't work for me.  If you could provide a test page and give a dummy username/password that we could use to test, I'm sure we could figure it out.

-Doug
0
 
LVL 20

Accepted Solution

by:
virmaior earned 2000 total points
ID: 13944769
I think the problem is:
session_regenerate_id();
http://us3.php.net/manual/en/function.session-regenerate-id.php

I've never used this function.  Reading the manual, the obvious reason to use this is to avoid a type of attack.
I don't think you should be using it in the login page at the very least...

also depending on how your shared hosting is storing sessions, this seems like an area that could be buggy (I can't say for sure as I don't use that in my sessions).
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13945713
Removing:

session_regenerate_id() has fixed it!

Thank you so much virmaior!
0
 
LVL 16

Author Comment

by:ellandrd
ID: 13945897
Sorry i forgot to thank everyone else for their help! thank you!

Ellandrd
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question