PHP session in logging in - php

the below given is my code for a simple login page using session...
since i'm new to php or any such languages i expect any one to correct my code yours faithfully Arunkumar
if(isset($_REQUEST['btnLogin']))
{
$Uname=$_REQUEST['txtUname'];
$pass=$_REQUEST['password'];
$obj-> check_login($Uname,$pass);
$result=$obj-> executec1();
//echo'Query'.$query;
//$result=mysql_query($query);
//$row = mysql_num_rows($result);
//if($row==0)
if($result)
{
// echo "username or password is incorrect";
//}
//else
if(isset($_REQUEST['']))
{
setcookie("username", $Uname);
setcookie("password", $password);
}
else {
setcookie("username", "");
setcookie("password", "");
}
$_SESSION['username'] = $Uname;

session_start();
if(isset($_POST['login_id']))
{
$login='';
$login_id=$_POST['login_id'];//username coming from login form page
$password =$_POST['password'];//password coming from login form page
$query = "SELECT * FROM users WHERE login_id='$login_id' AND password='$password'";
$result = mysql_query($query);
if(mysql_num_rows($result)> 0)//if user user_id and matches then it must show 1 coderun
{
$user_id = mysql_result($result, 0, "user_id");
$screen_name = mysql_result($result, 0, "username");
$_SESSION["session_user_id"] = $user_id;/*like this you can make
different session */
$_SESSION["session_screen_name"] = $screen_name;
header("Location: home.php");
exit();
}
else
{
$errormess = "Invalid Login ID or Password";
}
}

You should first start session with this
session_start();
or better
if(!isset($_SESSION))
{
session_start();
}
if(!isset($_SESSION['username']))
{
$_SESSION['username']=$Uname;
}

Related

PHP Session to restrict access to file

index.php
session_start();
if(isset($_POST['login'])){
$username = mysqli_real_escape_string($con,$_POST['username']);
$pass = mysqli_real_escape_string($con,$_POST['userpass']);
$sel_user = "select * from users where user_name='$username' AND user_password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
else {
echo "<script>alert('Username or Password is not correct, please try again!')</script>";
}
}
display.php
session_start();
if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}
Hello, I'm trying to figure out why my index.php is not letting me properly login and access my display.php The password and username is right, but keeps redirecting me to index.php Any ideas why?
Why don't you use Cookies instead?
In your login.php page instead of:
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
Do this:
if($check_user>0) {
$_SESSION['user_name']=$username;
$Month = 86400 + time();
setcookie('user', $username, $Month);
header("Location:display.php");
}
and then on your display.php
session_start();
if(!isset($_COOKIE['user']))
{
header("location:index.php");
die();
}

How to add a remember me function in login?

session_start();
if(isset($_POST['submit'])) {
$uname = $_POST['uname'];
$pw = $_POST['pw'];
require_once('db.php');
$sql = 'SELECT * FROM users_table
WHERE username="'.mysql_escape_string($uname).'" AND password="'.mysql_escape_string(md5($pw)).'"
LIMIT 0, 1
';
$qry = mysql_query($sql);
$count = mysql_num_rows($qry);
if($count > 0) {
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
header('Location: products_list.php');
} else {
header('Location: index.php?error=1');
}
}
use setcookie() function to set the cookie and then retrieve it when user acess the login restricted pages
setcookie description
I have done it using the Cookie, it runs amazingly perfect...
Only thing you need to do is just add encoding in cookies for security...
session_start();
if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['submit'])) {
$uname = $_POST['uname'];
$pw = $_POST['pw'];
require_once('db.php');
//Checking whether the cookies are set or not
if(!empty($_COOKIES['Last_Login_UserID']) && !empty($_COOKIES['Last_Login_Password'])){
if($_COOKIES['Last_Login_UserID']==$uname && $_COOKIES['Last_Login_Password']==$pw){
//Cookies are perfect give access
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
header('Location: products_list.php');
}else{
//Cookies cookies are wrong
login_check($uname,$pw);
}
}else{
//Cookies are not set so check the database
login_check($uname,$pw);
}
//Function to check the login
function login_check($uname,$pw){
$sql = 'SELECT * FROM users_table WHERE username="'.mysql_escape_string($uname).'" AND password="'.mysql_escape_string(md5($pw)).'" LIMIT 0, 1 ;';
$qry = mysql_query($sql);
$count = mysql_num_rows($qry);
if($count == 1) {
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
if(!empty($_POST['remember_me']) && $_POST['remember_me']==true){
setcookie('Last_Login_UserID',$_SESSION['username'],(60*60*24),"/");
setcookie('Last_Login_Password',$_SESSION['password'],(60*60*24),"/");
}
header('Location: products_list.php');
} else {
header('Location: index.php?error=1');
}
}}

Verifying user login against hash stored in database

I know this one has been asked before but have not been able to find a solution on previous questions.
Secure hash and salt for PHP passwords
Password verifying against database using bcrypt
php password_verify not working with database
I'm attempting to hash the password when registering and then verify it when trying to login. The query is retrieving the password associated with the username however isn't being verified correctly.
The problem is the way I am trying to use password_verify but no matter what I'v tried the past few hours I haven't been able to get it working. If anyone could take a look and try spot what I'm doing wrong it would be a great help.
The DB column length is set to 255 and Varchar to allow the full hash entry.
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_array($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
So I know the hash being returned from the database is being set in the $stored_hash variable correctly as if I hard code the hash returned from it and compare it, login is correct. Could it be something altering the input somewhere?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
Function is_valid_entry($inputData,$validData)
{
$inputData_array = str_split($inputData);
$validData_array = str_split($validData);
$i = 0;
while ($i < sizeof($inputData_array))
{
if (!in_array($inputData_array[$i],$validData_array))
{
return false;
}
$i++;
}
return true;
}
//User defined global variables go here
$username = "";
$ID = "";
$errorMessage = "";
$valid_chars = "abcdefghijklmnopqrstuvwxyz
1234567890";
session_start(); //start a session
if (isset($_POST['submit'])) { //submit button has been clicked
$username = $_POST['username'];
$username = trim($username); //trim any white spaces in the input value
$username = lcfirst($username); //attempts to convert upper case to lower
$username = htmlspecialchars($username); //convert special chars to html rendering null
$username = strip_tags($username); //Strip tags from input string
$ID = $_POST['ID']; //read in the value the user has entered for the password and assign to $ID
$ID = htmlspecialchars($ID);
$ID = strip_tags($ID);
$ID = trim($ID);
if (!is_numeric($ID)) { //if $ID is not numeric redirect to login page
$errorMessage = "Invalid username or password.";
$_SESSION['error'] = $errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php');
} else if (!is_valid_entry($username,$valid_chars)) { //check that user name is a valid char
$errorMessage = "Invalid username or password";
$_SESSION['error'] = errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php'); //redirect the user to the login page
} else { //if user name & $id are both valid
//now check if they are in the database
$mySQL_Server = "127.0.0.1";
$db_userName = "root";
$db_password = "";
$database = "projectdatabase";
//connect to the database on the MySQL server & store the connection in $conn
$conn = mysqli_connect($mySQL_Server, $db_userName, $db_password, $database);
if (mysqli_connect_errno($conn))
{
print("Error connecting to MySQL database: " . mysqli_connect_error($conn));
} else
{
print("Connected to the MySQL database");
}
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_assoc($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "$ID, $stored_hash"; //test to ensure is reaching this statement
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
mysqli_close($conn);
}
}
?>

How to set user/admin accounts for a redirect after log in? PHP

My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.

Login Not Working PHP MySQL

I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...

Categories