Session value are not set in PHP - php

index.php
<?php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "select * from admin where email = '$email' and password = '$password'";
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($result)
{
if ($num_rows > 0)
{
$sqls = "select * from admin where email = '$email' and password = '$password'";
$results = mysqli_query($con,$sqls);
while ($rows = mysqli_fetch_assoc($results))
{
$_SESSION['admin_id'] = $rows['id'];
}
header ("Location: dashboard.php");
}
else
{
echo "<p id='red'>Wrong email or password.</p>";
}
}
}
?>
dashboard.php
<?php
session_start();
include('../config.php');
$admin_id = $_SESSION['admin_id'];
echo $admin_id;
?>
In this code I have create login form and initialize id into session variable when I echo $_SESSION['admin_id'] in index.php it return value but when I want to set $_SESSION['admin_id'] in dashboard.php but its not working or showing no value. How can I fix this issue ?Please help me.
Thank You

Add session_start(); to the top of index.php (inside the php tags of course)
session_start();

Is the session_start() already initialized in the index.php file? You should check that first. It's recommended that you place this in top of all files or a single included file in your script.
session_start();
Test if this fixes your problem.

Before set or get session in php you should always start session at the top of the page like below
session_start();
So in your code try to to start session in index.php

Add session_start() in index.php
<?php
session_start();
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "select * from admin where email = '$email' and password = '$password'";
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($result)
{
if ($num_rows > 0)
{
$sqls = "select * from admin where email = '$email' and password = '$password'";
$results = mysqli_query($con,$sqls);
while ($rows = mysqli_fetch_assoc($results))
{
$_SESSION['admin_id'] = $rows['id'];
}
header ("Location: dashboard.php");
}
else
{
echo "<p id='red'>Wrong email or password.</p>";
}
}
}
?>

Related

Php dynamic login not working

am working with login form but it doesn't work, when am trying to var_dump my sql
<?php
session_start();
include ('database.php');
if (isset($_POST['login'])) {
$user = $_POST['username'];
$pass = sha1($_POST['pass']);
$sql = "SELECT * FROM users WHERE pass = sha1('$pass')
AND username = '$user'";
$query = mysqli_query($conn,$sql);
$results = mysqli_num_rows($query);
//die(var_dump($results));
if ($results == 1) {
$_SESSION['username']=$user;
}
header('location: index.php');
}
?>

Bad use of sessions?

So im having problem with code in php, it drives me crazy..
The thing is, i am making login page, and i have index.php, login.php and dashboard.php.
Login form is in index.php, in login.php it checks if user is in database, and if it is redirect user to dashboard.php, but when i type right user and pass, it redirects me to index.php instead of dashboard.php??
login.php
<?php
session_start();
include($_SERVER['DOCUMENT_ROOT'] . "/new_cms/includes/db.php");
$username = $_POST['username'];
$password = $_POST['password'];
$btn = $_POST['submit'];
if(isset($btn)){
if(empty($username) || empty($password)){
echo "You must fill all fields";
}else{
$sql = "SELECT * FROM admins WHERE username = '$username' AND password = '$password'";
$query = mysqli_query($dbconn, $sql);
$rows = mysqli_num_rows($query);
if($rows > 0){
$_SESSION['usr'] = $rows['password'];
header("Location: dashboard.php");
}else{
echo "Invalid login";
}
}
}
?>
dashboad.php
<?php
session_start();
include($_SERVER["DOCUMENT_ROOT"] . "/new_cms/includes/db.php");
include($_SERVER["DOCUMENT_ROOT"] . "/new_cms/admin/login.php");
if(!isset($_SESSION['usr'])){
header("Location: index.php");
}else{
echo "Welcome";
}
?>
What am i doing wrong?
$rows is just a number, not an array, since you used mysqli_num_rows. Still you try to get $rows['password'].
instead, fetch the first row of the result and use this to assign to the session variable.
if(isset($btn)){
if(empty($username) || empty($password)){
echo "You must fill all fields";
}else{
$sql = "SELECT * FROM admins WHERE username = '$username' AND password = '$password'";
$query = mysqli_query($dbconn, $sql);
$rows = mysqli_num_rows($query);
if($rows > 0){
$user = mysqli_fetch_assoc($query);
$_SESSION['usr'] = $user['password'];
header("Location: dashboard.php");
}else{
echo "Invalid login";
}
}
}

