PHP session is not functioning on the index page - php

I have got my index page which is redirecting fine without the PHP sessions included. When I I do included it and enter the correct username and password it seems to not be able to pass the username session across with the redirection. Therefore it sees the session as empty and redirecting me back to the index page.
here is my Index page
<?php
session_start();
?>
<!DOCTYPE html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title> RBH-PAS system </title>
<link rel = "stylesheet" type ="text/css" href = "pascss/index.css " >
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#login1").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "login.php",
type: "post",
data: $(this).serialize(),
success: function(d) {
var r = d;
if(r==2){window.location ="patient.php"; }
else if(r==1){window.location="clinician.php";}
else{alert("incorrect user details entered");
window.location="index.php";
}
}
});
});
});
});
</script>
</head>
<body>
<h1><CENTER> WELCOME TO PAS DASHBOARD</CENTER></h1>
<div id="login">
<h2><span class="fontawesome-lock"></span>Sign In</h2>
<form id ="login1" name ="login1" method="post">
<fieldset>
<p><label for="username">Username</p>
<p><input type="text" id ="username" name="username" placeholder="Enter username" required></p>
<p><label for="password">Password</label></p>
<p><input type="password" id="password" name="password" placeholder="Enter password" required></p>
<p><input type="submit" id ="submit" value="Sign In" /></p>
</fieldset>
</body>
</html>
and here is my login page, which I do initiate the session in
<?php
require_once"conn.php";
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
//recieve credentials from the user
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//check the variables recieved are not empty
if($username != '' && $password != ''){
$sql = "SELECT *FROM staff WHERE username ='$username' AND password = '$password' ";//create an sql statement
$result = $conn->query($sql);//run sqlm statement
$row = $result->fetch_assoc(); //fetch row of data
if($result->num_rows == 1 ){//check if user exist as a doctor
if($row["role"]== "clinician"){ //check if user exist as a clinician
$send = 1;
echo $send;}
else if($row["role"]== "doctor"){ //check if user exist as a clinician
$send = 2;
echo $send;}
}else{//if user doesn't exist
$_SESSION["myusername"] = '';
$send = 3;
echo $send;}
}
}
else{$conn=null;}
?>
and here is how I check on the other pages for is user logged in
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: index.php");}
?>

you are never setting $_SESSION['username'] to any value in your login page.

Related

showing wrong password or username even though it is correct password or username

