Jump to content

PHP Cookies/Sessions


rhyspaterson

Recommended Posts

Hey guys,

 

Have a login script that sets a cookie for authentication, and checks for a session variable when the user attempts to access a page. Everything works fine. The login script looks like this:

 

<?php
session_start();
// has the form been submitted?
if (!isset($_POST['submit'])) {
// are there session variables stored already?
    if (isset($_SESSION['username'])) {
        header("Location: /menu/index.php");
// no cookie has been set
    } else {
	include('menu/included_files/header_plain.inc');
	include('menu/included_files/login.inc');
	include('menu/included_files/footer.inc');
    }
} else {
// the form was submitted
    $username = $_POST['username'];
    $password = $_POST['password'];
    if ($username == "user" && $password =="test") {
        // Authenticated OK
	$_SESSION['username'] = $username;
        setcookie("authenticated", $username, time()+1, "/");
        header("Location: /menu/index.php");
    } else {
	include('menu/included_files/header_plain.inc');
	include('menu/included_files/login.inc');
	include('menu/included_files/footer.inc');
    }
}
?>

 

At the top of each of my pages i run a check to see if the user is logged in like so:

 

<?php
// Start Session
session_start();

// Check if user details have been stored in session vars yet
if (!isset($_SESSION['username'])){
   header("Location: http://xxx.xxx.xxx.xxx/");
}
// User is logged in
?>

 

I am trying to play around with the setcookie command for a timeout, as seen here:

 

setcookie("authenticated", $username, time()+1, "/");

 

Technically, i believe the user should have their cookie expire in 1 minute? However this does not appear to work. But what i really want to implement is an idle timer - wherein if the user is inactive for 300 seconds, the cookie/session is destroyed. Could anyone point me in the right direction?

Link to comment
https://forums.phpfreaks.com/topic/58030-php-cookiessessions/
Share on other sites

Thanks for the reply.

 

Does this negate the need for the

 

time()+[whatever number]

 

command in my initial cookie deceleration? I tried adding it to my page headers with no luck, the session stays logged in:

 

<?php

session_set_cookie_params(300);

// Start Session
session_start();

// Check if user details have been stored in session vars yet
if (!isset($_SESSION['username'])){
   header("Location: http://xxx.xxx.xxx.xxx/");
}
// User is logged in
?>

 

Have tried it both above and below the session_start(); command.

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/58030-php-cookiessessions/#findComment-287652
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.