php set session with cookies - php

$_SESSION['user_id'] = $login;
setcookie('user_id', '$login' , time()+86000);
header('Location: userindex.php');
function logged_in() {
return (isset($_SESSION['user_id']) || isset($_COOKIE['user_id']) ? true : false;
}
I have SESSION but I wonna include COOKIE too but I don't know how to restart SESSION with COOKIE. I don't have a idea how I can get that. I create COOKIE but can't logout and have problem with SESSION somebody can help me to fix my problem???? And in every page on top I have logged_in function for check if user is logged in or not I wonna these logged_in function to check if user has cookie to auto login to user cookie. I think it is in logged_in function must get write some code and...

I will note that this is not secure, as any one can create the cookie, using something like firebug.
#session_start();
function logged_in() {
if(!isset($_SESSION['user_id']) && isset($_COOKIE['user_id'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
}
return isset($_SESSION['user_id']);
}
function logout() {
unset($_SESSION['user_id']);
setcookie("user_id", "", time() - 3600);
header("Location: http://".$_SERVER['HTTP_HOST']);
exit;
}
Edit: Added logout() - will remove both session and cookie 'user_id', then redirect to homepage

First: you should set it with:
setcookie('user_id', $login , time()+86000);
So $login without quotes. And also maybe set path variable if this cookie should be seen in different pages.
Removing cookie is done with setting negative time value:
setcookie('user_id', '' , time()-86000);

session_start();
function logged_in() {
if(!isset($_SESSION['user_id']) && isset($_COOKIE['user_id'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
}
return (isset($_SESSION['user_id'])) && isset($_COOKIE['user_id'])));
}

Related

How to authenticate securely by session tokens and cookies? updated

I tried to write my own authentication method (school project), and I'm stuck.
Please advise, how to solve a secure authentication:
There is an index.php which contains everything that needs to be "protected". I will copy the relevant parts of my code here.
updated index.php
session_start();
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['PHPSESSID'])){
if ($_SESSION['PHPSESSID'] == $_COOKIE['PHPSESSID']){
$authStatus = true;
}
}
return $authStatus;
}
if(!checkUserAuth()){
include_once(dirname(__DIR__).'/admin/authentication/login.php');
exit();
}
If the checkUserAuth() determines, that there is no properly authenticated user, will include the login.php and stop the rest of the script.
updated login.php:
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
$_SESSION['PHPSESSID'] = $_COOKIE['PHPSESSID'];
$_SESSION['login_user'] = $_POST['user'];
What I imagine that might happen, is that if the login details are correct, the login.php sets a cookie, and refreshes the page. Then the index.php will detect the cookie, and skip the login part.
The login is pretty much figured out, and thanks to Juned, I think it is working now. However I don't know how secure is this?
On a scale from 1 to very, how wrong I am?
There are loads of ways of doing this. The below pseudocode is not the most efficient but should work and I don't think what you've done above will actually work.
Does this help?
login.php pseudocode
<?php
session_start(); // this function checks if there's a session ID already set, if not, sets one.
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
// do your login details checking here
// if login details correct
// set a flag in the $_SESSION superglobal and whatever else you want to store about the user like their username e.g.
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = "$_POST['user']"; // better practice to fetch a clean version from your database
//else return user to login page
}
?>
index.php pseudocode
<?php
session_start(); // this will fetch the session ID and other variables that you might have set e.g. username, logged in status
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true){
$authStatus = true;
}
return $authStatus;
}
if(!checkUserAuth()){
// redirect to login page. e.g.
header('Location: login.php');
exit;
}
?>

How to delete session of The HTTP_USER_AGENT

