Session variable not getting in another inner file PHP - php

I have one login form when user give username and password it leads to login.php file
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
echo "query successfull wrote to DB";
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
echo "unscccessful login";
header('location:index.php');
}
}
When I Try to print the session by print_r($_SESSION) from this file.. it shows the session and its variable with values
Array ( [userNameSession] => full name [loginStatus] => 1 )
In my admin/admin.php (opens when successful login) wrote
session_start();
print_r($_SESSION);exit;
if try to print the session by print_r($_SESSION) it shows empty array as Array()
Please help.

Why do you make an unset($_SESSION)? This may cause the session variable is deleted but the session still exists.
If you want to clean $_SESSION['LoginStatus'] and $_SESSION['userNameSession'], better clean one by one (although this is not necessary because you'll rewrite its value later):
unset($_SESSION['LoginStatus']);
unset($_SESSION['userNameSession']);
The code must be like this:
session_start();
if ( !empty($_POST['username']) && !empty($_POST['password']) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " YOUR QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
if (mysql_num_rows($result) > 0) {
//DELETE prints BEFORE header()!! -> echo "query successfull wrote to DB";
$row = mysql_fetch_assoc($result);
unset($_SESSION['userNameSession']);
unset($_SESSION['loginStatus']);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
//DELETE prints BEFORE header()!! -> echo "unscccessful login";
header('location:index.php');
}
}

One important thing that you must notice:
Don't echo before header. I think your code should be like this:
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
header('location:index.php');
}
}
Hope this helps.

Related

password_verify( ) function returns an empty var

my password_verify function doesn't return anything and yet i think my code is OK,i tried removing the character escapes but still same results,please help
this is my code
<?php
if (isset($_POST['submit'])) {
include_once 'db.php';
$uname = stripcslashes($_POST['username']);
$pass = stripcslashes($_POST['userpassword']);
$uname = mysqli_real_escape_string($conn, $_POST['username']);
$pass = mysqli_real_escape_string($conn, $_POST['userpassword']);
//check if input characters are valid
if (!preg_match("/^[a-zA-Z0-9]*$/",$uname) || !preg_match("/^[a-zA- Z0-9]*$/",$pass)) {
header("Location: ../index.php?signin=invalidwords");
exit();
}else {
//validate username n pwd
$sql = "SELECT * FROM loginAcc WHERE position='$uname'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$hashedpwd = $row['userpassword'];
$pw = password_verify($pass,$hashedpwd);
echo $pass."<br />";
echo $hashedpwd."<br />";
echo $pw;
}
}else{
header("Location: ../login.php");
exit();
}
password_verify() return bool value, and in case your $pw is false, then echo $pw will print nothing.
Try to test 2 cases with correct and incorrect password.

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';
}
?>

Undefined Index error

It occurs undefined index error for the first time while redirecting to the same page after login, how can I solve this problem?
Here's my code:
code on index-page
<?php
session_start();
$error = $_SESSION['error'];
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("db_food", $conn);
$row = mysql_query("select * from tbl_temp order by id DESC", $conn);
$row = mysql_fetch_array($row);
$user = $row['user'];
$pass = $row['pass'];
?>
code for the page After form submission
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if($username =='' || $password == '') {
$error = "Username or Password cant' be empty......";
header("location: index.php");
} else {
$data = mysql_query("select * from tbl_user where username='$username' && password='$password'", $conn);
$num = mysql_num_rows($data);
if($num==1) {
$row = mysql_fetch_array($data);
$_SESSION['name'] = $row['name'];
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
exit;
} else {
$error= "Either Username or Password wrong!!!";
header("location: index.php");
}
}
$_SESSION['error'] = $error;
?>
I want to display the error message in the index page.
check first by isset
$error = "";
if(isset($_SESSION['error'])){
$error = $_SESSION['error'];
}

php admin and user account doesn't work

I have a login form. I have in my table of the database two records: admin and user. If you login if admin you must go to admin_area.php. this is not working, he always log in if user.
If you login if user this works.
The first part of the script is not working and don't run.
Can someone help me?
thanks in advance.
<?php
//first part: this is not working
session_start();
//if (isset($_POST['submit'])) {
$a_username = $_POST ['username'];
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
{
include 'connect.php';
$sqli = "SELECT * FROM users WHERE username='$a_username' AND password='$a_password' ";
$numrows = mysqli_query($link, $sqli) or die(mysqli_error());
$username = 'username';
$password = 'password';
//Add some stripslashes
$username = stripslashes($username);
$password = stripslashes($password);
//Check if username and password is good, if it is it will start session
if ($username == $a_username && $password == $a_password)
{
$_SESSION['username'] = 'true';
$_SESSION['username'] = $username;
//Redirect to admin page
header("Location: admin_area.php");exit();
}
}
//second part: this works
$username = $_POST ['username'];
$password = md5( $_POST ['password']);
if($username&&$password)
{
include 'connect.php';
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' ";
$numrows = mysqli_query($link, $query) or die(mysqli_error());
if ($numrows != 0)
{
/
while ($row = mysqli_fetch_assoc ($numrows))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username==$dbusername&&$password==$dbpassword)
{
echo "you are log in <a href='user.php'>click here for contine</a>, after 4 seconds"; header('Refresh: 4;url=user.php');
$_SESSION ['username'] = $username;
}
else
echo "<h3>incorrect password, <a href='index.php'>click here</a></h3>";
}
else
die ("text");
}
else
die ("text");
//}
?>
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
This condition is not valid, because
$a_password = md5( $_POST ['password'])
is first converted to md5 format and then checked $a_password=="intel"
$a_password is now in md5 format and intel is normal string. For this first try to match normal $a_password like
$a_password = $_POST ['password']
and write your variable into your condition as like
$a_password = md5( $_POST ['password'])

What's wrong with my login script?

Here is my login.php script.
When it runs, it dumps the array (error 2) of what was input, completely skipping everything (i think). I have absolutely no idea what's wrong.
<?php
include('../../content/php/base.php');
// Get data
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
// Encrypt password
include('../../content/php/salt.php');
$pass = crypt($pass,$salt);
// Check database for user / check session
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['user'])) {
header("Location: websiteURL");
} elseif(!empty($user) && !empty($pass)) {
$user = mysqli_real_escape_string($con, $user);
if($result = mysqli_query($con, "SELECT * FROM users WHERE `user`='".$user."' AND `pass`='".$pass."'")) {
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 1) {
$row = mysqli_fetch_array($result);
$email = $row['email'];
$_SESSION['user'] = $user;
$_SESSION['email'] = $email;
$_SESSION['LoggedIn'] = 1;
header("Location: websiteURL");
} else {
echo "Error 1";
die();
}
} else {
echo "<pre>"; // dumps the array onto multiple lines instead of one
print_r($_REQUEST);
echo "</pre>";
echo "Error 2";
die();
}
} else {
echo "Error 3";
die();
}
?>
Here is the full output of the print_r($_REQUEST); :
Array
(
[user] => username
[pass] => password
[PHPSESSID] => 5958246ece69dfdff197ec46e4771aac
)
Error 2
Your query is obviously failing
if($result = mysqli_query($con, "SELECT * FROM users WHERE `user`='".$user."' AND `pass`='".$pass."'") {...}
Is $con a valid connection?
Try putting backticks around the table name users.
You should do some error checking. Take a look at the output of
// You can add this to the Error 2 block (for testing.. not production use)
echo mysqli_error($con);
This will give you an "idea" of what's going wrong, and will help others much in helping you.
Try using session_start(); before any of the includes. This ensures the server session is started

Categories