Sessions not working PHP - php

My website doesn't start a session when I visit, I don't know why but my website works like this:
<?php
session_start();
$title = "Home";
include("include/header.php");
include("include/functions.php");
?>
...HTML stuff here...
<?php
include("footer.php");
?>
But when I check with Cookies (add-on for Firefox) there are no sessions started... I used session_regenerate_id(); but it doesn't work at all.
It fails to log in since there are no sessions, I do not have any session_destroy() in my website, only in the logout.
But funny thing is, when I login (without refreshing or navigating just yet) and then click on the logout button, there is a session on my website, then when I log in again, it tells me that I am logged in BUT if I login and navigate or refresh, it doesn't tell me that I'm logged in since there are no sessions...
Logout:
<?php
session_start();
session_destroy();
setcookie("cookie-name", "", time()-60, "", "", 0);
header("Location: ../index.php");
exit;
?>
What do I do?

You must have session_start() at the beginning of every file that is being accessed and uses sessions. The name is misleading, session_start() actually doesn't start a new session but initialzes PHP session menagment.

Not sure if it's related, but there was a strange PHP quirk that required the SESSION_START() to be on the line immediately below the <?php tag. Something about whitespace and extra things above the session used to make it go haywire for me. I've been using Zend of late, which avoids that issue with its own session handling system.
You might try doing a print_r($_SESSION) to see if there's anything in the session array at all.

It's probably because you are not setting a session in either of the examples you have given, you have to have a line like the one below to actually create a session, and then to access the session variables on all subsequent pages you need session_start();
$_SESSION['example'] = 'something';

It doesn't look like your setting anything in the session or the cookie.
If you want to pass information around in the session you'll need to assign the necessary values in the $_SESSION variable.
For example on your main page you can do:
<?php
session_start();
$_SESSION['myVariable'] = "my text";
?>
And then on any subsequent pages you can access the variable you've set.
<?php
session_start();
echo $_SESSION['myVariable']; //This will print "my text"
?>

Related

Session variables not being created if the user doesn't log out before logging back in

When the user logs in, multiple session variable are created and work perfectly.
When they sign out and log in again it works.
However, when someone quits out of their browser without signing out, the next time they log in no session variables are created.
To sign out, one goes to my logout.php file. The code in my logout.php file is:
<?php
session_start();
session_destroy();
echo '<meta http-equiv="refresh" content=".000001;url=index.php">';
?>
I've tried pasting the code at the start of my index.php (where the login form is) but it doesn't work unless you go to the logout.php file.
Why is this and how do i fix it?
There are some possible situations:
First and main reason:
If you have already started session_start(), server may be dump error, while you trying to create new, if your errors are off, you can't see them.
Second: You do check before session destroy.
You are destroying the session before you are making sure that no session variables remain.
I would delete all of the session variables first before you destroy it, to be safe, because sometimes some get left behind. You can do this like so
if (isset($_SESSION['/*whatever session variables you are using*/'])) {
$_SESSION = array();
session_destroy();
}
Also if you are using any cookies for any reason (though this may not be the case), you need to make sure those are also deleted. something like this:
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(),'',time() - 3600);
}

PHP session variables life

Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>

Ending A Session, Reset Variables Not Working?

I am writing a script which is supposed to end a session for a user, and log them out of the system, thus returning them to the login page.
My logout script looks like this:
<?php
$_SESSION['signin'] = null;
session_destroy();
header("Location: /test/index.php");
?>
Initially I reset the signin variable that way even if the session isn't destroyed the variable should have at least changed so that the system believes the user is logged out.
And at the top of my login page I have a condition to forward them to the home page if they are already logged in, that way that can't visit the log in page once already logged in. This portion looks like this:
<?php
session_start();
if($_SESSION['signin'] == 5)
{
header("Location: /test/home.php");
}
?>
So in short, when someone is logged in, and clicks the link to logout it utilizes the first code block to log out, and then is forwarded to the page containing the second blcok of code.
However, this page still forwards me back to the home page, believing the user is still signed in and thus I'm guessing the signin variable was not reset.
Thoughts on how to solve my issue?
session_destroy() does not unset any of the global variables within the session. Simply using:
session_unset();
to unset all global variables, or to only unset the specified variable, use:
unset($_SESSION['signin']);
You can try something like this.
session_unset()
you don't have to use
$_SESSION['signin'] = null;
using session_destroy(); should be enough
and I don't exactly know the deep stuff of PHP, but if you set a $_SESSION variable to NULL, PHP could read it as it is set to NULL which means 'it is set'? (don't know for sure though)
In this case, if you want to destroy a variable, you could do this:
Have a page named logout.php and whenever the user needs to logout, redirect him/her to that page. Now, inside that page you'll put the following, and here I'll explain you what this does:
<?php
session_start(); //Initializes the session
unset($_SESSION['thenameofyoursession']); //This unsets a specific session, so the user is logged out, in this case it would unset "thenameofyoursession".
$URL="/test/home.php"; //This is the redirect URL
header ("Location: $URL"); //This basically will send the user back to the redirect URL using header.
die(); //terminates the PHP script from running
?>
With that you should be fine.
Your procedure is fairly obvious and similar to one that we use, however, it would be best to unset() the entire session if nothing in it is valid. -- If they aren't logged in, no session variables should exist.
My logout.php script includes this:
session_start();
session_register("loginMessage");
session_unregister("authenticatedUser");
session_destroy();
// relocate back to login page
header("Location: /");
Which works. session_unset() is historically redundant.
Hope this helps.

