I having a difficulty on Log-in procedure. The username & password are both correct based on the database. The name of the fields on the database are also correct. I'm using PDO. When I click the log-in, I'm always redirecting to the else bracket. Please help me,thank you.
<?php
session_start();
include 'config.php';
if ($_POST) {
$user = $_POST['user'];
$pass = md5($_POST['pass']);
$query = "SELECT * FROM useraccounts WHERE USER_NAME=? AND USER_PASSWORD=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$user);
$stmt -> bindParam(2,$pass);
$stmt -> execute();
$num = $stmt->rowCount();
if ($num>0) {
session_start();
$_SESSION['user']=$user;
$_SESSION['active']=true;
header('location:frontpage.php'); //Must be the destination
echo "SUCCESS";
}
else{
header('location:login.php'); // <-- I'm always directing here
echo "FAILED";
}
}
else{
header('location:login.php');
echo "FAILED";
}
If you are getting redirected to the login.php page, please keep in mind the following:
1) Unless you access that page with a POST request, you will always get the login.page. You have an if statement that looks like this:
if ($_POST) {
So if you access the page directly from the browser, you are redirected straight to the login.php page.
2) If you are getting redirected from the second else statement like you stated with your comment "<-- I'm always directing here" then your query is not returning any result. Your query looks fine. So check the credentials you are passing. Make sure it matches that of the database.
Is your html form using POST or GET in the method attribute. it should be using POST otherwise your database checking code will not be run
Related
I made a signin form that will look through the database and find a match to the user's credentials, but how do I fix this code so it will relocate the page if there is no match.
<?php
session_start();
include_once 'includes/dbh.php';
$username = $_POST['u_name'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM users;";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row['username'] && $password == $row['password']) {
$_SESSION['username'] = $username;
header("Location: second_index.php?signinSuccessful");
}
if ($username != $row['username'] && $password != $row['password']) {
header("Location: index.php?NotSucessful");
}
}
I tried putting the code inside of the loop, but I know that can't work, and if I put it outside of the loop, It redirects even if the credentials are correct. Please help. Thanks
First of all, this is totally wrong, you're looping trough all the users to see if the user exist, instead of that sql statement try $sql = "SELECT * FROM users where user='$user' and password='$password'";
And to avoid any data breach in that sql statemen you have to serialize the user and pass like that before adding it to the statement
$user = mysql_real_escape_string($conn, $user);
$password =mysql_real_escape_string($conn, $password);
Then you only check if the fields aren't empty (which means the user exist)
You are getting all the users from the users table and checking each record manually in php.
The reason why your code doesn't work is because the while loop doesn't check all the users in user table. If the first record in the retrieved table data doesn't match with entered username and password, it will go to 2nd if block and redirect.
You should change your query to filter by user-entered values.
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD='password'
And later check in php if any record is returned. If any record is returned, it is a valid user, else redirect the user to failed authentication page.
As a good practice, make sure to use parameterized query.
Update Replace the while loop and block with this.
if(mysqli_num_rows($result) > 0){
// valid user
}else{
// invalid user
}
Why do you need while loop in this case when you fetching data from database? Using sql and make the database fetch the only one correct answer, don't make server site do unnecessary work.
I propose just do simple fetch then if check, no need for while loop at all.
Your logic is always redirect to index.php when username password not correct so of course it will always do so when your while loop on server do not hit the correct user.
I am making an html login page which will submit a form to a php page to check to see if user details lie in an established username access database.
If the username and password correspond to a row in the database, the php redirects to an mainpage (mainpage.html), otherwise it redirects back to the login page (LOGINPAGE.html).
The if function I have used to achieve this in my php script is as follows:
if(odbc_fetch_row($DetailCheckExec)) //If username corresponds with password
header('Location: mainpage.html');
else
header('Location: LOGINPAGE.html');
The problem is, the php doesn't seem to redirect. Even if I simplify my code to simply redirect, nothing changes. i.e.
<?php
header("Location: LOGINPAGE.html");
exit;
?>
won't work either.
Any help is appreciated thank you.
well i dont know the function "(odbc_fetch_row($DetailCheckExec)" but there's a step by step login that I made i hope it works
if ((isset($_POST['user'])) and (isset($_POST['password'])))
{//checks if the inputs in the form are empty
//sets two variables with the value of the imputs
$usuario = $_POST['user'];
$clave = $_POST['password'];
//then selects the row where the values are equal in the database
$consulta = "SELECT usuario, contrasena FROM `usuarios`
WHERE usuario = '$usuario' and contrasena = '$clave'";
$resultados=mysqli_query($con,$consulta);
while(($fila=mysqli_fetch_array($resultados))){
$vpeso = $fila['peso'];
$vestatura = $fila['estatura'];
$vusuario = $fila['usuario'];
}
if(($resultados) AND ((isset($vusuario)) and ($vusuario <> '') )){
//starts session
session_start();
//stablishes the user in the session
$_SESSION['usuario'] = $usuario;
//if the user doesn't exist it will bring to signup.php for example
}else{
header("Location: signup.php");
}
}
well I hope it works, sorry for not changing the variable names haha
We have a system where the user logs in to an admin page to make edits however when they are logging in they can log in with any password as long as the username is correct. The following code is in php tags
include 'database_conn.php';
$sql = "SELECT passwordHash FROM nmc_users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt); // execute the query
mysqli_stmt_bind_result($stmt, $passWDHash);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($passWD, $passWDHash)) {
echo "<p>Password correct!</p><a href='logout.php'>Click here to log off</a></p>\n";
} else {
echo "<p>Sorry we don't seem to have that username.</p>";
session_destroy();
}
if (isset($_SESSION['[url']))
$url = $_SESSION['url'];
else
$url = 'index.php';
header("location $url");
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
Would anyone know how to make it so it only logs users in with the correct username and password that.
The password is in our database as well as the usernames. If any more code is needed then please say and I will reply with the relevant pieces.
From the docs:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie.
If $_SESSION['url'] is set, and the password is wrong, session_destroy() won't unset it. So you're still falling into the success part of the if statement.
Edit: Also, you should be checking authentication on the actual page that requires it. Here, it looks like you're checking on one page and then conditionally redirecting to another. If I type the other page's URL directly into my address bar, will I get that page without an auth check?
Piggybacking on #AlexHowansky answer, you need to do a few things here:
First you need to be sure you're using session_start() at the beginning of the script to make sure the session is set up correctly.
Second, you need to unset the $_SESSION variables to make sure that once the session is destroyed, you can't accss these variables on the current page (they'll be unset on the next page, so you don't have to worry about that).
Third, you'll need to close the mysql connections before redirecting for them to do any good.
Fourth, there was a typo with this: if (isset($_SESSION['[url']))
Your header() redirect also won't work because you're echoing out text before it, which will cause it to fail, but I'll let you fix that.
I'm also not seeing where $passWD is coming from, but I'm assuming you have it in there somewhere.
Updated code:
include 'database_conn.php';
session_start();
$sql = "SELECT passwordHash FROM nmc_users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt); // execute the query
mysqli_stmt_bind_result($stmt, $passWDHash);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($passWD, $passWDHash)) {
echo "<p>Password correct!</p><a href='logout.php'>Click here to log off</a></p>\n";
} else {
echo "<p>Sorry we don't seem to have that username.</p>";
session_destroy();
$_SESSION = array();
}
if (isset($_SESSION['url']))
$url = $_SESSION['url'];
else
$url = 'index.php';
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("location $url");
}
?>
I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)
My Profile php
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
This is my php for viewing user profile.
http://mywebsite.com/profile.php?userID=5 its working fine in this way.
i want my code to check if user is available in database for example if i add ?userID=10 which is not present in database it gives out mysql error or even if i use http://mywebsite.com/profile.phpthen also it give error.
so now i want if user is not available in database it should give that user is not available and when we use simple http://mywebsite.com/profile.php it should give auto add it to userID=1 OR REDIRECT it to home.php
If there is other way of doing this please let me know. well im very newbie in this field
Thanks for looking my question and answering :)
Solved
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
$UserID = $_GET['userID'];
$CheckQuery = mysql_query("SELECT * FROM users WHERE id='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: index.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
You shouldn't use MySQL As it's depreciated,
If you really wish to use MySQL You could check at the start of the script if there is a row count for the User ID, Example:
<?
$UserID = $_GET['UserID'];
$UserID = mysql_real_escape_string($UserID);
$CheckQuery = mysql_query("SELECT * FROM users WHERE userID='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
// Do something If user is Not Found
// Redirect to Another Page OR Something
}
?>
than check that query give with result if it wont found data in database than redirect
$result = mysql_query(...);
if(mysql_num_rows($result) !=1){ //
header("Location:signup.php");
exit();
}
You shouldn't use MySQL As it's depreciated, either use PDO or mysqli