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.
Related
I have an app that requires users to log in in order to use it and I use sessions in PHP in order to accomplish that. The first file index.ui.php includes this piece of code:
if ( isset( $_POST ) ) {
if ( $_POST['sent'] == 'sent' ) {
$msg = fx_login_user( $cn, $_POST['email'], $_POST['password'] );
if ( $msg == $_POST['email'] ) {
session_start();
$_SESSION['ss_user'] = $_POST['email'];
$job = fx_take_job( $cn, $_POST['email'] );
if ( $job == 'Tech' ) {
header("Location: index_tech.php");
exit;
} elseif ( $job == 'Admin' ) {
header("Location: index_admin.php");
exit;
} elseif ( $job == 'Root' ) {
header("Location: index_root.php");
exit;
}
}
}
}
And now, in ìndex_root.php (but also all the remaining index pages) I put a require("session.php") at the beginning in which I manage the access like this:
<?php
session_start();
if ( !isset( $_SESSION['ss_user'] ) ) {
header("Location: index.php");
die();
}
?>
In that same index_root.php I have a form that apart from the data saved in the session variable, gets the value of an entity and tries to save it into $_SESSION
Part of index_root.php
<?php
echo '<form class="form" id="form_info_user_root" method="POST" action="">';
echo '<input type="hidden" name="sent_user" value="user">';
echo '<input type="hidden" name="session" value="'.$_SESSION['ss_user'].'">';
echo '<input type="submit">';
?>
And form_root.php (which I include in index_root.php with another require() just before the one for session.php)
if ( isset( $_POST ) ) {
if ( $_POST['sent_user'] == 'user' ) {
session_start();
$_SESSION['ss_user'] = $_POST['session'];
$_SESSION['entity_info'] = substr( $_SERVER["REQUEST_URI"],
strrpos($_SERVER["REQUEST_URI"], "=" ) + 1 );
header("Location: info_user.php");
}
}
And now, in info_user.php, I also have at the beginning require("session.php") for the session management, but the two variables saved previously (which I both need for some logic in that page) get lost somehow and therefore, I get kicked out to index.php.
I did some logging to know when do I lose the variables (or maybe the session itself), and the ID of the session is the same in every page (as it should be, I guess) so it doesn't get finished, the variables are (as it looks like) properly saved in form_root.php, but they disappear once I enter to 'info_user.php'.
What can I do to maintain those variables or manage the session and its variables in a better way so that I can jump between pages without problems like this one?
Edit 1:
I've change the code a bit. I've now just put session_start() at the beginning of index_root.php and info_user.php and I have deleted that part in session.php and in form_root.php. The code becomes:
form_root.php
<?php
if ( isset( $_POST ) ) {
if ( $_POST['sent_user'] == 'user' ) {
$_SESSION['entidad_info'] = substr( $_SERVER["REQUEST_URI"],
strrpos($_SERVER["REQUEST_URI"], "=" ) + 1 );
header("Location: info_usuarios.php");
}
}
?>
Now I don't send the ss_user session variable via form and save it again, I just include another variable. However, by doing these changes, now in form_root.php I lose the ss_user, so I can't reach info_user.php because I am redirected to index.php. The variables still remain lost when I change between pages.
In the end I've been able to save the variables between form_root.php and info_user.php just by adding exit; after the header() function in the form file.
The code would stay like this:
if ( $_POST['sent_user'] == 'user' ) {
session_start();
$_SESSION['ss_user'] = $_POST['session'];
$_SESSION['entity_info'] = substr( $_SERVER["REQUEST_URI"],
strrpos($_SERVER["REQUEST_URI"], "=" ) + 1 );
header("Location: info_user.php");
exit;
}
This approach solves the specific problem, but I am forced to send the session data via form because I cannot access it from form_root.php's $_SESSION variable, so I've re-written that part of the code I previously had. However, this is just a partial solution, therefore, I am looking for a complete one yet.
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.
I am quite insecure about sessions. I am making a site where a user can login. All my pages, no matter if you are logged in or not, is calling a header.html. So on my index.php, which everybody can see I have the following code:
**index.php**
<?php
if( !isset( $_SESSION['username'])) include('resources/auth/login.php');
else exit( header('Location: home.php') );
if( !isset( $_SESSION ) ) session_start();
if( isset( $_GET['todo'] ) && $_GET['todo'] == 'logout'){
session_unset();
session_destroy();
//echo 'You have been logged out!';
}
?>
<?php include 'resources/includes/header.html';?>
<!-- A lot of code -->
<?php include 'resources/includes/footer.html';?>
The session code comes before my header, and I am redirected to home.php. Should I have that session code in my header instead?
home.php
<?php
if( !isset( $_SESSION ) ) session_start();
?>
<?php include 'resources/includes/header.html';?>
<!-- A lot of code -->
<?php include 'resources/includes/footer.html';?>
So I just thought of earlier today, that I am actually including a session in my body? Because in my header.html I do not have anything with sessions. So should I have the session in my header.html? And in case how can I do that the most smart way?
The session_start() must always be run BEFORE you attempt to access any $_SESSION variables.
So the safest way to code it is to always add it just after your first <?php in the script.
index.php
<?php
session_start();
if( !isset( $_SESSION['username'])) include('resources/auth/login.php');
And
<?php
session_start();
if( !isset( $_SESSION ) )
include 'resources/includes/header.html';
include 'resources/includes/footer.html';
?>
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();
}
?>
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>";