I'm creating login form using AJAX, i,m trying to make it work from 4 days but unable to do so
in this i have few issues i.e., if i enter Valid username & password also then also its not getting logged in to the page, i don know where im going wrong please
can any one find it out where im going wrong, it would be really very help full.
login.php
<?php
session_start();
$mysqli = mysqli_connect("localhost","root","","ajax1");
?>
<!DOCTYPE HTML>
<html>
<head>
<title> login script with ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body style="background-color:#b3ffff">
<div style="padding-left:500px ; padding-top:200px">
Username: <input id="username" type="text" name="username" placeholder="username"><br><br>
Password: <input id="password" type="password" name="password" placeholder="Password"><br><br>
<input id="submit" name="submit" type="button" value="Log In">
<p style="color:black">Havent Registered? Register.</p><br><br>
<div id="display" style="color:red"></div>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var password = $("#username").val();
var password = $("#password").val();
var datastring = 'username=' + username + '&password=' + password;
if(username=='' || password==''){
$("#display").html("Please Enter All The Fields");
}
else{
$.ajax({
type: "POST",
url: "success.php",
data: datastring,
cache: false,
success: function(result){
$("#display").html(result);
window.location = "welcome.php";
}
});
}
return false;
});
});
</script>
</div>
</body>
</html>
success.php
<?php
$mysqli = mysqli_connect("localhost","root","","ajax1");
session_start();
if (isset($_SESSION['id'])){
header('location:welcome.php');
}
$myusername = mysqli_real_escape_string($mysqli,$_POST['username']);
$mypassword = mysqli_real_escape_string($mysqli,$_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$myusername' AND password='$hashed_password'";
$result = mysqli_query($mysqli,$sql);
$row = mysqli_fetch_array($result);
$hashed_password=$row['password'];
if(password_verify($mypassword, $hashed_password)) {
$_SESSION['login_user'] = $myusername;
//$_SESSION['id']=$row['userid'];
echo'Successfully Registered';
exit();
}
else
{
echo'Invalid username or password';
}
?>
welcome.php
<?php
session_start();
if (!isset($_SESSION['id'])) {
header('location:login.php');
}
?>
<!DOCTYPE html>
<html>
<body>
<div style="Padding-left:200px; padding-top:100px">
<?php
$mysqli = mysqli_connect("localhost","root","","ajax1");
$query=mysqli_query($mysqli,"select * from `users` where userid='".$_SESSION['id']."'");
$row=mysqli_fetch_array($query);
echo 'Welcome - '.$row['username'];
?>
<!--br><br>
Logout
<br><br-->
</div>
</body>
</html>
remove AND password='$hashed_password'
from
$sql = "SELECT * FROM users WHERE username = '$myusername' AND password='$hashed_password'";
just check whether the username exists
using
$sql = "SELECT * FROM users WHERE username = '$myusername'";
and then check the password using password_verify()
change your
password_verify(){
echo 'success';
}else{
echo 'error';
}
and in ajax
success:function(data){
if(data.trim() == 'success'){
window.location.href='success.php'
}else if(data.trim()== 'error'){
///use some javascript to display the error message
}
}
In your submit function on your login.php you have set the your variables wrong. Change them to this:
var username = $("#username").val();
var password = $("#password").val();
After you do that, do what v Sugumar suggested in his answer.
You have defined password twice instead of Username.
var password = $("#username").val();
var password = $("#password").val();
Correct this and check your code again.

Website Login Using PHP

So a project in my class is to create a website that incorporates a database. I'm having trouble getting the login function to work. I've written the login and login-script in php. All that happens when I login is the page just refreshes to "localhost/login.php?" instead of "index.php" Any help is appreciated, thanks in advance.
My login.php
<?php
include 'nav.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>UCF Events</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/navstuff.css">
<?php
include 'setUniversityColors.php';
setColors();
?>
<script>
function call() {
//we will POST to this php file on the server
//it will process what we send and can return back JSON information
var request = $.post("login-script.php",
{
//these are defined in the inputs within our form
//each input is defined by their id attribute in the HTML
email: $("#inputEmail").val(),
password: $("#inputPassword").val()
}
//this function is called when we get a response back from the server
function(json){
//write back what we get in the "message" field to the response div defined in this HTML
//the response div is located right below the "Register" button
$("div.response").html(json.message);
//on success redirect to the index page
if(json.success === "success")
self.location="index.php";
}
//defines that we are expecting JSON back from the server
"json");
}
</script>
</head>
<body>
<?php
displayNav('login.php' ,'Login');
?>
<div class="container">
<form class="form-signin">
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" onClick="call();">Sign in</button>
</form>
</div>
</body>
</html>
My login-script.php
<?php
//sets the following variables:
$mysqluser = 'root';
$mysqlpassword = '';
$mysqldbname = 'db';
//now connect to the database
$mysqli = new mysqli("localhost", $mysqluser, $mysqlpassword, $mysqldbname);
//here we can extract information from the client's POST request
// this was submitted by the jQuery function
//always use mysql_real_escape_string when taking in user input
// this prevents SQL injection
$email = $mysqli->real_escape_string($_POST['UserEmail']);
$password = $mysqli->real_escape_string($_POST['Password']);
$success = " ";
$message = " ";
$sql = "SELECT Password, isAdmin, isSuperAdmin, UserID FROM user WHERE UserEmail='$email'";
//run the query and check if it was successful
$result = $mysqli->query( $sql );
if($result){
//get an associative array from the result
//retrieve specific attribute values by $row['tableAttribute']
$row = $result->fetch_assoc();
//check entered password against the hash
if (password_verify($password, $row['Password'])) {
$message = "Login Successful, redirecting...";
$success = "success";
//start the session and set some identifying variables
//these are save across pages
//we will end the session when the user logs out
session_start();
$_SESSION['UserEmail'] = $email;
$_SESSION['isAdmin'] = $row['isAdmin'];
$_SESSION['isSuperAdmin'] = $row['isSuperAdmin'];
$_SESSION['id'] = $row['UserID'];
} else {
$message = "There was a problem with your user name or password.";
$success = "fail";
}
} else {
$message = "Error accessing database: " . $mysqli->error;
$success = "fail";
}
$return = array('message' => $message, 'success' => $success);
echo json_encode($return);
?>
Your code is very weird.
I see that you use jquery, so an example.
$.ajax({
url: "your.php",
method: "POST",
data: { email : $('#email').val(), password: $('#pass').val() }
});
Now, in your php
$_POST['email'];
$_POST['password'];
Now with JSON.
//Prepare your JSON
var myJson = {};
myJson['email'] = $('#email').val();
myJson['password'] = $('#pass').val();
$.ajax({
url: "your.php",
method: "POST",
data: { email : $('#email').val(), password: $('#pass').val() },
dataType: "json"
});
In your PHP
echo "The array ".print_r($_POST['paramet'],1);
$data = json_decode($_POST['paramet']);
echo $data['email'];
echo $data['password'];

check if admin or not php

I have a database table that holds a users username, password and other information as well as whether theyre and administrator or not. Its currently set to Char where A is for admin and U is for normal user.
I have the following code which checks if a user exists:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if(mysqli_num_rows($result) == 1) {
header("Location: home.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
</html>
How would i check if Account_Type is A and if so direct the user to another page instead of the normal home.php page?
EDIT:
It works fine however the admin wont log in.
Ive given it test username of 456 and a password of 456 when i enter them into the two textboxes nothing happens, the screen just refreshes and im back on the login page:
new code below:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
//set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
You are going about this the wrong way. Every page that requires the user to be authenticated should check at the very start if the user is authenticated and at what level. The way to do that is to use the session.
Right now you are setting the session variable before you even check whether the user / password combination is correct so you are effectively logging in anybody who enters a username.
You need to store the variables in the session only upon successful login and as mentioned you need to get a row from your result set to get the user information:
// Personally I would use a prepared statement here
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
// Now you can set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
// Add any additional user information to the session that you might need later on
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
Now in every page where a user is required you can do:
session_start();
if (isset($_SESSION['Username']))
{
// valid user, additional checks for user type?
}
else
{
// not a valid / logged in user
}
Note:
(unsalted...) md5 is unsafe to use for passwords, see Secure hash and salt for PHP passwords;
$row = mysqli_fetch_array($result);
if ($row['Account_Type'] === 'A') {
} elseif ($row['Account_Type'] === 'U') {
} else {
}

Showing form errors on a dropdown form

my title might sound strange so I'll try to explain it better in here.
I have a login form that is hidden when you visit the page. It's located in the upper right corner as a small dropdown form. This is the code without the Jquery since I think it isn't needed for my problem:
<!DOCTYPE html>
<?php
include "core/init.php";
?>
<html>
<head>
<title>Swimstats</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<header>
<div id="border"></div>
<div id="login">
<div id="userName" class="toggleOff">
<?php
if(logged_in() === true){
echo '<p>Welcome ' . $_SESSION['userID'] . '</p>';
} else {
?>
<p>Have an account? <span id="test">Sign in here!</span></p>
<?php } ?>
</div>
<div id="login-content">
<form class="clearfix" action="checkuser.php" method="post">
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
</div>
</header>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
SO a simple dropdown form, but I whenever the user fills in faulty credentials or leaves something empty or whatever I need to show an error under the form or above, doesn't matter. I have the following code to catch the errors:
<?php
include "core/init.php";
if(empty($_POST) === false){
$email = $_POST['email'];
$password = $_POST['password'];
if(empty($email) === true || empty($password) === true){
$errors[] = 'You need to enter your email and password.';
} else if(user_exists($email) === false){
$errors[] = 'Unable to find that email.';
} else {
$login = login($email, $password);
if($login === false){
$errors[] = 'Email/password combination is incorrect!';
} else {
$_SESSION['userID'] = $login;
header('Location: index.php');
exit();
}
}
}
?>
But this method will just bring me to the checkuser.php page and show me the errors there while I have to get the errors show on the form, but I seriously have no clue how to get that.
Ok, found the solution:
Here's my Jquery part:
$(document).ready(function(){
$(".bt_login").click(function(){
email = $("#email").val();
password = $("#password").val();
if(email == '' || password == ''){
$(".errors").html("Please fill in both fields!");
return false;
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: "email=" + email + "&password=" + password,
success: function(html){
if(html == 'true'){
window.location = "index.php";
} else {
$(".errors").html("Wrong username or password!");
}
}
});
return false;
});
});
and my checkuser.php:
<?php
include "core/init.php";
$email = $_POST['email'];
$password = md5($_POST['password']);
$query = "SELECT * FROM user WHERE email = '$email' AND password = '$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
$row=mysql_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['userID']=$row['userID'];
$_SESSION['last_name']=$row['last_name'];
$_SESSION['first_name']=$row['first_name'];
}
else{
echo 'false';
}
?>
Although it may not be the safest solution, it works for now :) Will try to build in more security later.

