I have been working for 2 days on a login and authentication system in PHP. For my logic it should be perfect, but I have problems as usual.
Here is the code:
<?php
ob_start();
session_start();
include "../navbar.php";
require_once '../database-connection.php';
include "../login.html";
if (isset($_SESSION['session_id'])) {
header('Location: ../index.php');
exit;
}
if (isset($_POST['login'])) {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$query = "
SELECT email, password
FROM users
WHERE email = :email
";
$check = $pdo->prepare($query);
$check->bindParam(':email', $email, PDO::PARAM_STR);
$check->execute();
$user = $check->fetch(PDO::FETCH_ASSOC);
if ($email == $user['email']) {
if (password_verify($password, $user['password'])) {
session_regenerate_id();
$_SESSION['session_id'] = session_id();
$sql = "
SELECT username, id FROM users
WHERE email = :email";
$check = $pdo->prepare($sql);
$check->bindParam(':email', $email);
$check->execute();
$user = $check->fetch();
$_SESSION['session_user'] = $user['username'];
$_SESSION['email'] = $email;
$_SESSION['user_id'] = $user['id'];
header('Location: ../index.php');
exit;
} else {
$msg = "Wrong Password";
}
} else {
$msg = "Wrong Email";
}
printf($msg, 'back');
}
The system works, it allows me to authenticate the users registered in the database, but I don't understand why the $msg variable that I use for errors is not printed.
Or better any echo that I put in any part of the listing is not printed.
I can't print anything anywhere. It looks like the program just hangs after the first few includes, yet it lets me authenticate.
(Yes guys I debug by printing the echo to understand up where the scripts work!)
Related
I have one problem in PHP. I have my webpage with login. When I try to login on localhost after writing email and password and hitting login it redirects me to dashboard. But when I upload my page to hosting and I am trying to do that online, it doesn´t redirect me at first, I have to refresh or login one more time to redirects me. How could I fix it? Thanks.
Here is my PHP code:
<?php
session_start();
if (isset($_SESSION['user_name']) && !empty($_SESSION['user_name'])){
header('Location: dashboard/index.php');
}
?>
<?php
if (isset($_POST['login'])){
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
try{
include 'dashboard/includes/db.php';
$query = "SELECT * FROM users WHERE user_email = :user_email AND user_password = AES_ENCRYPT(:password, :key)";
$send_info = $connection->prepare($query);
$send_info->bindParam(':user_email', $user_email);
$send_info->bindParam(':password', $user_password);
$send_info->bindParam(':key', $key);
$send_info->execute();
$send_info->setFetchMode(PDO::FETCH_OBJ);
$result = $send_info->fetchAll();
if(count($result) == 0){
$message = "<h6 class='text-danger mt-2'>Chybný email alebo heslo</h6>";
}
else{
foreach ($result as $item){
$_SESSION['user_id'] = $item->user_id;
$_SESSION['user_email'] = $item->user_email;
$_SESSION['user_name'] = $item->user_name;
$_SESSION['user_lastname'] = $item->user_lastname;
$_SESSION['user_role'] = $item->user_role;
$_SESSION['user_function'] = $item->user_function;
$_SESSION['user_image'] = $item->user_image;
header('Location: dashboard/index.php');
exit;
}
}
}
catch (Exception $e){
echo $e;
}
}
?>
I do not like the ?> (empty space) <?php part. Outputting anything before a header() call will have unintended consequences. Also you miss an exit() after the first header.
so im trying to get my login working which is using php and mysql. i dont no what to replace (mysqli_fetch_array) because before i was using md5 password and changed it to password hash. what i want the code to basically do is when the users correct email and password is inputted the page is redirected to (user-page.php) where the user info will be displayed. im only having problems with the login as the register is working with password hash
<?php
session_start();
require_once "connection.php";
if(isset($_SESSION['username'])!="") {
header("Location: user-page.php");
}
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$email_error = "Please Enter Valid Email ID";
}
$query = "SELECT `password` FROM `users` WHERE `email` = ?";
if(!empty($query)){
if ($row = mysqli_fetch_array($query)) {
$_SESSION['user_id'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SESSION['full_name'] = $row['full_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['gender'] = $row['gender'];
$_SESSION['medical_condition'] = $row['medical_condition'];
header("Location: user-page.php");
}
}else {
}
}
?>
the below code works by checking if the email exits and if the password is correct but only displays if the password is correct or incorrect. is there a way to redirect the user like the code above?
<?php
session_start();
require_once "connection.php";
if(isset($_SESSION['username'])!="") {
header("Location: user-page.php");
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$email_error = "Please Enter Valid Email ID";
}
$query = "SELECT `password` FROM `users` WHERE `email` = ?";
$params = array($_POST['email']);
$results = dataQuery($query, $params);
$hash = $results[0]['password']; // first and only row if username exists;
echo password_verify($_POST['password'], $hash) ? 'password correct' : 'passwword incorrect';
}
?>
register.php
<?php
require('connection.php');
if (isset($_POST['username'])){
$username = $_POST['username'];
$full_name = $_POST['full_name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$medical_condition = $_POST['medical_condition'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// insert values into the database.
$query = 'INSERT INTO `users` (`username`, `full_name`, `gender`,`email`,`medical_condition`, `password`) VALUES (?,?,?,?,?,?)';
$params = array($username, $full_name, $gender, $email, $medical_condition, $password);
$result = dataQuery($query, $params);
$_SESSION['username'] = $username;
$_SESSION['full_name'] = $full_name;
$_SESSION['email'] = $email;
$_SESSION['gender'] = $gender;
$_SESSION['medical_condition'] = $medical_condition;
if($result){
header("Location: user-page.php");
}
}else{
?>
When login in, after you check if password is valid, you need to fill your Session the same way you would after registering.
It differs from the registering, Instead of receiving all the information via the $_POST attribute, you need to get the information from the database and fill the $_SESSION.
So you would need to select more information from the query
$query = "SELECT * FROM `users` WHERE `email` = ?";
$params = array($_POST['email']);
$results = dataQuery($query, $params);
$hash = $results[0]['password']; // first and only row if username exists;
if ( password_verify($_POST['password'], $hash) )
{
$_SESSION['username'] = $results[0]['username'];
$_SESSION['full_name'] = $results[0]['full_name'];
$_SESSION['email'] = $results[0]['email'];
$_SESSION['gender'] = $results[0]['gender'];
$_SESSION['medical_condition'] = $results[0]['medical_condition'];
header("Location: user-page.php");
}
From my understanding of your question, you're trying to do a redirect with header("Location: user-page.php"); after doing password_verify($_POST['password'], $hash) and storing your user information in $_SESSION.
There is a single issue when using header() function as stated in the documentation :
https://www.php.net/manual/en/function.header.php
Note:
Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.
So you have to actually add the Session ID to the url manually for your session to persist to your next page.
It would look like this:
//https://www.php.net/manual/en/session.idpassing.php
//https://www.php.net/manual/en/function.session-id
//
//EDIT:
//307 Temporary Redirect
//Added slash "/" in front of php page. Better browser recognition.
header("Location: /user-page.php?".htmlspecialchars(SID),TRUE, 307);
//Use exit function to terminate program and make sure it does not perform any other tasks.
exit();
so I have this site where drivers can login and register.
at the moment i can store the username in a session variable, im trying to do the same for the user_id so the user can later retrieve it when adding more details for a job.
heres what I got so far:
function selectUser($conn, $username, $password, $userID)
{
$query = "SELECT * FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
//$stmt->bindValue(':user_ID', $userID);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
if (md5($password) == $row->password) {
$_SESSION['username'] = $username;
$_SESSION['user_ID'] = $userID;
// $_SESSION['password'] = $password;
echo "Welcome, you are now logged in as " . $username;
return true;
}
return false;
}
else
{
//echo "Your details were not found";
return false;
}
}
when the driver accesses another page:
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once ("config.inc.php");
try
{
$conn = new PDO(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $exception)
{
echo "Oh no, there was a problem" . $exception->getMessage();
}
if(isset($_SESSION["username"]))
{
echo "Welcome, you are now logged in as <b>".$_SESSION['username']."</b> <img class='clientView' src='images/loginIcon.png' alt='client'>"; }
else {
echo "You are currently not logged in";
}
$login = $_SESSION['user_ID'];
$query = "SELECT * FROM login WHERE user_ID = :login";
$term = $conn->prepare($query);
$term->bindValue(':login', $login);
$term->execute();
$login = $term->fetch(PDO::FETCH_OBJ);
print_r($_SESSION);
?>
tested it using print r and for some reason it doesnt seem to be collecting the user_ID.
am i doing something wrong?
upon test: https://snag.gy/6bGd5m.jpg
when calling the function:
$username=trim($_POST['username']);
$password=$_POST['password'];
$username= htmlspecialchars($username);
$validForm = true;
if (empty($_POST["username"]))
{
$validForm=false;
}
if (empty($_POST["password"]))
{
$validForm=false;
}
if (!$validForm) {
$error = "please ensure all fields are filled in";
include("add.php");
return false;
}
$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
header( 'Location: profile.php');
}else{
$error = "The details you have entered are incorrect";
include("add.php");
}
Debug.
Where do you store the value in the session state?:
$_SESSION['user_ID'] = $userID;
Ok, so where does $userID come from?:
function selectUser($conn, $username, $password, $userID)
{
//...
Ok, so where does the function parameter come from?:
selectUser($conn,$username,$password)
Nowhere. You never supplied a value to be stored in session, so no value was stored in session.
It seems unlikely that you actually want to supply the User ID to the function. Instead, you probably want to supply just the username and password as you currently do and then get the User ID from the database. Which might look more like this:
$_SESSION['user_ID'] = $row["user_ID"];
Or perhaps:
$_SESSION['user_ID'] = $row->user_id;
Or however you get values from your $row object.
But basically the important lesson here is... When a value isn't what you expect it to be, trace back where that value came from. Chances are you have a false assumption somewhere.
My question is, when I try to log in with correct password, it still display the error message "You have entered wrong password, try again!".(Register works fine, the part checking if user already exist works fine) Here is the code:
register.php (works):
<?php
include('db_conn.php'); //db connection
session_start();
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
$_SESSION['email'] = $_POST['email'];
$_SESSION['full_name'] = $_POST['name'];
// Escape all $_POST variables to protect against SQL injections
$full_name = $mysqli->escape_string($_POST['name']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$usertype = $mysqli->escape_string("A");
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'") or die($mysqli->error());
if (isset($_POST["submit"])){
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
// header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
$sql = "INSERT INTO user (Email, Password, UserType, FullName, Hash) "
. "VALUES ('$email','$password', '$usertype','$full_name', '$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"You are registered";
header("location: home.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
// header("location: error.php");
}
}
}
?>
sign_in.php (not working properly):
<?php
include('db_conn.php'); //db connection
session_start();
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'");
if (isset($_POST["submit"])){
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
// header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
echo $_POST['password'].$user['Password'];
if ( password_verify($_POST['password'], $user['Password']) ) {
$_SESSION['email'] = $user['Email'];
$_SESSION['full_name'] = $user['Name'];
$_SESSION['user_type'] = $user['UserType'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: home.php");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
// header("location: error.php");
}
}
}
?>
Don't escape the password hash, it is safe to input directly into the DB:
$mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
to:
password_hash($_POST['password'], PASSWORD_BCRYPT);
Good day, while doing my project, I did stuck on Login page.
This might be really trivial question or maybe even duplicate, but I can't find any solution online.
For some reason, my php script simply skips my login form and keeps making session and redirecting to index.php.
Here is my php script, for checking if email and password exist in databse:
if(isset($_POST['login'])) {
require 'connect.php';
$email = $_POST['email'];
$password = $_POST['password'];
$select_userdata = "select * from users where password ='$password' AND email = '$email'";
$run_check = mysqli_query($dbconfig, $select_userdata);
$check_user = mysqli_num_rows($run_check);
/**Error part**/
if ($check_user == 0) {
echo "<script>alert('Password or email is incorrect')</script>";
echo "<script>window.open('login.php','_self')</script>";
} else {
$_SESSION['email'] = $email;
echo "<script>alert ('You Have Been Logged in')</script>";
header('Location: index.php');
exit;
}
}
if(isset($_GET['logout'])) {
unset($_SESSION['email']);
}
For some reason, script does not care, if I have email and password in database or not. It "pretends" that there is such email address and password, and skips to $_SESSION['email'] = $email;
My question is, what am I doing wrong, and how do I fix it?
Problem is in your logic not your code. $check_user is 0 or more there is no difference for your code. it always reach the $_SESSION['email'] = $email; line.
Try this:
<?php
session_start();
include'functions/dbconfig.php';
if(isset($_POST['login'])) {
require 'functions/connect.php';
$email = $_POST['email'];
$password = md5($_POST['password']);
$select_userdata = "select * from users where password ='$password' AND email = '$email'";
$run_check = mysqli_query($dbconfig, $select_userdata);
$check_user = mysqli_num_rows($run_check);
if ($check_user == 0)
{
echo "<script>alert('Password or email is incorrect')</script>";
echo "<script>window.open('login.php','_self')</script>";
}
else
{
$_SESSION['email'] = $email;
echo "<script>alert ('You Have Been Logged in')</script>";
header('Location: index.php');
exit;
}
}
if(isset($_GET['logout'])) {
unset($_SESSION['email']);
}
?>