PHP session variable won't change - php

UPDATE : I added all codes;
I want to create a login page for test purpose and I included attempt number with php sessions. The problem is session's variable isn't changing.
index.php
<?php
if (!isset($_SESSION)) {
session_start();
$_SESSION['attempt']=3;
}
if ($_SESSION['attempt']<0){
header('location:login_error.php');
}
require('../function/start.php');
$title = 'Login';
require('../template/header.php');
$ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
var_dump($_SESSION['attempt'])
?>
<h3 class="epad_header">Login</h3>
<div id="epad_wrapper">
<div id="ad_form_wrapper">
<form action="control.php" method="POST">
<fieldset>
<span class="formtext">ID</span>
<input type="text" name="epadName" id="epadName" required>
<span class="formtext">Pass</span>
<input type="password" name="epadPass" id="epadPass" required>
<input type="submit" value="Ok" class="formbuton" name="formbuton">
<br>
<span class="formtext">IP Adress : <?php echo $ip; ?></span>
<br>
<span class="formtext">Attempt : <?php echo $_SESSION['attempt'] ?></span>
</fieldset>
</form>
</div>
</div>
<?php require('../template/footer.php'); ?>
control.php
<?php
if (!isset($_SESSION)) {
session_start();
}
require('../function/start.php');
$title = 'Control';
if (isset($_POST['formbuton'])){
$name = htmlentities($_POST['epadName']);
$pwd = htmlentities($_POST['epadPass']);
}
$check = $db->prepare('SELECT user, pass FROM users');
$check->execute();
$result = $check->fetch(PDO::FETCH_ASSOC);
$user = $result['user'];
$pass = $result['pass'];
if ($name == $user && $pwd == $pass ){
$_SESSION['name']= $name;
header("location:main.php");
}else{
$_SESSION['attempt']--;
header('location:index.php');
}
?>
when a user enter the page(first visit) ; a session will be started, and attempt variable will be created. (index.php)
If they enter false data attempt variable will be decreased. (control.php)
if there are 3 failed attempt page will redirects to login_error.page (index.php)
First Problem : Session variable is not changing.
Second Problem: Even If I enter correct data, the page directs to index.php (login area) instead of main.php

try to place session_start(); at the first line, after <?php

