PHP Session variables being unset - php

I've created a login which sets a session variable to the users id which I get from my database. After the user clicks login after entering their details I redirect them to the home page which uses the session variable to get the users id for display purposes. The problem I am having is with the session variable. This is what my code looks like (simplified):
$_SESSION['user_id'] = $User_id;
header('Location: http://localhost/Projects/Login/home.php');
exit();
This is the snippet of code which sets my session variable, I have tested an it works. The next snippet of code is the function which is called from the home page (home.php). It is used to check if the user is logged in or not
function logged_in(){
return isset($_SESSION['user_id']);
}
I then use this if statement to perform different displays based on whether the user is logged in or not, again it has been simplified.
if( logged_in() === true ){
$session_user_id = $_SESSION['user'];
print "logged in";
}
else{
print "not logged in";
}
The problem seems to be with the if statement as it unsets the session variable to an empty array. If I print out the session variable I get Array(). I have started a session on each of the pages.

There seem to be two issues here.
First is the array keys; you're using user in one case and user_id in the other.
The second is speculative; you said it results in an empty array (I assume you have var_dump($_SESSION) or similar to confirm this?). If so it suggests you haven't started the session. You need to call session_start(); to get access to the session data.
Each time your script runs it needs to get access to the sessions stored on the server, this is why you run session_start(). The long version is that it obtains a lock on the local file which stores the session data (leading to whats known as session locking). As a result you may (for longer running scripts and/or performance) wish to call session_write_close() when you're finished with the $_SESSION superglobal.

Related

PHP session variable not accessible on another page

After trawling through other posts, I could not find the answer.
The problem is that when i create a custom session name, I am not able to access session variables on any other pages. How can I get this working with custom session variable?
Scenario A
Login page
after successful login, the following is called
function initiatenewsession($app, $userid){
$session_name = getuniquesessionid($app,$userid); // Set a custom session name
session_name($session_name);
session_start();
session_regenerate_id(true);
$_SESSION["loggeduserid"] = $user_id;
echo("1a)SESSION NAME[".session_name()."]");
echo("1b)logged user[".$_SESSION["loggeduserid"]."]");
}
Echo result
1a) SESSION NAME[myappsessionid6520150528184534]
1b) logged user[65]
Registration page (User clicks a link after logging in)
session_start();
echo("2a)SESSION NAME[".session_name()."]");
echo("2b)logged user[".$_SESSION["loggeduserid"]."]");
2a)SESSION NAME[PHPSESSID]
2b)logged user[]
Scenario B
Login page
after successful login, the following is called
function initiatenewsession($app, $userid){
session_start();
session_regenerate_id(true);
$_SESSION["loggeduserid"] = $user_id;
echo("1a)SESSION NAME[".session_name()."]");
echo("1b)logged user[".$_SESSION["loggeduserid"]."]");
}
Echo result
1a) SESSION NAME[PHPSESSID]
1b) logged user[65]
Registration page (User clicks a link after logging in)
session_start();
echo("2a)SESSION NAME[".session_name()."]");
echo("2b)logged user[".$_SESSION["loggeduserid"]."]");
2a)SESSION NAME[PHPSESSID]
2b)logged user[65]
As per my comment, when you do session_start(), php will check if you set a session name via session_name(), otherwise it'll use its default.
Session startup is basically like this, in php-ish pseudocode:
if (custom_session_name_was_set()) {
$session_name = get_custom_session_name();
} else {
$session_name = ini_get('session.name');
}
if (isset($_COOKIE[$session_name])) {
$id = $_COOKIE[$session_name];
} else {
$id = generate_new_random_id();
setcookie($session_name, $id);
}
$session_data = file_get_contents('/path/to/session/files/' . $id);
$_SESSION = unserialize($session_data);
For your first bit of code, you set a custom name, so that's the name that's used for the session cookie.
In your other code, you do NOT set a custom name, so php uses its default: PHPSESSID. Now you've got two sessions floating around, each with their own unique names, and their own different IDs, and their own separate data in $_SESSION.
If you're going to be using custom session names, you have do session_name($customName) EVERYWHERE you have session_start().
If using a custom session name you must call session_name().
You must call session_start() before headers_sent().
On servers with multiple PHP version support check phpversion() to ensure that the server did not decide to run the wrong version (and hence the wrong session_save_path()).

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

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.

session set in folders php mysql

i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
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.

PHP Login, Store Session Variables

Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something

Categories