Sessions variable unseen in multiple pages - php

I don't understand the thing with sessions in php. It says that after you start a session, the session variable are stored and can be seen in multiple pages.But in my pages that are not seen. For example I have my index.php page where I start the session_start(). Then I click a button to login and if everything is ok it should redirect me to profile.php page where I print the session email. But it doesn't recognize my session variable.My code:
if($_POST['actiune'] == 'login'){
$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
if ($verify) {
header("Location: index.php?page=profile");
}
else {
header("Location: index.php?page=login&msg=PleaseRegister");
}
}
profile.php
echo $_SESSION['username'] ; die();
Any help?
UPDATE:
profile.php
<?php
session_start();
echo $_SESSION['username'] ;
?>
<div id="profile">
<p id="welcome">Welcome :<?php echo $_SESSION['username']; ?></p>
<?php
if ($_SESSION['avatar'] == ""){
?>
<img src = "http://placehold.it/400x200/0000ff/&text=Upload a picture" alt =""/>
<?php
}
else if ($_SESSION['avatar'] != ""){
?>
<img src="avatars/<?php echo $user['file'];?>">
<?php
}
?>
<p id="modifyPf"> Modify</p>
<p id="reset"> Reset password</p>
<p id="articlePf"> Article page</p>
<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="actiune" value="avatar">
<input type="hidden" name="id" value="<?php echo $user['id'];?>">
<p><label for="avatar">Upload an avatar:</label></p>
<p><input type="file" name="avatar" id="fileToUpload"></p>
<p><input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/></p>
</form>

You need to call session_start(); in profile.php also.
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.
Update
<?php
if(!isset($_SESSION))
{
session_start();
}
if (isset($_SESSION['username'])){
?>
<div id="profile">
<p id="welcome">Welcome :<?php echo $_SESSION['username']; ?></p>
<?php if ($_SESSION['avatar'] == ""){ ?>
<img src = "http://placehold.it/400x200/0000ff/&text=Upload a picture" alt =""/>
<?php
}
else if ($_SESSION['avatar'] != ""){
?>
<img src="avatars/<?php echo $user['file'];?>">
<?php
}
?>
<p id="modifyPf"> Modify</p>
<p id="reset"> Reset password</p>
<p id="articlePf"> Article page</p>
<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="actiune" value="avatar">
<input type="hidden" name="id" value="<?php echo $user['id'];?>">
<p><label for="avatar">Upload an avatar:</label></p>
<p><input type="file" name="avatar" id="fileToUpload"></p>
<p><input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/></p>
</form>
</div>
<?php
}
else {
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
}
?>
Index.php
<?php
session_start();
if($_POST['actiune'] == 'login'){
$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
if ($verify) {
header("Location: index.php?page=profile");
}
else {
header("Location: index.php?page=login&msg=PleaseRegister");
}
}
else {
echo 'POST actiune is not login';
}
?>

You need session_start() at the top of every page request - exactly one time per request. It doesn't just create the session; it's required for every request in which you want to use the session. From the docs:
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.

Related

Session id is set even after logout

