php - Check Session strange beahviour - php

EDIT: Just wanted to add that by not having
exit();
As pointed by zerkms and user1578653 makes this code useless and probably dangerous, it should not be used.
Im writing a small cms and checking to see if the user is logged in trough sessions. Every page in my backoffice has a:
require('includes/security.php');
with the following code
<?php
session_start();
session_regenerate_id();
if (!isset($_SESSION["user_logged"]) or !isset($_SESSION["ip"]) )
{
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
}
if ($_SESSION["ip"] != $_SERVER['REMOTE_ADDR'])
{
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
}
if ($_SESSION["user_logged"] != "yes")
{
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
}
?>
If I try to acess any page directly it works as intended and redirects me to index.php except for a single page.
This page simple takes in data from a POST and updates/deletes the images/data in the Database.
The only difference I can think about is that this page doesn't have any html, and its on the same folder as every other.
But when I try to access it directly instead of redirecting me it trows:
Notice: Undefined variable: _SESSION
Warning: session_destroy() [<a href='function.session-destroy'>function.session-destroy</a>]: Trying to destroy uninitialized session
This page starts exactly like this:
<?php
require('includes/security.php');
// Engine - Update and Delete Images
What could be causing this?

Your code is most likely trying to destroy the session multiple times (once in each 'if'). You're also doing the exact same thing in each 'if' - try changing the code in security.php to:
<?php
session_start();
session_regenerate_id();
if(
!isset($_SESSION["user_logged"]) ||
!isset($_SESSION["ip"]) ||
$_SESSION["ip"] != $_SERVER['REMOTE_ADDR'] ||
$_SESSION["user_logged"] != "yes"
) {
session_destroy();
unset($_SESSION['user_logged']);
unset($_SESSION['ip']);
unset ( $_SESSION );
header("location: index.php");
exit();
}
?>

Related

implementing both session, cookie in a login form

i'm implementing session, cookie simple from with a remember me check box . i want to use the cookie so the user could see index.php(protected content) i closed the browser to end the session to check if the cookie working and i got the famous error ..redirected you too many . i searched a bit but still stuck so what should i do? and Is what is the best practice to for doing it?
authentication.php
if(mysqli_num_rows($rows) > 0){
$chck_pass = password_verify($clean_password,$user_arr["password"]);
if($chck_pass){
//log in the user
$_SESSION["id"] =$user_arr["id"];
$_SESSION["fristname"] = $user_arr["fristname"];
$_SESSION["email"] = $user_arr["email"];
$_SESSION["verified"]=$user_arr["verified"];
$_SESSION["message"]="Please verify Your Email to Complete Registration";
//make login-id cookie
if(isset($_POST["remmberme"])){
$user=$user_arr['id'];
setcookie("I_user",$user, time() + 1800);
}
header("location:index.php");
exit();
}else{
$errors["login_error"]="Wrong Password";}
}else{
$errors["login_error"]="Wrong Email";
index.php
<?php
include("Authentication.php");
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
header("location:login.php");
}
?>
login.php
<?php
require_once("config/db_connect.php");
require("Authentication.php");
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
header("location:index.php");}
So you login, close your browser. Then open it up again.
You go to index.php and the following line runs
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
$_SESSION["id"] isn't set, so you redirect to login.php.
On login.php
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
$_COOKIE['I_user'] is set, so you redirect to index.php
Repeat forever.

PHP session not logging out / unset

I know this question has many duplicates, but I tried several of them and none of those have been answered.
Here is my code for logout.php:
<?php
session_start();
require './codefiles/dbhelper.php';
$dbh = new DbHelper();
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\'');
session_unset();
session_abort();
session_destroy();
$_SESSION = array();
unset($_SESSION['username']);
unset($dbh);
header('location:index.php');
?>
But the session variables are just too "stubborn" to be removed. Neither session values are being cleared not the session variables are being removed. Object $dbh is being unset but not $_SESSION['username'];
Another unrelated problem, despite I am setting the LoggedIn = 0, in my SQL query, it just stays as 1 in database. LoggedIn field is of type 'bit'. SessionID field is set to blank though.
Any solutions please?
EDIT:
Removed echo $dbh->error as it was unnecessary.
EDIT 2:
Added session_destroy() as suggested by Hossam Magdy.
<?php
include 'codefiles/dbhelper.php';
if(!isset($_SESSION['id']))
{
header ("Location: login_form.php");
}
else
{
session_destroy();
die('You have been logged out.<meta http-equiv="refresh" content="0;url=login_form.php">');
}
?>
This is basically the "Logout" structure.
I don't know why, but the code for destroying the sessions was somehow not working in logout.php. It worked in index.php and other files, but will all sorts of unpredictable behavior.
Found a workaround to circumvent the problem. The logout.php has code as below:
<?php
session_start();
$_SESSION['logout'] = TRUE;
header('location:index.php');
?>
And add this code to index.php:
# Implement logout functionality
<?php
session_start();
if(isset($_SESSION['logout']) && $_SESSION['logout'] == TRUE){
foreach($_SESSION as $var => $value){
unset($_SESSION[$var]);
}
session_destroy();
session_unset();
}
?>
It may not be a standardized solution, but the code works for me every time, with no unpredictable behavior.
Thanks everyone for sharing their ideas.
Try this
<?php
session_start();
require './codefiles/dbhelper.php';
$dbh = new DbHelper();
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\'');
echo session_status() . '<br />';
session_unset();
session_destroy();
echo session_status();
// header('location:index.php');
Let's see what session_status() says.
But on my projects unset && destroy work.

Session Won't Start