I've solved the problem;
Actually I don't understand why
if(!isset($_SESSION){session_start; $_SESSION['attempt']=3;}
didn't work but when I modified this code to that code
session_start;
if (!isset($_SESSION['attempt']){$_SESSION['attempt']=3;}
Anyway, thank you for reading.

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.

PHP - Session doesnt work on mobile

For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?
My session_start code on index.php
session_start();
if (isset($_SESSION['username'])){
session_id();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if (password_verify($password, $row[0])){$passwordOK = true;}
if($usernameOK == true && $passwordOK == true){
$_SESSION['username'] = $username;
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
Not really sure what your code does, because I dont see anything regarding setting the username or anything of that sort. What your code does is, it starts the session and checks if username variable in session is set, and if YES, it calls session_id.
Can you use this to check if the session is created properly?
session_start();
if (session_status() !== PHP_SESSION_NONE)
{
echo session_id();
}
Starts a session and shows you the session ID if the session_status is not PHP_SESSION_NONE
You don't need to do a session_id() to start a session, session_start() is enough.
I've tested the following on Safari on iPhone 6 (just add the db query part back if you want):
testa.php
<?php
//require('config.php');
session_start();
echo "Session ID: ".session_id()." <br>\n";
$usernameOK = false;
$passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernameOK = true;
$passwordOK = true;
if ($usernameOK == true && $passwordOK == true) {
$_SESSION['username'] = $username;
} else {
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])) {
header("Location: ../");
exit;
} else {
?>
<form class="login-form" method="POST">
<?php if (isset($error_message)) { ?>
<div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
testb.php
<?php
session_start();
echo "Session ID: ".session_id()." <br>\n";
echo "Data stored in session: {$_SESSION['username']}<br>\n";
Clear data/cookies on your mobile browser (or just go into incognito mode). This will make sure you "start from scratch".
Open testa.php on your mobile browser. Take note of the session id shown. Enter your login details and tap Submit. The next page may show blank.
Open testb.php. Again, take note of the session id shown. It should be equal to the session id shown in test1.php. If they are different then it is possible your mobile browser is configured not to accept cookies.
I've personally tested this on Safari on iPhone 6 and I was able to get the username data from session.
PS. A friendly reminder: don't forget to escape the data you use in queries (i.e. $username and $password). Use mysqli_real_escape_string, or use prepared statements. For security.
Maybe you are experiencing some conflict issues:
My session_start code
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if($usernameOK == true && password_verify($password, $row[0])){
if (isset($_SESSION)){
$_SESSION['username'] = $username;
} else{
session_start();
$_SESSION['username'] = $username;
}
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
In the index.php on the first line I have -> REMOVE THAT, PUT FIRST ROUTINE OF SESSION CHECKING
if (!isset($_SESSION)){
session_start();
}
EDIT: I noted that you're using header function to redirect to the index page. It's important avoid such redirects unless you're sending user out of your system, because some environments doesn't work well with them. I suggest to change your routine to user POST/GET http routines instead:
Inside validateSession.php
outside validateSession, NOTHING about sessions rules, concentrate everything there
index.php/head.php/some code that always starting in every page start only that:
<?php
include_once('validateSessions.php');
?>
Your form:
<form class="login-form" action="index.php" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
EDIT: I reviewed your routine, pay attention on validateSessions.php, I was forgetting to load session_start() in every routine that called the file. Put validateSessions inside your include directory.
UPDATE: Even my code helping the OP, the main problem was the SESSION configuration into php.ini file with session.save_path, causing issues about session routines. The php.ini fix solved the problem, the code I expect that helped OP to think about some routines towards Session stuff.
Probably your session is not set. Depending on the PHP version you use, check your session.
For versions of PHP >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
Cookies definitely work on mobile browsers.
I have simplified the code and the session is started when all checks are passed.
<?php
require('config.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($result);
if($usernameTEST == 1){
$row = mysqli_fetch_row($result);
if(password_verify($password, $row[0])) {
session_start();
$_SESSION['username'] = $username;
header("Location: ../");
exit();
}
}
$error_message = "Incorrect login data";
}
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
Simplified the code to make it easier to understand.Ignoring checks for username and password etc. You're basically trying to set a session variable. That happens in login.php. Code for that is.
<?php
$username = "Umesh";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
?>
In index.php you're trying to check the session status. The code is below.
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
print_r($_SESSION);
The above works for me on every browser and device. I even tested chrome on iphone. It seems to work fine. Please check this and see if it works. If not, we will have to check your webserver to see, what the issue is, with session objects on that system.
I verified that print_r ($_SESSION) was same in both cases.
Why you use session_id(). session I am always use this login system. I have no problem Desktop or Mobile session.
PHP code
<?php
session_start();
include 'connect.php';
if(isset($_POST['submit']))
{
$username = htmlspecialchars($_POST["uname"], ENT_QUOTES, "ISO-8859-1");
$username = stripslashes($username);
$password = htmlspecialchars($_POST["pass"], ENT_QUOTES, "ISO-8859-1");
$password = stripslashes($password);
$sql="SELECT * FROM member WHERE username= '$username' AND password='$password' AND status='1' ";
$result=mysql_db_query($dbname,$sql);
$row=mysql_fetch_row($result);
$num=mysql_num_rows($result);
$msg= "<h3 style='padding:0px;margin:0px;font-size:16px;background:#fff;padding:8px;'><font color='red'><center>Incorrect login data</center></font></h3>";
if($num>0)
{
$_SESSION['id'] =$row[0];
$_SESSION['fullName'] =$row[1];
$_SESSION['username'] =$row[2];
$_SESSION['password'] =$row[3];
$_SESSION['email'] =$row[4];
$_SESSION['userType'] =$row[5];
$_SESSION['status'] =$row[6];
header('location:index.php');
}
}
?>
My HTML Form
<form method="post">
<p><?php if (isset($_POST['submit'])) { echo $msg; } ?> </p>
<div>
<input type="text" name="uname" class="form-control" placeholder="Username..." required="" />
</div>
<div>
<input type="password" name="pass" class="form-control" placeholder="Password..." required="" />
<p align="right">Forgot it?</a></p>
</div>
<div>
<button class="btn btn-success submit" type="submit" name="submit"> Login <i class="fa fa-sign-in"></i></button>
</div>
</form>
Remove session_start(); in index.php
and Add this in your config.php
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
Going by your last comment I guess it is due to the query string you are using. Basically using password as a column name sometimes breaks the query as password is also a mysql keyword.
Also, regarding your session you can refer to session_id() vs session_regenerate_id() for further details regarding the functions. Session_id('login') basically sets the session id to login which works on your mobile device as this creates the session with the specific static id. However, you can try using session_regenerate_id(true) to see if it helps.
Also i tried executing the code by putting static value as username as follows
login.php
<?php
$username = "deadlock";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
index.php
<?php
if (isset($_SESSION['username'])){
session_regenerate_id(true);
} else if (!isset($_SESSION)){
session_start();
}
print_r(session_id());
I started using index.php directly using the phone which printed the output as array() with no values.turned out that the Login.php file is not executed.after I explicitly executed Login.php the index.php printed the session array. Can you make sure that the login php file is properly executed.
Regards
Check that session_start() is placed before any browser output. I have found that Chrome on Desktop can be a lot more forgiving then other browsers as well as Mobile Chrome
This problem is generated with Chrome "Lite Mode" to reduce data load throw the Phone. If you use secret navigation so the lite mode is automatically disable an page work correctly. You have to disable "Lite Mode" on Chrome.
This is the final solution.
My problem was on server-side the session.save_path not definied to my server. Thanks a lot to all, who helped me :)

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.

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?

Keeping a PHP variable throughout several HTML pages/stages

I'm getting that the variable $email is undefined. I know that the emailParser() method works as it does everything it's supposed to do.
How to I make it so that the variable $email persists so that I can access it in the second iteration of index.php?
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = $_POST["message"];
include "etext.php";
//Run etext
$email = emailParser($message); //set by running etext
header("Location: index.php?status=submitted");
exit;
}
?>
<h1>Etext Email Converter</h1>
<?php
if (isset($_GET["status"]) AND $_GET["status"] == "submitted") {
$output_file_path = $email->generateParsedEmailFile();
?>
<p> File located at: <?php echo $output_file_path; ?> </p><br>
<a href=<?php echo $output_file_path;?> >Click Here to Access</a>
<?php
} else { ?>
<form method="POST" action="index.php">
<label for"message"></label>
<textArea rows="30" cols="40" name="message" id="message"></textArea>
<input type="submit" value="Submit">
</form>
<?php } ?>
You can use the $_SESSION super-global to achieve this.
$_SESSION['Email'] = 'example#example.com';
That would make that variable accessible on multiple pages provided you support sessions within your code.
To do that, on every page you want to access the session values you would call
session_start();
and after you have called that, you can go ahead and access the variable you set elsewhere.
echo $_SESSION['Email']; // Outputs example#example.com

Categories