PHP Cookies not being loaded when coming from a clicked link - php

I'm working on a website that is keeping a user session token in $_SESSION. When I type the URL directly, I can load the cookies just fine, but when I click on a page that loads the cookie through PHP, it can't find the cookie. Is there any way to get around this?
Here's the code for saving the cookie
setcookie("tpl_token", $token, time()+365*24*60*60, "/");
And for retrieving
if(isset($_COOKIE['tpl_token'])){
$token = $_COOKIE['tpl_token'];
} else {
echo "Cookie not set";
}
It is returning that cookie is not set.

In order to create a session in PHP, use the session_start() function. PHP handles sessions internally for you, so you do not have to do any dirty work.
Example:
session_name("tpl_token");
session_start(); //sends session cookie with name "tpl_token"
//create session variable.
$_SESSION["logged_in"] = true;
if(isset($_SESSION["logged_in"])){
//stuff to do if user is logged in already
} else {
//stuff to do if user is not logged in.
}
//Destroy Session/Logout;
session_unset();
session_destroy();
If you are try create session cookies, there is no need for the $_COOKIE[] function

Related

Session reset without session_destroy is valid?

I'm trying to destroy the session without using session_destroy because I want to carry the information message. My question is if my code is valid, I already reset the session by saying all $_SESSION is an empty array or for security reason using the session_destroy is a must but if I use session_destoy I can't pass the $_SESSION['msg'] anymore.
<?
session_start();
$_SESSION = array();
//session_destoy();
$_SESSION['msg'] = "You have logged out.";
header('Location: index.php');
?>
You need session_unset()
session_unset just clears out the session for usage. The session is
still on the users computer. Note that by using session_unset, the
variable still exists. session_unset just remove all session
variables. it does not destroy the session....so the session would
still be active.
via: http://php.net/manual/en/function.session-unset.php
and then you can do it like
$_SESSION['msg'] = "You have logged out.";
so that the msg is added to session.
OR You can do it like this too:
$msg ="Whatever the message is";
header("Location: index.php?message=$msg ");
In index.php file
if(isset($_GET['message']) && !empty($_GET['message'])){
echo $_GET['message'];
}
1st you should use session_unset(); to remove all session variables/values rather than assigning a new array to it.
The main answer to your query:
I would recommend to use session_destroy() because it removes the internal session ID generated which would be validated at every request coming from a client device. To verify this, just print the session ID using the function echo session_id(); before and after emptying the session in the way you are doing. It would pring the same session ID.
So destroying it first and then creating new will be a good idea.
Once you destroy the session using session_destroy() you can start a new session again and set your message $_SESSION['msg'] in it.
Just user session_unset($_SESSION['session_name']); hope this will work.
You can use cookies; you would keep for example the username, the password and the connection status of the user. When the user comes back to your site, you know who he is and if he is already connected.
setcookie ("Msg", "you have logged out", time () + 3600);
(for a cookie of one hour, you put the time that you want ...)
Your code:
<?
session_start();
$_SESSION = array();
//session_destoy();
$_SESSION['msg'] = "You have logged out.";
header('Location: index.php');
?>
in the index page do below stuff:
<?php
if(!empty($_SESSION['msg']) && isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
this will show your message once and unset it immediately.

How to determine cookie validity?

I am starting the session as
session_start(); //So This session will get destroyed when user exit the browser
I set the cookie as
setcookie('cookie',$value,time()+3*60);
$_SESSION['cookie'] = true; //When user log in, I don't need to get the
salt again from db and do all the security
checks. Assume it as a cache
This suggesion is suggested in this question.
The problem is, cookie gets expired after 3 minutes. But session exists. So user tries to login after 3 minutes
if($_SESSION['cookie'])
{
//success
}
else
{
//Authenticate user
}
But this is wrong. Since cookie expired, else part should execute. But if part gets executed. I understand that session is still alive. How do I handle this situation?
I understand that it is due to that time()+3*60. But how do I implement that cache thing?
You need check cookie not in $_SESSION.
Check them in $_COOKIE.
As example:
if($_COOKIE['cookie'])
{
//success
}
else
{
//Authenticate user
}
Cookies and session variables are not related (except that PHP internally uses a cookie named PHPSESSID to connect the client to its session). Expiring the cookie doesn't have any effect on a session variable with the same name. If you want to test whether the cookie has expired, use:
if (isset($_COOKIE['cookie']))

User authentication Session is set from the start

I'm working on page authentication. It can login already, but I want it to make user authentication on other pages aswell if someone tries to access pages through URL. If the person is not a logged in user, redirect that person to the login page. I tried it by working with sessions but it doesn't work. I'm following MVC structure
Somehow the sessions never gets unset. I don't know why..
Here is how I did it
My loginController
<?php
//LoginController
if($_POST)
{
if(isset($_POST['submit']) AND $_POST['submit'] == "login")
{
$username = $_POST['username'];
$password = $_POST['password'];
try
{
include '../model/Login.php';
$login = new Login($db, $username, $password);
if($login == TRUE)
{
session_start();
$_SESSION['username'] = $username;
header("Location:../index.php");
}
}
catch (Exception $exc)
{
echo $exc->getMessage();
}
}
}
My index controller( for main page)
<?php
include 'model/Database.php';
session_start();
//Checks if the user is logged in.
if(!isset($_SESSION['username'])) {
//echo"<h2>You have no access to this page!";
include 'view/login.php';
die();
}
include 'c:/wamp/www/mvc/model/Display.php';
$displayPatients = new Display($db);
$dataDisplay = $displayPatients->getData();
include 'view/Main.php';
?>
my logout.php: When a user clicks this button:
<?php
//Logout
//destroys the session when the user clicks logout
session_destroy();
header('Location:view/login.php'); //redirect to the login
The user does get logged out redirected to the login page but the session is still set. The session is set from the beginning and I have no idea why..
Just taken out of the manual for the session_destroy()
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.
So it seems to me you need to destroy your session id or set it to something else when starting the new session otherwise your next sesson_start() resumes the old session again.
For this reason you could also just regenerate the session id on login before redirecting. Ah and it's always a good idea to use "exit;" after a "Location:" redirect via "header()".
session_start();
session_regenerate_id(true);

PHP Session not clearing?

I am using PHP sessions for a tool I have created. It allows for you to resume a previous session you may have started that is stored in the database. All that functionality is working as intended.
However, I provide a link that says "Create New Session" and point it to a PHP page that contains this code:
<?php
session_start();
session_destroy();
$_SESSION = array();
unset($_SESSION);
header('Location: wizard.php');
?>
Now, when it redirects back to wizard.php, I have it printing out all session details and it still contains information from the previous session.
Is there something I am missing here?
Wizard.php starts with session_create(); so I would assume as soon as it redirected it would create a new session ID and all which isnt happening.
Thanks for any info
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// Finally, destroy the session.
session_destroy();
header('Location: wizard.php');
?>
Taken from: session_destroy Example 1

Session problem during refresh

When i refresh my flex application, the page does not hold its state and gets back to login page. I am not sure why this occurs, Here is my peiece of code handling session.
public function doLogin($username,$password) {
include("connection.php");
session_start();
session_register("session");
$query = "SELECT *
FROM users
WHERE username = '".mysql_escape_string($username)."'
AND password = '".mysql_escape_string($password)."'";
$result = mysql_fetch_array(mysql_query($query));
if(!$result) {
session_unset();
return 'no';
}
else
{
$session['id']=session_id();
$session['username']=$username;
return 'yes';
}
}
public function Logout() {
session_start();
session_register("session");
session_unset();
session_destroy();
return 'logout';
}
Should i do something on my Flex pane which loads after a successful login.
your problem is here
else
{
$session['id']=session_id();
$session['username']=$username;
return 'yes';
}
}
$session is not defined... if you want to store something in the session array use $_SESSION
After successful login redirect back to some other page.
For example
if(doLogin($user,$pass) == 'yes')
{
Header("Location: index.php");
exit;
}
By refresh do you mean reload the page (F5). If so then that is the reason! A reload/refresh will reinitialise everything. So whatever is your starting state (login) will be shown when you reload/refresh.
If you wish to maintain the apps state then every time the state changes you would have to save its details to a DB then when the user hits the starting page reload their session.
If the browser gets refreshed/reloaded (or crashes etc) then you have no means of getting the app to logout the user, so you'd have to revert to the last know state when the login page gets hit. This would of course have major security issues if the user didn't log of properly.
Are you maintaining the session id in your flex application, and sending it along with new requests?
Can you test & confirm that the same session id is being returned from your PHP scripts on each request inside Flex?
Are you persisting the session id in a cookie outside of your flex application? If not, you will lose your session id on page refresh. You'll need to store in local storage or in a cookie, and access this when your flex application starts.

Categories