In order to increase the security for the logged-in users, after the session_start(); and assigning the other session variables, I also try to store the HTTP_USER_AGENT value, using $_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']); for the login.php page.
Besides, in the login.php page, I redirect logged-in users to the home page if they try to visit it again without logging it out first, using the conditional like this:
if (isset($_SESSION['agent']) OR ($_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']) ) ) {
//redirect to home page
header('location:http://index.php.com');
exit();
}
The question is that in my logout.php page I code the conditional like this:
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT']) ) ) {
//Redirect to home page
}else{
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
setcookie (session_name(), '', time()-3600); // Destroy the cookie.
}
Then I came back to visit the login.php page again as a logged-in user (session has been set), it still redirected me to the home page.
Then I tried deleting the cookies in the FF browser, close it, then revisited the login.php page, it still redirected me.
Do you know what I was wrong or missing?
NOTE: I have no problem to destroy the session if not storing **the HTTP_USER_AGENT
You have an assignment where you want to check.
Change:
if (isset($_SESSION['agent']) OR ($_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']) ) ) {
to
if (isset($_SESSION['agent']) OR ($_SESSION['agent'] == md5($_SERVER['HTTP_USER_AGENT']) ) ) {
off topic security tip(maybe helpfull):
public function Start_Secure_Session()
{
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params
$cookieParams = session_get_cookie_params();
// Set Cookie Params
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $this->isHTTPS, $this- >deny_java_session_id);
// Sets the session name
session_name($this->session_name);
// Start the php session
session_start();
// If new session or expired, generate new id
if (!isset($_SESSION['new_session']))
{
$_SESSION['new_session'] = "true";
// regenerate the session, delete the old one.
session_regenerate_id(true);
}
}

Can not log out correctly PHP

I can log in and access all member pages, but when I log out, I can still access all memberspages
I use this code to log out:
$_SESSION["admin_id"] = false;
$_SESSION["username"] = null;
redirect_to("login.php");
and this code to check if a user is logged in,
function logged_in() {
return isset($_SESSION["admin_id"]);
}
function confirm_logged_in($page) {
if (!logged_in()) {
redirect_to($page);
}
}
he redirects me after i have used the log out code. But i can still type in the member page URL and access them like I am logged in. I use an other webbrowser its impossible, so the pages are protected correctly. Or do I need to destroy the cookie and session complectly?
Here's what you're doing when you logout.
You are setting admin_id to false (which is technically a value).
$_SESSION["admin_id"] = false;
You then check to see whether admin_id is set:
isset($_SESSION['admin_id'); // returns TRUE because it "IS SET" to false
Options
You can either check whether admin_id is not empty (which handles null, false, 0).
function logged_in() {
return ! empty($_SESSION["admin_id"]);
}
You can extend your current function.
function logged_in() {
return isset($_SESSION["admin_id"] && $_SESSION["admin_id"] !== false);
}
You can set the variable to null.
$_SESSION['admin_id'] = null;
You can destroy the session completely.
session_destroy();
In place of:
$_SESSION["admin_id"] = false;
Try this:
unset($_SESSION["admin_id"]);
If you really need to log out, in my opinion your best option is to invalidate the session with a simple session_destroy().
By doing this you can check $_SESSION with the isset() function without problems, since every parameter belonging to the old session has been unset.

$_SESSION cookies not expiring when browser is closed

So here is my code that sends an expire time of a year if remember me is clicked.
And if not, then it sets the session_set_cookie_params() to 0. Which means that it should destroy the session when browser is closed. However it isn't working like that for some reason.
This is my login page:
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {
if (isset($_POST['rememberme'])) {
$_SESSION['username'] = $user;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (60*60*24*365);
}
else{
$_SESSION['username'] = $user;
session_set_cookie_params(0);
}
header('Location: index.php');
} else {
$p->addContent('<font color = red>Wrong</font>');
}
}
This is my index page:
session_start();
if (isset($_POST['rememberme'])){
$user = $_SESSION['username'];
}
else {
$user = $_SESSION['username'];
session_set_cookie_params(0);
}
if ($user == null) {
$user = 'Guest';
$logout = $p->header()->addButton('Login', 'login.php', 'a', 'home', false, false, true);
$logout->rel('external');
}
else{
$logout = $p->header()->addButton('Logout', 'logout.php', 'a', 'delete', false, false, true);
$logout->rel('external');
}
It's quite simple. session_set_cookie_params(0); isn't affecting your session as you call it after calling session_start();.
Just reorder your code to something like this:
if (isset($_POST['username']) && isset($_POST['password'])) {
if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {
if (isset($_POST['rememberme'])) {
session_start();
$_SESSION['username'] = $user;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (60*60*24*365);
} else {
session_set_cookie_params(0);
session_start();
$_SESSION['username'] = $user;
}
header('Location: index.php');
} else {
session_start();
$p->addContent('<font color = red>Wrong</font>');
}
} else {
session_start();
}
EDIT:
It's also worth nothing that session_set_cookie_params only work on the current script and has to be called again every time you use session_start(). It might me useful to set a cookie to indicate if it should used.
As of your code, session_set_cookie_params() isn't called in any case. Therefore I propose to do this:
session_set_cookie_params(0);
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
...
Note, that's actually useful to call session_set_cookie_params() always for session cookies.
Generate a new session-ID at each user level change
To protect your applications against attackers, it is absolutely required to change the sessionID after each change of the role of a user:
Anonymous user -> Logged in user
Logged in user -> anonymous user
Logged in user -> Administrative logged in user
...
Thus, if user gets logged in or logged off, please regenerate the session ID like so:
session_regenerate_id( true );
Have a look in OWASP's PHP security cheat sheet.
Session-files get deleted regularly
Using PHP's standard session policy, sessions get mapped to regular files, so called session-files. If the user closes his browser, the session-file keeps living in the file system. Quite likely, the operation system is going to delete the session-file once a day (by night).
Thus, if a user comes back a day later, the sessionID cookie points to a session-file, which might no longer be available.
The case of public PCs
Additionally imagine a browser running on a public PC: If user closes his browser and a new user logs in, the other user gets automatically logged in.

php session lost after submitting form

The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.

Categories