I'm trying to use session to keep the access to my website only to the authorized users.
Now, This is my main page:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require 'dbConfigBDO.php';
require 'message.php';
require 'SafeRedirect.php';
if (isset($_POST['username']) AND isset($_POST['pass']))
{
$_SESSION['message'] = '';
$username = $_POST['username'];
$password = $_POST['pass'];
$response= $conn->prepare('SELECT username,pass
FROM AdminTable
WHERE username = :nom
');
$response->bindValue(':nom',$username,PDO::PARAM_STR);
$response->execute();
$member = $response->Fetch();
$response->CloseCursor();
if(!$member) exit('اسم المستخدم غير صحيح');
if($password !== $member['pass']) exit('كلمة المرور غير صحيحه');
$_SESSION['id'] = $member['username'];
$_SESSION['message'] = htmlspecialchars($user). ' تم تسجيل دخولك بنجاح ';
safe_redirect('index.php');
exit;
}
?>
<!-- Log in:
First read name and password:-->
<form action="" method="post" id="form">
<fieldset class="form-item">
<legend>الدّخول</legend>
<label for="email">الاسم</label><input type="text" name="username" id="username"><br>
<label for="pass">كلمة المرور</label><input type="password" name="pass" id="pass">
</fieldset>
<fieldset class="form-submit">
<input type="submit" value="موافق">
</fieldset>
</form>
</body>
</html>
the problem here is when I redirect the user to index.php which checks as follows:
<?php
session_start();
require 'message.php';
require 'SafeRedirect.php';
$_SESSION['message'] = '';
$session_id = (isset($_SESSION['id'])) ? $_SESSION['id'] : null;
if($session_id == null)
{
$_SESSION['message'] = htmlspecialchars($user). ' Please sign in first... ';
safe_redirect('login.php');
exit;
}
?>
<a href="logout.php">
click here to log out</a>
Now when I press logout I shouldn't be able to access page index.php right?
the problem is I still can!
I tried to print the session ID and it does not change even after logout. I used
<?php
require 'SafeRedirect.php';
session_start();
unset($_SESSION["id"]);
session_regenerate_id(true);
session_destroy();
safe_redirect('login.php');
?>
my code use to work long time ago on another website but not now and I'm really confused what I did change since then.

Header function is redirecting to index.php instead of the specified file (PHP)

I am currently organising my files into appropriate folders and a problem has arisen. Before changing the code to organise the files everything worked. Now whenever I try to log in, instead of redirecting to 'Staff/staff.php', it redirects to 'Staff/index.php'.
The code is as follow:
<?php
session_start();
include("connectdb.php");
//if the form has been submitted
if (isset($_POST['submitted'])){
//get the information out of get or post depending on your form
$username = $_POST['username'];
$password = $_POST['password'];
global $db;
//sanitise the inputs!
$safe_username = $db->quote($username);
//run a query to get the user associated with that username
$query = "select * from user where username = $safe_username";
$result = $db->query($query);
$firstrow = $result->fetch(); //get the first row
if (!empty($firstrow)) {
//check the passwords, if correct add the session info and redirect
$hashed_password = md5($password);
if ($firstrow['password'] == $hashed_password){
$_SESSION['id'] = $firstrow['userID'];
$_SESSION['username'] = $firstrow['username'];
$_SESSION['fname'] = $firstrow['first_name'];
$_SESSION['lname'] = $firstrow['last_name'];
$_SESSION['staff'] = $firstrow['staff'];
if($firstrow['staff'] == 1) {
header("Location:Staff/staff.php");
exit();
} else {
//echo "Success!";
header("Location:Customer/customer.php");
exit();
}
} else {
echo "<h1>Error logging in, password does not match</h1>";
}
} else {
//else display an error
echo "<h1>Error logging in, Username not found</h1>";
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="CSS/theme.css">
</head>
<body>
<h1 class="register-title">Aston Animal Sanctuary</h1>
<div class="register">
<!--<form method="link" action="staff.php">
<input type="submit" value="Staff Login">
</form>-->
<form action="index.php" method="post">
<input type="text" class="register-input" name="username" placeholder="Username">
<input type="password" class="register-input" name="password" placeholder="Password">
<input type="submit" value="Login" class="register-button">
<input type="hidden" name="submitted" value="TRUE" />
</form>
<form method="link" action="register.php">
<input class="register-button" type="submit" name="register" value="Register">
</form>
<div>
<!--Test-->
</body>
</html>
<?php include('View/footer.html'); ?>
Is the header the problem?
EDIT
The same thing happens with my logout file. It redirects to 'Staff/logout.php' instead of '../logout.php'. It worked before I started organising the files.
The code for logout.php:
<?php
session_start(); //get the previous session info
session_destroy(); //destroy it
header("Location: ../index.php"); //redirect back to the start
?>
Have you tried:
header("Location: ./staff/staff.php");
and:
header("Location: ./customer/customer.php");

PHP Session always working

I've got an if statement to check if a variable within the $_SESSION is active and set, and if it is then a message is returned to the user. Here's my header.php:
<?php
$conn = HIDDEN;
session_start();
$username = '';
$_SESSION['username'] = $username;
?>
<header>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="style/main.css">
<title>webshop</title>
</header>
<div id="LogIn">
<?php
if (isset($_SESSION['username']))
{
echo "its working";
} else {
?><form class="form1" method="post" action="" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>
<input class="submit .transparentButton" value="Next" type="submit" name="Submit"/>
</ul>
<br/>
</fieldset>
</form>
<?php } ?>
</div>
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
}
?>
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
// Use the following code to print out the variables.
echo 'Session: '.$_SESSION['username'];
echo '<br>';
echo 'POST: '.$_POST['username'];
}
?>
The first time running, or before the user logs out (to be implemented later), the site should prompt for a username to be entered and then upon refreshing the page the welcome message should be display.
As of right now the code simply returns "it's working" despite no variable in $username existing. The code:
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
// Use the following code to print out the variables.
echo 'Session: '.$_SESSION['username'];
echo '<br>';
echo 'POST: '.$_POST['username'];
}
?>
should print out the variable underneath the welcome message, or nothing at all if it's empty. As of right now, the welcome message "it's working" is displayed always but no variables are in $username. Can anyone tell me why?
Thanks in advance.
$_SESSION['username'] is SET/NULL but is EMPTY you should try !empty() instead if isset(). See below.
<?php
if (!empty($_SESSION['username']))
{
echo "its working";
} else {
?><form class="form1" method="post" action="" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>
<input class="submit .transparentButton" value="Next" type="submit" name="Submit"/>
</ul>
<br/>
</fieldset>
</form>
<?php } ?>
EDIT 2
As to the comment.
IF statement needed to tell if there was a submit if there was don't display the form else display the form. See below Code
<?php
$conn = ""; //HIDDEN kept throwing error whilst I was testing
session_start();
$username = '';
$_SESSION['username'] = $username;
?>
<header>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="style/main.css">
<title>webshop</title>
</header>
<div id="LogIn">
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['username'] = $_POST['username'];
// Use the following code to print out the variables.
echo 'Session: '.$_SESSION['username'];
echo '<br>';
echo 'POST: '.$_POST['username'];
} else {
if (!empty($_SESSION['username']))
{
echo "its working";
} else {
?><form class="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>
<input class="submit transparentButton" value="Next" type="submit" name="Submit"/> //removed css selector .
</ul>
<br/>
</fieldset>
</form>
<?php } } ?>
</div>
The isset() checks only whether the variable is set or not and it returns true since it is initialized to null string. Here you have to use !empty().
if (isset($_SESSION['username']) && !empty($_SESSION['username'])) {
}
Just a quick solution is to change
if (isset($_SESSION['username']))
to
if (strlen($_SESSION['username']) > 0)
That will work. Im guessing it because technically u did set username so it isset but if u check the length u know its not empty

