Jump to content

Sessions problem - HELP!


ianh

Recommended Posts

It appears that my '/tmp' folder on my shared hosting (GoDaddy) account is full with session files and it seems I have to wait (up to 72hrs) for their hopeless admins to clear out the folder.

 

The strange things is everything was working fine a couple of days ago.

Now sometimes I get errors on my PHP page saying disk is full and session cache error. Sometimes don't even get these errors. I can't seem to get back these errors now. Is there anyway to generate session or disk errors in PHP?

 

Also, the login page doesn't work. It just doesn't login and reloads itself each time.

I think it might be due to either the '/tmp' folder being full or it's getting confused with session variables that haven't been destroyed. I'm really not sure?

 

Any help or insight would be much appreciated.  :confused:

 

 

Class creating the session variables and verifying login:

 

<?php session_start();

//global $loginTime;


/**
* LoginSystem
* 
* Simple Login system with sessions and MySQL User DB
* 
* @version		1.0
* @author 		A.Surrey	(www.surneo.com)
* 
* 
*/

class LoginSystem
{
    var	$db_host,
	$db_name,
	$db_user,
	$db_password,
	$connection,
        //$userid, //added by IH 18-January-2011
	$username,
	$password,
        $userip,
        $loginTime,
        $timeout;

/**
 * Constructor
 */
function LoginSystem()
{
	require_once('../../config/settings.php');

	$this->db_host = $dbhost;
	$this->db_name = $dbname;
	$this->db_user = $dbuser;
	$this->db_password = $dbpassword;
}

/**
 * Check if the user is logged in
 * 
 * @return true or false
 */
function isLoggedIn()
{
	if($_SESSION['LoggedIn'])
	{
		return true;
	}
	else return false;
}

/**
 * Check username and password against DB
 *
 * @return true/false
 */
//function doLogin($username, $password)
    function doLogin($username, $password, $userip)
{
        $timezone  = 0; //(GMT -5:00) EST (U.S. & Canada)
        $loginTime = gmdate("Y-m-j H:i:s", time() + 3600*($timezone+date("I")));

        $this->connect();

	$this->username = $username;
	$this->password = $password;
	$this->userip = $userip;

	// check db for user and pass here.
	//$sql = sprintf("SELECT UserID, UserName, Password FROM Users WHERE UserName = '%s' and Password = '%s'",
        $sql = sprintf("SELECT UserID, UserName, FullName, Password FROM Users WHERE UserName = '%s' and Password = '%s' AND ActiveUser = '1'",
										$this->clean($this->username), md5($this->clean($this->password)));

	$result = mysql_query($sql, $this->connection);

	// If no user/password combo exists return false
	if(mysql_affected_rows($this->connection) != 1)
	{
		$this->disconnect();
		return false;
	}
	else // matching login ok
	{
		$row = mysql_fetch_assoc($result);

            $userid = $row['UserID'];

		// more secure to regenerate a new id.
		session_regenerate_id();

		//set session vars up
		$_SESSION['LoggedIn'] = true;
		$_SESSION['userName'] = $this->username;
		$_SESSION['userID'] = $row['UserID'];
		$_SESSION['fullName'] = $row['FullName'];


            //$this->getLoginTime();
	    //return $this->loginTime;

            //#### WORKING QUERY - MANUAL DATE VALUE ####
            //$sql2 = 'UPDATE Users SET LastLogin = "2011-01-18 23:55:32" WHERE UserID = "' . $userid.'"';
            //#######################//

            //$sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'" WHERE UserID = "'.$userid.'"';
            $sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'", UserIP = INET_ATON("'.$this->userip.'") WHERE UserID = "'.$userid.'"';
            $result2 = mysql_query($sql2, $this->connection);
            //echo '<script>alert("'.$sql2.'");</script>';




	}

	$this->disconnect();
	return true;
}


   function sessionTimer()
   {
        //unset($_SESSION['timeout']);
        session_start();

        $this->inactivesession = $inactivesession;
        // set timeout period in seconds (14400 = 4 hours)
        $this->inactivesession = 1400;
        $this->session_life = $session_life;

        // check to see if $_SESSION['timeout'] is set
        if(isset($_SESSION['timeout']) ) {
          $this->session_life = time() - $_SESSION['timeout'];
          if($this->session_life > $this->inactivesession)
          {
            session_destroy();
            //header("Location: logout.php?msg=2");
            return true;
          }
          else {
            return false;
          }
        }
        //$_SESSION['timeout'] = time() + $this->session_life;
        $_SESSION['timeout'] = time() + $this->inactivesession;
        //$_SESSION['timeout'] = time();
        //return false;
}





/**
 * Destroy session data/Logout.
 */
function logout()
{
	unset($_SESSION['LoggedIn']);
	unset($_SESSION['fullName']);
	unset($_SESSION['userName']);
	unset($_SESSION['userID']);
        unset($_SESSION['timeout']);

	session_destroy();
}

/**
 * Connect to the Database
 * 
 * @return true/false
 */
function connect()
{
	$this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) 
													or die("Unable to connect to MySQL");

	mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!");

	// Valid connection object? everything ok?
	if($this->connection)
	{
		return true;
	}
	else return false;
}

/**
 * Disconnect from the db
 */
function disconnect()
{
	mysql_close($this->connection);
}

/**
 * Cleans a string for input into a MySQL Database.
 * Gets rid of unwanted characters/SQL injection etc.
 * 
 * @return string
 */
function clean($str)
{
	// Only remove slashes if it's already been slashed by PHP
	if(get_magic_quotes_gpc())
	{
		$str = stripslashes($str);
	}
	// Let MySQL remove nasty characters.
	$str = mysql_real_escape_string($str);

	return $str;
}

/**
 * create a random password
 * 
 * @param	int $length - length of the returned password
 * @return	string - password
 *
 */
function randomPassword($length = 
{
	$pass = "";

	// possible password chars.
	$chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J",
		   "k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T",
		   "u","U","v","V","w","W","x","X","y","Y","z","Z","1","2","3","4","5","6","7","8","9");

	for($i=0 ; $i < $length ; $i++)
	{
		$pass .= $chars[mt_rand(0, count($chars) -1)];
	}

	return $pass;
}
}

?>

 

 

Login page:

 

<?php session_start();

    require ('class/MathGuard.class.php');
require_once('class/LoginSystem.class.php');

    $userip = $_SERVER['REMOTE_ADDR'];

if(isset($_POST['Submit']))
{
	if((!$_POST['Username']) || (!$_POST['Password']))
	{
		// display error message
		header('location: login.php?msg=1');// show error
		exit;
	}

        // ######## MatchGuard check ########
        if (!MathGuard :: checkResult($_REQUEST['mathguard_answer'], $_REQUEST['mathguard_code']))
        {
            //show_error ("Incorrect Security Code entered");
            header('location: login.php?msg=3');
            exit;
        }

	$loginSystem = new LoginSystem();
	if($loginSystem->doLogin($_POST['Username'],$_POST['Password'],$userip))
	{
		/**
		 * Redirect here to your secure page
		 */
		header('location: view_articles.php');

	}
	else
	{
		header('location: login.php?msg=2');
		exit;
	}
}

/**
 * show Error messages
 *
 */
function showMessage()
{
	if(is_numeric($_GET['msg']))
	{
		switch($_GET['msg'])
		{
			//case 1: echo "Please fill both fields.";
                case 1: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Please fill in all fields!</p></div>';
			break;

			//case 2: echo "Incorrect Username or Password!";
                case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Username or Password!</p></div>';
			break;

			//case 3: echo "Incorrect Security Code";
                case 3: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Security answer!</p></div>';
			break;
		}
	}
}

/*
function show_error($myError)
{
    echo $myError;

//stop executing script and display the form
exit();

}*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<meta name="robots" content="noindex, nofollow" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/supersleight.js"></script>
<script type="text/javascript">
$(document).ready(function(){
		$(".block").fadeIn(1000);
		$(".msg").fadeIn(1000);	
		$('.msg').supersleight();
});
</script>
</head>

<body>
    <div id="wrap">
        <?php showMessage();?>
        <div class="block">
            <div class="head">
                <h3>Login</h3><!--<a href="#">Forgot Password?</a>-->
            </div>
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <div class="body">
                <div class="div-row">
                   <label for="username">Username</label><input type="text" id="Username" name="Username" maxlength="30" />
                </div>
                <div class="div-row">
                    <label for="password">Password</label><input type="Password" id="Password" name="Password" maxlength="30" />
                </div>
                <div class="div-row">
                    <?php MathGuard::insertQuestion(); ?>
                </div>
                <div class="send-row">
                    <button id="login" value="Login" type="submit" name="Submit"></button>
                </div>
            </div>
            </form>
        </div>
    </div>
</body>
</html>

 

 

Make pages secure include:

 

<?php session_cache_expire(240);
session_start();

require('./class/LoginSystem.class.php');

$loginSys = new LoginSystem();
/**
* if not logged in goto login form, otherwise we can view our page
*/
if(!$loginSys->isLoggedIn()) {
  header("Location: ./login.php");
  exit;
}




$sessionTime = new LoginSystem();
if($sessionTime->sessionTimer()) {
    header("Location: ./logout.php?msg=2");
exit;
}