In my login php page, after I check if the user's info is saved in the database, I set a session:
$_SESSION['username'] = $user;
if (isset($_SESSION['username'])) {
header( 'Location: index.php' );
}
and put session_start(); on this page at the tippy top.
Then it redirects me to index.php, telling me that the session has been set. On this page, I put session_start(); at the top but in the login area, I type:
<?php if (!isset($_SESSION['username'])) { echo $_SESSION['username'];?><li class="cat_0" id="login_btn_1">Login / SignUp</li>
<?php }
else {?>
<span id="login_show"><?php echo $_SESSION['username']; ?><a href="/account/logout.php?logout=1" id="logout_btn">LOGOUT</a></span>
<?php }?>
but every time, even if I reload, it shows the result for the !isset(), so that is telling em the session variable is not set. I check in my chrome cookies settings and it shows that PHPSESSID is set each time I test the Login. Can anyone explain why my session is not starting or what the problem is?
This is probably due to a simple race condition between your script and your session handling.
$_SESSION is a superglobal which has a specific way of working.
You are actually trying to access a superglobal variable which still only exists in the buffer of the session handler. If you want to access the session variable, you need to write the buffered data to the session by calling session_write_close() first:
$_SESSION['username'] = $user;
session_write_close(); // remember, you can no longer write to the sessions any more
if (isset($_SESSION['username'])) {
header( 'Location: index.php' );
exit; // just for safety
}
On the login page
-----------------
session_start();
if( !isset( $_SESSION['usename'] ) && isset( $user ) ) $_SESSION['username'] = $user;
if( isset( $_SESSION['username'] ) ) header( 'Location: index.php' );
On the index page
-----------------
if ( isset( $_SESSION['username'] ) ) {
echo '<span id="login_show">
'.$_SESSION['username'].'
LOGOUT
</span>';
} else {
echo "
<a href='/login.php'>
<li class='cat_0' id='login_btn_1'>Login / SignUp</li>
</a>";
}
There was an error in the html - there were two closing a tags together and quite often badly formed html can do all sorts of weird things to the display of the page.

SESSION isset, redirect

This is my code for userslist.php. I put it above the head of this page so if this link is clicked, only admin can enter the page as filtered that is why I have redirections.
session_start();
$loggedInfo['username'] = $_SESSION['username'];
if(
isset($loggedInfo['username']) && $loggedInfo['username']==="admin" &&
trim($loggedInfo['username']) != "guest"
)
{
header('Location: userslist.php');
}
else {
header('Location: ../index.php');
}
This is my php script and I got a problem with redirecting. On the header(location ...) when I changed it to echo true or false, the echo returns the value correctly. But when I put a redirect/location, it does say:
This webpage has a redirect loop
Why is that? :(
Put this code in top of the userlist.php.An try what you got
<?php session_start();
$loggedInfo['username'] = $_SESSION['username'];
if(isset($loggedInfo['username']) && $loggedInfo['username']!="admin"){
header('Location: ../index.php');
exit();
}else if(isset($loggedInfo['username']) && $loggedInfo['username']=="admin"){
?>
You page code here goes
<?php } ?>
You're probably including this code in all pages. Thus on userslist.php it will also redirect to userslist.php. This causes permanent redirects, which is a redirect loop.
This conclusion is however difficult to support without seeing all the code you are using.

php session doesn't work

How it should work:
Index.php is the secured page. It includes check.php, which checks if you have a session = good. If it hasn't, you're not logged in -> log off, remove session. But it doesn't work, it always logs off, like I didn't log in...
index.php
include ‘check.php’;
echo "logged in";
check.php
session_start();
if($_SESSION[‘login’] != ‘good’) {
unset($_SESSION[‘login’]);
unset($_SESSION[‘name’]);
header(‘Location: login.php?logoff’);
exit();
}
Login.php
if(isset($_POST[‘login’])) {
$gb = array();
$gb[‘user1’] = ‘pass1’;
$gb[‘user2’] = ‘pass2’;
if(isset($gb[$_POST[‘username’]]) && $gb[$_POST[‘username’]] == $_POST[‘password’])
{
$_SESSION[‘login’] = ‘good’;
$_SESSION[‘name’] = $_POST[‘name’];
header("Location: index.php");
} else {
header("Location: login.php?wrongpass");
}
} else { ?>
Login Form
<?php } ?>
I hope someone can help me!
You should verify you started the session in login.php.
Put session_start(); in all the pages
You need to have session_start() at the top of all the pages, you havent shown the session start for your login page.
(Thanks to Danny for proving I cant type)
Check that you have register_globals is On in your php.ini
First check on the pages you want to use session variables session is start or not and if session is not stat then start it.
and this is the very first line in the php file.
Code for the session checking is :
if(!session_id())
{
session_start();
}
if($count==1){
session_start();
$_SESSION['Username'] = $UserName;
$_SESSION['Password'] = $password;
UpdateOnlineChecker($Session);
header( "Location: http://". strip_tags( $_SERVER ['HTTP_HOST'] ) ."/newHolo/" );
exit;
}
else {
echo "Wrong Username or Password";
}
Look at my code. It checks if the statement is true (for me, if there is one row with a query statement i execute). Then i start a session and basically Ill define global session variables, sned out a query to my database to update the session and then refer through.
you are missing a session_start(); in your if true block.
Use one for action document such as index.php there is code:
session_start();
if(isset($_POST['login']) && isset($_POST['password'])){
// login
header('Location: (here is some page)');
}
if(!isset($_SESSION['user']){
// #todo some action
} else {
require_once('login.php');
}
if(isset($_GET['logout'])){
unset($_SESSION['user']);
header('Location: (here is some page)');
}
I think problem is header:
('location:------.php);
Your hosting server doesn't run this.
You can use this:
echo "<script>window.location.href='-----.php'</script>";

Categories