i am having a debate on what would be a better method for loging out in php , if someone could help me clarify i would be most gratefull :
I have two versions of the code for log out
1 )
$logoutGoTo = "login.php";
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['username'] = NULL;
$_SESSION['user_id'] = NULL;
unset($_SESSION['username']);
unset($_SESSION['user_id']);
$_SESSION = array();
if ($logoutGoTo != "") {header("Location: $logoutGoTo");
exit;
2)
session_start();
session_unset();
session_destroy();
Which is the better solution?
Generally neither because they both essentially destroy the entire session.
Sessions aren't just for keeping user's logged in. Sessions are used to track other data which may not be linked to a user's account and so you might not want to destroy it when logging out.
Take this for example, you store the language setting in the session. Now the user logs out, you want to keep language setting but logout the user. If you destroy the session then all other data your tracking is destroyed.
I would simply unset/remove the session variables that are keeping the user logged in.
It depends on your situation. If you hold more data in session then login information it would be not a good idea to unset the whole session. Otherwise the second version seems a bit cleaner.
It depends. If you don't have any other $_SESSION variables you want to keep, and your project has more than one developer, #2 is definitely the better option.
On the other hand, if you either have other $_SESSION variables, or you are developing all by yourself, then you might want to use #1 (you will be able to keep track of all the $_SESSION variables you set and unset, which is a "reminder" for you, but be careful not to forget any variables that you need to unset).
Related
I only store logged users id in SESSION.
When a user logs out, SESSION becomes useless for me. Do I have to destroy it?
These are the methods of Utils class which I am using to start and destroy SESSION.
static function sessionSecureStart()
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
static function sessionSecureDestroy()
{
//Utils::sessionSecureStart(); This part is for testing only
if (session_status() == PHP_SESSION_ACTIVE) {
$_SESSION = [];
session_destroy();
}
}
Sometimes randomly I get errors/warnings like SESSION could not be destroyed.... Am I doing something wrong?
(I am using PHP/5.5.25)
You don't have to destroy the whole session, just unset the parts you don't need. Let's say that when a user logs in that you set $_SESSION['user_id'] and everything that says I am logged in is looking for that variable. A simple unset($_SESSION['user_id']); and suddenly the user is logged out. Remember, your user doesn't have control over what's in the session.
Another option is to set the session cookies to very low lifetimes. It's cruder but just as effective.
I highly advice you to destroy the session. For both security and performance.
Normally session data is saved in temporary files on the server and in a cookie on the browser, this one only contains the session id but no data.
When you call session destroy you delete this file but you also might tel the browser to delete the session cookie (sending a cookie with the same name which expires in the past). You can know the name calling the session_name() function (normally it's PHPSESSID).
When a user logs out, SESSION becomes useless for me. Do I have to destroy it?
Yes. Besides destroying it, it's also helpful to generate a new session-id
Sometimes randomly I get errors/warnings like SESSION could not be destroyed.... Am I doing something wrong?
You cannot destroy a session that haven't been started. Make sure you have successfully initiated your sessions with session_start(); before trying to destroy it
I'm working on a login system for a site and just want to make sure that my actual login and logout core functions are correct.
To login I have:
session_start();
session_regenerate_id(true);
$_SESSION["user"] = $username;
$_SESSION["startTime"] = time();
Then later to logout I have
unset($_SESSION["user"]);
unset($_SESSION["startTime"]);
session_destroy();
Is this correct or can this be improved in any way? And can someone clarify what session_regenerate_id(true) is really doing? I inherited it from some preexisting code.
1/You may not need this code in the login part:
session_regenerate_id(true);
For more info about it, please visit the PHP manual here:
http://www.php.net/manual/en/function.session-regenerate-id.php
2/To log the user out, the session values will be reset, the session data will be destroyed on the server.
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
If you decide to change the session name later, this code will still be accurate.
i dont really think you need to do unset($_SESSION["user"]); actually session_destroy() is enough . once you call session_destroy() thats enough and after calling it there will not be any $_SESSION["user"]
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.
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: ./');
?>
Which one is the better way to handle login in PHP?
#1 PHP.net
$email = $_POST['email'];
$password = $_POST['password'];
if($user->connection($email,$password)){ // user logging validation
session_start(); //start the session
$_SESSION['user_logged'] = true; // user logged in
header('location : control_panel.php'); // go to control panel
}
else { // go back to logging page
header('location : logging.php?' . $user->error_string);
}
#2 Me after Paul Dixon's improvements and Sebasgo's improvements
if (isset($_REQUEST['email'])) {
$result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users
WHERE email=$1;");
$passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email']));
session_start();
$_SESSION['logged_in'] = false;
if ($passhash_md5 == $_REQUEST['passhash_md5']) {
$_SESSION['logged_in'] = true;
}
header('Location: index.php');
The code #2 has $_REQUEST commands because I am still trying to get it work.
You shouldn't try to manage the session ids yourself. A simple scheme like the one you propose (incrementing the session id by one for every new session) contains a serious security issue: A user with freshly generated session id can trivially guess other valid session ids by trying ids slightly smaller than its own. Thus it is very easy two acquire someone else's session.
If you let PHP manage the generation of new session ids for you, PHP uses a pseudo random generator to create the new ids, which will be hard to guess for a potential attacker. This prevents the above outlined attack scenario effectively.
Additionally, you will virtually never want to access $_SESSION before calling session_start() because before the session array will be always empty. Therefore your test of empty($_SESSION['SID']) will always raise false.
Bottom line: I strongly recommend you to stick to the simple way of managing login like PHP.net does it.
You force all new sessions to have the same ID, which means everyone will be sharing the same session! Probably not what you intended?
You can omit the call to session_id() and just let PHP take care of creating a unique id for the session.
Also, you should really call session_start before using the $_SESSION array to ensure it is populated with any current session variables.