PHP $_SESSION variable will not unset

sorry for a repetitive question, I've seen a few of these on this forum but none of the responses worked for me...
I am building a basic login using php sessions, which I'm new at...
login.php validates html login form and begins a session, setting variables: $_SESSION['login'] and $_SESSION['id],
then each page that requires a valid login uses require 'session.php'; which checks the $_SESSION['valid'] variable and redirects a user w/o proper login variable. The problem is when I logout neither session variable I've set will unset.
Right now my logout.php file uses about every method to destroy the variables that I've been able to find online and none will actually do it.
So whenever I log out, I can still access the 'private' pages.
Also note: I have tried it w/o a session name ex: session_start(); that didn't work so now I'm using session_start("user");
Also note: I am NOT using cookies.
Here are the files I mentioned:
login.php
$email=$_POST['email-log']; $pass=$_POST['password-log'];
$i=-1;
do
{$i++; $path="users/".$i.".json";
$file= file_get_contents($path);
$x=json_decode($file,true);
} while($x['email']!=$email);
$id=$i;
$truepass=$x['pass'];
$errors=0;
$hash=hash('sha256',$pass);
if($hash != $truepass){$errors=$errors+1;}
if($errors==0){
session_start("user");
$_SESSION['login']="valid";
$_SESSION['id']=$id;
header('Location: loginlanding.php');}
else{header('Location: front.php?error=y');}
session.php
session_start("user"); if($_SESSION['login'] !== "valid") {header('Location: front.php?needto=login');}
logout.php
unset($_SESSION); unset($_SESSION['login']); unset($_SESSION['id']); session_unset("user"); $_SESSION=array(); session_destroy("user"); header('Location: front.php?logged=out');
Any and all responses are welcome and I thank you in advance, also note, I am new to logins in general so any advice to beef up security is welcome also. I'm planning on making it more secure, but first I need to get this basic functionality up and running.
You should never unset($_SESSION).
The easiest way to clear the $_SESSION variable is $_SESSION = Array();
However, you can also iterate with unset:
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
It's amazing how many things you're attempting to do after you've unset the only reference you had to the session in the first place. Directly from the manual:
Caution
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.
http://php.net/manual/en/function.session-unset.php
You're unsetting $_SESSION so your unsets to the other arrays of the super global $_SESSION aren't registering, leaving them still in the browsers temporary cookies. Use session_unset() instead if you're trying to remove all session variables. Otherwise, don't unset the session global, but unset each individual value of it you want to remove.
My working example (notice that you must put start on the call)
<?php
session_start();
session_unset();
session_destroy();
header('location: ./');
?>

PHP Session issues in Chrome

I have a web app I am developing for a school project, I am having issues with the logout page. When a user clicks logout it will send them to a logout.php which just looks like this:
<?php include ("includes/check_authorization.php");
// Unset the session and destroy it
session_unset();
session_destroy();
// Redirect to the home page
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
exit;
?>
It is very simple, but it will unset, then destroy the session, and redirect to the index, which is the login page. However when this is run the index immedietley redirects to a user homepage. The check_authorization page included at the top will redirect someone to login if the username and id are not set and matching in the $_SESSION, so this means that it is setting these for me? I am really confused as to how this is happening. I am using CAS for authentication.
EDIT: the check_authorization.php also initializes the session as well as checking those key values
For like this situation I did as follows, this is working for me all the browsers,
#session_unset();
$old_sessid = #session_id();
#session_regenerate_id();
$new_sessid = session_id();
#session_id($old_sessid);
#session_destroy();
Rather than just unsetting the data, try assigning a dummy value to the session, like:
$_SESSION['authKey'] = '!!INVALID!!';
session_unset();
session_destroy();
Even if the session 'revives', the authentication can't possibly succeed anymore because of the "fake" data.
There are some possibilities :
The most simple possibility : did you include the
session_start();
on top the file? before you include a file? I've been there before, and it pissed me off.
The second possibility : try to put
session_regenerate_id();
on the very top of your file (before you declare session_start();). Because in some Server Hosting, their configuration still using "LINUX" style that i can't explain to you here. But, the point is they always using "cache" when you redirect. In other words, you always redirect into your "cached" page when you rediret to another page. See.. it's hard to explain for you here. But just try the session_regenerate_id(); code, maybe it would work.
I never use the "echo" things in doing redirect things. Try :
header("location:index.php");
i don't know if this working or not. I just simply giving you my analysis based of my assumptions.
Hope these helpful. :)

Categories