Session Variables are lost after redirecting using header()

I have got index.php file that takes username and password from users, then it redirects to process_login.php that compares these credentials with SQL database to authorize the users. Now if the user is authorized, I want to get all the data about this user and want to use in other PHP files. I am using sessions to do so, but somehow they are not working.
I know they are so many similar questions, but none of them worked.
Here is my process_login.php code
<?php
session_start();
require_once('connectdatabase.php');
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
echo $count = mysqli_num_rows($result);
if($count == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}
else {
header('Location: ../../src/index.php');
}
}
?>
Now I want those variables on welcome.php file.
And this is my welcome.php code
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
It's because you are using $fist_name rather than $first_name. And edit your echo part
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
To
<?php
session_start();
$first_name = $_SESSION['first_name'];
echo $first_name;
?>
I wanted to comment but I can't so here is my suggestion for you.
When something like your issue happens to me I tend to echo the $_SESSION all of them to see if they're actually set or not.
Below is a small PHP script which does the same but I'm using PDO as the DB API.
if (isset($_REQUEST["pWord"])){
$inmPword = md5($_REQUEST["pWord"]);
$loginData = "SELECT * FROM userlogin WHERE pWord = :pWord";
$loginDataQuery = $dbConnect -> prepare($loginData);
$loginDataQuery -> bindParam(':pWord', $inmPword);
$loginDataQuery -> execute();
if ($row = $loginDataQuery -> fetch(PDO::FETCH_ASSOC)){
//Time to set the session
$_SESSION["uId"] = $row["uId"];
$_SESSION["uRole"] = $row["uRole"];
$_SESSION["fName"] = $row["fName"];
$_SESSION["lName"] = $row["lName"];
echo "3";
}else{
echo "4";
}
}
I think it's better not do the row count and echo it. Something like this might help.
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
if($row = mysqli_fetch_assoc($result)) {
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}

PHP Log in page with hashed password issue

So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.
<?php
session_start();
include 'databaseconnection.php';
$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);
$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);
if ($hash == 0) {
header("Location: error.php")
exit();
} else {
$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);
if (!row = mysqli_fetch_assoc($result)); {
echo "your email address or password is incorrect!";
} else {
$_SESSION['id'] = $row['id'];
}
header("Location: profile.php")
If someone could simply suggest what changes I should make, I would really appreciate it.
There you go simple code
<?php
session_start();
include 'databaseconnection.php';
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database
// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
$_SESSION['id'] = $row['id'];
header('Location: profile.php');
}
else
{
header("Location: error.php")
exit();
}
?>
You have not closed the "} else {"... section.
First check request second filter input third use pdo
<?php
session_start();
include 'databaseconnection.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
$pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
$hashed = sha1($pwd);
$sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
$sql->execute(array($email, $pwd));
$row = $sql->fetch();
if($row['email'] !== $email || $row['password'] !== $hashed){
header("Location: error.php");
exit();
} else {
$_SESSION['id'] = $row['id'];
header("Location: profile.php");
}
}else {
echo 'error';
}
?>

Save $_SESSION on JQUERY $.POST

I have an HTML page in which I use Jquery .post() to post the forms into one big php file. I thought that this way I'll be able to save the username in a $_SESSION.
I have a login form that stores the username into a session, but then, when I try to display the php file (using .load()) in a different html page (linked to by the login one) I have no session variable set.
When I did a little debugging I found out the session is lost only if it's created in the if(isset($_POST['username'})) part of the page.
<?php
session_start();
include_once("connect.php");
$username = $_SESSION['username'];
//check if username is in session
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
?>
<div id="part_login">
<?php
//if not, check login
if(isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5($_POST['password']);
$result = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND password='$password' AND active='1' LIMIT 1") or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
echo "<div class='ui-btn'>Invalid Login Credentials</div>";
}
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
$query = mysqli_query($conn, "UPDATE `users` SET lastlogin=now() WHERE username='$username' LIMIT 1");
}else{
}
?>
</div>
<div id="part_user">
<?
echo $username . " " . $oldlogin;
?>
</div>

Categories