How to modify the login page to reflect what happened to the authentication?

There are two cases here.
The user enters an empty input. In this case, the login page will warn the user that he has entered an empty input.
The user enters the wrong username or password. In this case, the login page will warn the user that he has entered a wrong username or password.
In both the scenarios, the input processing will be done on the server(PHP). My problem is, how do I modify the login page dynamically to show the warning messages?
I tried passing the PHP boolean value into a javascript variable in login page but after some research, I found out that you cannot mix Javascript and PHP codes. The code is below:
function error_msg()
{
<?php session_start();?>
var failed_login= <?php echo $_SESSION['failed_login'];?>;
var empty_field= <?php echo $_SESSION['empty_field'];?>;
var txt=document.getElementById("failed_login_text");
if (empty_field== 1)
{
txt.innerHTML="No empty fields allowed.";
<?php unset($_SESSION['empty_field']);?>
}
else if (failed_login== 1)
{
txt.innerHTML="Failed login. Wrong username or password.";
<?php unset($_SESSION['failed_login']);?>
}
<?php session_destroy();?>
}
Another method I used is by echoing the whole Javascript into the login.php using PHP. This PHP code is in the login page file.
<?php
session_start();
$failed_login= $_SESSION['failed_login'];
$empty_field= $_SESSION['empty_field'];
echo $_SESSION["empty_field"];
echo $_SESSION["failed_login"];
$script="<script>
var empty_field= $empty_field;
var failed_login= $failed_login;
var txt=document.getElementById(\"failed_login_text\");
txt.innerHTML= empty_field;
if (empty_field== 1)
{
txt.innerHTML=\"No empty fields allowed.\";
}
else if (failed_login== 1)
{
txt.innerHTML=\"Failed login. Wrong username or password.\";
}</script>";
echo $script;
unset($_SESSION['empty_field']);
unset($_SESSION['failed_login']);
?>
What did I do wrong?
I have written this script for dynamic login , you can use it if it serves you , and i have used jquery for validation , Hope this might help you
<?php
if (isset($_POST['user'])){
$email = $_POST['user'];
$password = $_POST['password'];
$sql = "SELECT * FROM `register` WHERE `email` = '{$email}' AND BINARY `password` = '{$password}'";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($result);
$_SESSION['email'] = $row['email'];
$_SESSION['sno'] = $row['sno'];
header("location:some_page.php");
}
else
{
$msg ="Invalid Username / Password";
header('location:your_page_name?msg='.$msg);
}
}
else
{
$msg = "Internal Server error";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>login-user</title>
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/validity.form.js"></script>
<link rel="Stylesheet" type="text/css" href="js/jquery.validity.css" />
<link rel="stylesheet" href="js/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validity(function() {
$("#user").require().match("email");;
$("#password").require();
});
});
</script>
</head>
<body>
<div id="container">
<?php
if(isset($_REQUEST['msg']) && $_REQUEST['msg']!='')
{
echo "<div id='message'>".$_REQUEST['msg']."</div>";
}
?>
<form id="form1" name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<lable>User Name:</lable>
<input name="user" type="text" id="user" size="30" />
<lable>Password:</lable>
<input name="password" type="password" id="password" size="30" value=""/>
<input type="submit" name="Log In" id="Log In" value="Login" />
</form>
</div>
</body>
</html>

Categories