Session variables get lost when redirecting -PHP

I am new using PHP and I am trying to build a content management site.
I started developing the login pages and at the start the SESSION variables were kept as normal and were working without any issues when using redirect to another page after login was confirmed.
But 2 days ago i tried to develop the forgot password functionality as well and since then and by only changing the output buffering which i just enabled I have an issue.
The SESSION variables are not carried over to the redirected page and thus the login doesn't work.
My code is below:
<?php include("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php
$username = "";
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {
// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login($username, $password);
//print_r($found_admin);
if ($found_admin) {
// Success
// Mark user as logged in
$_SESSION["admin_id"] = $found_admin["usr_serno"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
} else {
// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
}else if(isset($_POST['forgot'])) {
redirect_to("forgotPassword.php");
}
?>
<?php $layout_context = "admin"; ?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Login</h2>
<form action="login.php" method="post">
<p>Username:
<input type="text" name="username" value="<?php echo htmlentities($username); ?>" />
</p>
<p>Password:
<input type="password" name="password" value="" />
</p>
<input type="submit" name="submit" value="Submit" />
<input type="submit" name="forgot" value="Forgot Password" />
</form>
</div>
</div>
<?php include("../includes/layouts/footer.php"); ?>
the session.php starts the session
and the admin.php will just check if the SESSION[admin_id] isset then it will show the page or else it will redirect again to login.php page, which is what happens.
Any advise or help please?

Session Handling in PHP 5

i've a problem with php session handling that i can't explain to myself.
I'm studying php from scratch, and i can't figure out how to mantain a session live:
This is my index page, where a user can login or register to the database visiting the right page, and then come back to see if he's logged in:
Code:
Index
<?php session_start(); ?>
Register
Login
<?php
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin'];
?>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
else
{
echo "Please Register or Login";
}
?>
In fact this work, because when i come back from login.php it says, "Logged as: Admin"
But when i click on the link to get the login page, or register page again from the index page, i should get the same message, "Logged as...", but the session appear to be closed instead. :(
here's login.php:
<?php
session_start();
include "dbConnect.php";
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin']; // IT NEVER SHOW THIS MESSAGE
}
if(isset($_POST['submit']) &&(trim($_POST['submit']) == "Login"))
{
if(!isset($_POST['user']) || $_POST['user']=="")
{
echo "Attenzione inserire l'username.";
}
elseif(!isset($_POST['pwd'])||$_POST['pwd']=="")
{
echo "Attenzione inserire la password.";
}
else
{
$u = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));
$u = str_replace(" ","_",$u);
$p = trim(filter_var($_POST['pwd'], FILTER_SANITIZE_STRING));
$p = sha1($p);
$istance = new dbHandle;
$istance->connect();
$data = $istance->query("SELECT * FROM login WHERE username_login = '$u' AND password_login = '$p'");
if(mysql_num_rows($data) == 0)
{
echo "Failed";
echo "<a href='index.php' target='_self'> Go Back </a>";
}
else
{
echo "Logged";
$res = $istance->getdata($data);
$_SESSION['login'] = $res->id_login;
$_SESSION['nlogin'] = $res->username_login;
echo "<a href='index.php' target='_self'> Go Back </a>";
}
}
}
else
{
?>
Login
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...
<input name="user" type="text" size="20" required="required"/>
...
<input name="pwd" type="password" size="20" required="required"/>
...
<input type="submit" name="submit" value="Login"/>
</form>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
$istance->disconnect();
?>
When i come back using the link above "Go Back" to the index page, it shows Logged as...
but when i come back here again, it does not.
So i assume my session were destroyed automatically? but why?
Thanks, i appreciate your help.
I forget to say that PHP.ini has
session.cookie_lifetime
set to "0"
Thanks
You are calling unset($_SESSION['login']) many times. It removes your login:
<form method="post" action="<?php unset($_SESSION['login']) ?>">
Try this:
<form method="post" action="index.php">
<input type="button" name="logOut" value="LogOut" />
</form>
<? if (isset($_REQUEST['logOut'])){ session_destroy(); } ?>
unset the session like below
if(isset($_REQUEST['logOut']))
{
unset($_SESSION['login']);
}
You check for if(isset($_SESSION['login'])).
If that results in true, you do <form method="post" action="<?php unset($_SESSION['login']) ?>">
Note the unset($_SESSION['login']) part - after that, if(isset($_SESSION['login'])) will return false.
Session overview :
<?php
// Always Start our session
session_start();
$_SESSION['username'] = 'Saurabh Singh';
$username = $_SESSION['username'];
echo $username;
if(isset($_SESSION['username']))
{
Do your action
}
else
{
echo "Please Register or Login";
}
I don't think the session has been destroyed!
I would start by first removing all the empty lines between the opening tags for php and the
session_start().
Test it again and you could add the line
error_reporting(E_ALL);
below the session_start to see if any error messages are echo(ed) back to you.
In your PHP.ini what
session.cookie_lifetime = 0
means is that the session remain active so long as the browser stays open. It's only destroyed when the browser is closed.
I hope this helps

Categories