?>

 

 

Logout page:

 

<?php session_start();
require('class/LoginSystem.class.php');

$loginSys = new LoginSystem();
$loginSys->logout();

function showMessage()
{
    if(is_numeric($_GET['msg']))
        {
            switch($_GET['msg'])
            {
                case 1: echo '<div class="msg" style="border:1px; border-color:#8be57e; background:#b4efab; color:#337129;"><img src="images/icons/succes.png" alt=""/><p>You have logged out successfully.</p></div>';
                break;

                case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Due to inactivity your session has expired.</div>';
                break;
            }
        }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<meta name="robots" content="noindex, nofollow" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
<link rel="stylesheet" type="text/css" href="css/ui.dialog.css" />
<style type="text/css">
body{
  background-image: none;
}
</style>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/supersleight.js"></script>
<script type="text/javascript">
$(document).ready(function(){
		$(".block").fadeIn(1000);
		$(".msg").fadeIn(1000);
		$('.msg').supersleight();
});
</script>
</head>
<body>
<div id="wrap">
    <?php showMessage();?>
    <div class="block">
        <div class="head">
            <h3>Logged Out</h3>
        </div>
            <div class="body">
              <p align="center"><font color="#000000"><b>Redirecting to the 'Login' page in <span id="seconds" style="color:#ff0000;">10</span> seconds.</b></font></p>
              <script language="JavaScript">
              var seconds = 10;
              setInterval(
                function(){
                    if (seconds <= 1) {
                        window.location = 'http://domain.tld/cms/login.php';
                    }
                    else {
                      document.getElementById('seconds').innerHTML = --seconds;
                    }
                    },
                    1000
              );
              </script>
              <br><br>
              <p align="center">If you are not redirected, go straight to the <a href="login.php"><font size="3" color="blue"><b>Login</b></font></a> page.</p>
            </div>
    </div>
</div>
</body>
</html>

 

 

MathGuard class (works fine and I have not changed anything in this file)

 

<?
class MathGuard {

/** A main hashing function: concat of user's answer, hour and the additional prime number (default 37) */
function encode($input, $prime) {
	return md5($input.date("H").$prime);
}

/** This function generates the hash code from the two numbers 
 * @param $a 	first number
 * @param $b	second sumber
 * @param $prime	additional number to encode with
 * */
function generateCode($a, $b, $prime) {
	$code = MathGuard::encode($a + $b, $prime);
	return $code;
}

/** This function checks whether the answer and generated security code match 
 * @param $mathguard_answer		answer the user has entered
 * @param $mathguard_code		hashcode the mathguard has generated
 */
function checkResult($mathguard_answer, $mathguard_code, $prime = 37) {

//		echo("prime; $prime, $mathguard_answer");
	$result_encoded = MathGuard::encode($mathguard_answer, $prime);

	if ($result_encoded == $mathguard_code)
		return true;
	else
		return false;

}

/** this function inserts the two math term into your form, the parameter is optional */
function insertQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter
	$a = rand() % 10; // generates the random number
	$b = rand() % 10; // generates the random number
	$code = MathGuard :: generateCode($a, $b, $prime);
	echo ("<label for=mathcheck>Security: $a + $b =</label>
             <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />");

}

/** this function returns math expression into your form, the parameter is optional 
 * quite simmilar to insertQuestion, but returns the output as a text instead of echoing
 */
function returnQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter
	$a = rand() % 10; // generates the random number
	$b = rand() % 10; // generates the random number
	$code = MathGuard :: generateCode($a, $b, $prime);
	return ("<label for=mathcheck>Security: $a + $b =</label>
			<input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />");

}

}
?>

 

edit: removed domain name

Link to comment
Share on other sites

You need to make your own folder within your account's folder tree and set your session.save_path setting to point to your own folder so that you session data files will be stored in your own folder.

 

You need set the session.save_path before every session_start() statement, so it is best if you do this in a .htaccess file (when php is running as an Apache Module) or in a local php.ini (when php is running as a CGI application) or in your script.

 

Link to comment
Share on other sites

PFMaBiSmAd thank you so much!  :)

 

I couldn't get the .htaccess to work (seemed to generate internal server error).

 

.htaccess file (not working)

php_value session.save_path "/mypathgoeshere"
php_value session.gc_maxlifetime 14400
php_value session.gc_probability 1

 

 

So I ended up putting the following code in each of my PHP pages containing session_start() which worked.

 

PHP (working)

session_save_path('/mypathgoeshere');
ini_set('session.gc_maxlifetime', 14400);
ini_set('session.gc_probability', 1);
session_start();

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.