Session variables get lost when redirecting -PHP - 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?

Related

Sessions variable unseen in multiple pages

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.

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");

i am trying to practice a simple session code in my house in xamp

but some how the page is not showing any error message. also it is not redirecting to the page where i want to redirect it after successful login. i want the login page to be redirected at home page and show the message and when the logout link is clicked the page again come back to the login page
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_post["unametxt"]; ?>" />
<label>Password</label><input type="password" value="<?php echo $_post["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_post["sbt"]))
{
if($_post["unametxt"]== "debarun" && $_post["password"]=="1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_post["unametxt"];
$_SESSION["passwd"]=$_post["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
and it is my home page script:
<?php
session_start();
if(!isset($_SESSION["login"])){
session_destroy();
header('location:login.php');
}
else{
echo "Welcome".$_SESSION["uname"]."<br/>"."your password is".$_SESSION["passwd"];
}
?>
<html>
<body>
<form action="" method="post">
Logout
</form>
</body>
</html>
please
tell me why it is not working??
Add name attribute in your password element. Because of this, it cannot fetch from $_POST array and your condition will always fail.
Try this,
<label>Password</label><input type="password" name="password" value="<?php echo $_post["password"]; ?>" />
First thing $_post must be up letter case like this $_POST then you forgot to specify name="password" to password input field
take a look
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_POST["unametxt"]; ?>" />
<label>Password</label><input type="password" name="password" value="<?php echo $_POST["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_POST["sbt"]))
{
echo $_POST["password"];
if($_POST["unametxt"] == "debarun" and $_POST["password"] == "1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_POST["unametxt"];
$_SESSION["passwd"]=$_POST["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
Put all those validation code at the top. Nothing should be sent to the browser before redirecting. Not even an empty line.
Also, make the L in location capital
header("Location: home.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

JQueryMobile Login Page Redirect on Successful Login

Trying to redirect a user to index.php after they login successfully. I have everything working except the redirect. Been looking around for about an hour now and no luck..I'm sure it is tied to jQueryMobile owning the page
Have tried
header('Location: index.php');
nothing happens.
Also tried
echo '<script type="text/javascript">$.mobile.changePage($(\'index.php\'), {transition : "slide"});</script>';
Both do a re-direct if I make them the first part of my php code, but when placed where I need it they do nothing.
Here is my code:
<?php include "layouts/header.php";
if (isset($_POST['submit'])) { // Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$hashpass = sha1($password);
$found_user = User::authenticate($username, $hashpass);
if ($found_user) {
$session->login($found_user);
$message = "Logged in";
// Redirect to index.php ********
} else {
// username/password combo not found
$message = "Username/password combination incorrect.";
$forgotdisplay = "visible";
}
} else { // Form was not been submitted.
$username = "";
$password = "";
}
?>
</head>
<body>
<div data-role="page" id="loginForm">
<div data-role="header">
<h1>Assessment</h1>
</div>
<div data-role="content" class="centerContent">
<h2>Login</h2>
<p><?php echo output_message($message); ?></p>
<form action="login.php" method="post" data-ajax="false">
<table>
<input type="text" id="username" name="username" maxlength="50" placeholder="username" value="<?php echo htmlentities($username); ?>" />
<input type="password" id="password" name="password" maxlength="30" placeholder="password" value="<?php echo htmlentities($password); ?>" />
<input type="submit" name="submit" value="Login" />
</form>
Sign Up
Forgot Your Password?
<p id="validate-status"></p>
</div>
</div>
</body>
</html>
When valid credentials are submitted the $message does correctly change to "Logged in" so I know that I am getting that far in the script. Have also tried with data-ajax="false" and "true"
Hello you may want to put the full domain in there. I had this problem too
header('location: www.yourdomain.com/index.php');
I believe that should do the trick

Categories