0
require("database.php");

if(empty($_SESSION['user']))
{
    header("Location: login.php");

    die("Redirecting to login.php");
}

//check session timeout
$now = time();


$limit = $now - 60 * 1;

if (isset ($_SESSION['last_activity']) && $_SESSION['last_activity'] < $limit)
{
  $_SESSION = array();
  header('Location: login.php');
  exit;
} 
else {

  $_SESSION['last_activity'] = $now;
 }

The coding works fine if I put the session timeout in each and every page manually. But if I try to store it in another file and call it to each page,it will be ignored and i wont get any session time out.

Example

require("database.php");
require("expired.php");

if(empty($_SESSION['user']))
{
    header("Location: login.php");

    die("Redirecting to login.php");
}

expired.php contains the same coding as my //check session timeout, Any help will be appreciated. Thanks.

Edited to include my database.php

$username = "";
$password = "";
$host = "";
$dbname = "";

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

try
{
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect to the database: " . $ex->getMessage());
}

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
    function undo_magic_quotes_gpc(&$array)
    {
        foreach($array as &$value)
        {
            if(is_array($value))
            {
                undo_magic_quotes_gpc($value);
            }
            else
            {
                $value = stripslashes($value);
            }
        }
    }

    undo_magic_quotes_gpc($_POST);
    undo_magic_quotes_gpc($_GET);
    undo_magic_quotes_gpc($_COOKIE);
}

header('Content-Type: text/html; charset=utf-8');

if(!isset($_SESSION)){
session_start();
}
//session_start();
  • are you calling `session_start()` on each page? – Class Apr 03 '13 at 06:51
  • require("database.php") has my DB info and call for session start at the end of the page like this. if(!isset($_SESSION)){ session_start(); } – Salehin Suhaimi Apr 03 '13 at 06:53
  • @SalehinSuhaimi - session_start() should be at the top of the php-script (and I would skip the isset()-part). Just to a session_start() at the top of database.php – bestprogrammerintheworld Apr 03 '13 at 06:55
  • and you probably don't need if isset for `session_start` – Class Apr 03 '13 at 06:57
  • Correct me if i'm wrong, but my idea is like this. On each page, i will need database access, so i will call database.php on top of every page. And at the end of the page, it will start a session IF the session hasn't been set. So technically, that is the same as having the session_start on top of every page. And i need the isset function because i include 2-3 file in 1 index.php so it will give me a ignoring session_start() in.... I'm still learning, pardon me. – Salehin Suhaimi Apr 03 '13 at 07:02
  • Please supply your code that actually sets the session. Then it would be easier to understand and give you feedback. – bestprogrammerintheworld Apr 03 '13 at 07:04
  • added my database.php per request – Salehin Suhaimi Apr 03 '13 at 07:07
  • session_start will start a session if session is not started. If session is already exists, then it will use that session – Amit Apr 03 '13 at 07:08
  • pardon me? thats quite confusing, mind explaining it a bit more please? – Salehin Suhaimi Apr 03 '13 at 07:10
  • session_start - Start new or resume existing session, so you do not need to check whether a session is started or not. PHP will automatically start/resume a session using SESSION ID – Amit Apr 03 '13 at 07:13
  • @Amit it means that for one user will create one `SESSION ID` and in other page use same ID. If write `session_start();session_start();` you will get warning. – Narek Apr 03 '13 at 07:15
  • See session start documentation. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling. – Amit Apr 03 '13 at 07:19
  • from PHP 4.3.3 onwards, session_start after the session was previously started will result in an error of level E_NOTICE and second session start will simply be ignored. But, $_SESSION will be populated after you start the session and in your case isset($_SESSION) will always return false, as you use this check to start the session. So statement if (!isset($_SESSION)) has no use in your code and you can simply remove it – Amit Apr 03 '13 at 07:22
  • @SalehinSuhaimi - Your code should work involving the sessions, but $_SESSION = array() wont actually delete the session, it will give the $_SESSION an empty array. I think you should take look at http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes , because I think this is what you want? – bestprogrammerintheworld Apr 03 '13 at 07:24
  • @amit then how do i check if the session is started or not? Except calling session_start on each page. – Salehin Suhaimi Apr 03 '13 at 07:25
  • You do not need to check whether session is started or not, simply calling session_start will start the session if it is not started. If it is active, then it will be resumed – Amit Apr 03 '13 at 07:31
  • @bestprogrammerintheworld i noticed that. And fixed it with unset($_SESSION) or session_unset() and also session_destroy, to no avail. – Salehin Suhaimi Apr 03 '13 at 07:35
  • @Amit you mean that if i just put session_start() on top of each page, and i include 3 page that has session_start(), it will not give any warning like Notice : ignoring session right? Will try it now – Salehin Suhaimi Apr 03 '13 at 07:35
  • Yes, it will give a warning, but you should include session_start statement in one file which you include in all your pages. If that is not feasible for you then you can suppress the warning by putting @ before session_start like @session_start() – Amit Apr 03 '13 at 07:41

3 Answers3

1

Your won't get the same effects with your first example (Example1) and your second (Example2) because the code are ordered diffrently.

Example1 and Example3 have the code in the same order, so it should result in the same behaviour.

Of course you could argue about the session_start() (where to put it etc) but that was not really your question.

Example 1:

require("database.php");

if(empty($_SESSION['user']))
{
    header("Location: login.php");

    die("Redirecting to login.php");
}

//check session timeout
$now = time();


$limit = $now - 60 * 1;

if (isset ($_SESSION['last_activity']) && $_SESSION['last_activity'] < $limit)
{
  $_SESSION = array();
  header('Location: login.php');
  exit;
} 
else {

  $_SESSION['last_activity'] = $now;
 }

Example 2:

require("database.php");
require("expired.php");

if(empty($_SESSION['user']))
{
    header("Location: login.php");

    die("Redirecting to login.php");
}

Example 3:

require("database.php");

if(empty($_SESSION['user']))
{
    header("Location: login.php");

    die("Redirecting to login.php");
}

require("expired.php");
bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72
1

if session isn't started then $_SESSION should not exist. By the way, session_start() returns TRUE on success, FALSE on failure.

So keeping this in mind, you should write something like this:

/* File: session.php */
if ( session_id() == ''){ // If session id doesn't exist

   if ( ! session_start() ){ // Do start a new session
      die('Cannot start a session'); 
   }
}

Then you would include this part where you want to.

Yang
  • 8,580
  • 8
  • 33
  • 58
-1

Keep

session_start();

on top of each page, then do not use it inside your page or include page.

If you still want to use session_start() inside your pages, use it like this:

if(!session_start()){
    session_start();
}

you can tell php.ini to throw which type of errors, search for "error_reporting" and read rules. Warnings do not stop the execution of your code.

justnajm
  • 4,422
  • 6
  • 36
  • 56