when the user enters their details they click on login but its not working, my connection to the database is fine its this file that is not working, any help would be appreciated, thanks
include '../connection.php'; //used to include connection file that is 1 level higher in the directory
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$fquery = 'SELECT Username FROM login LIMIT 0, 30 ';
$squery = 'SELECT Password FROM login LIMIT 0, 30 ';
$username_query = mysqli_query($dbc, $fquery);
$password_query = mysqli_query($dbc, $squery);
$username_row = mysqli_fetch_array($username_query);
$password_row = mysqli_fetch_array($password_query);
if($username == $username_row && $password == $password_row) {
echo 'username and password correct';
}
?>
<?php
include '../connection.php'; //used to include connection file that is 1 level higher in the directory
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$query = 'SELECT Username FROM login WHERE Username = ? AND Password = ?';
/* set a default value to check against */
$valid_user = '';
/* use prepared statement */
$stmt = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($stmt, $query)) {
/* set question marks equal to values */
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
mysqli_stmt_execute($stmt);
/* get the valid username only if query is successful */
mysqli_stmt_bind_result($stmt, $valid_user);
mysqli_stmt_fetch($stmt);
/* close the statment */
mysqli_stmt_close($stmt);
}
/* check if default was overwritten */
if($valid_user != '') {
echo 'username and password correct';
}
?>
Try this out, should accomplish what you are trying to do.
$username_query = mysqli_query($dbc, $fquery);
$password_query = mysqli_query($dbc, $squery);
$username_row = $username_query->fetch_array(MYSQLI_ASSOC);
$password_row = $password_query->fetch_array(MYSQLI_ASSOC);
if($username == $username_row['username'] && $password == $password_row['Password']) {
echo 'username and password correct';
}
$username = mysqli_real_escape_string($dbc, $_REQUEST['username']);
$password = mysqli_real_escape_string($dbc, $_REQUEST['password']);
$query = "SELECT * FROM login WHERE Username = '$username' AND Password = '$password' LIMIT 1";
if(mysqli_num_rows($query) > 0)
echo 'username and password correct';
Related
im trying to verify the users hashed password with their input but i cant get it working, so far it idenfities if theres a user with that username but it just wont verify the password. here is my code
<?php
$serverName = "localhost"; //Variables to access the user database
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database); //Connect to the database
if(!$conn){ //If the database failed to connect
die("Database failed to connect: " .mysqli_connect_error()); //Display an error message
}
$username = $_POST['username']; //set the username/ password varaibles
$password = $_POST['password'];
$hashPass = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password
$sql = "SELECT * FROM users WHERE username = ?"; //Select all usernames and passwords
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$count = mysqli_num_rows($result); //Count how many results there are
if ($count == 1)
{
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($password, $result )){
$count = 2;
}
}
if($count == 2) //If there is 1 account that matches
{
$stmt->close(); //Close the statment and connection
$conn->close();
session_start();
$_SESSION["LoggedUser"] = $username; //Log the user in
$_SESSION["lastPage"] = "login.php";
header("location: profile.php"); //Direct the user to their profile
}else //if there is no accounts that match
{
array_push($errors, "Username or password is incorrect");
session_start();
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php"; //Make this page the last page
header("location: index.php"); //Go to the homepage
}
?>
any help is appriciated, thanks
You are doing a lot of things you dont need to do.
A SELECT * will return all the columns so you dont need to do another SELECT for just the password.
Also you should not password_hash() the password again, when checking a password against the one already stored on the database. Use password_verify() and that will do all the checking. So you pass it the hashed_password from the database and the plain text password the user just entered on the screen, it will return true or false telling you if the password entered matched the hashed one on the database
<?php
// always do this early in the code
session_start();
$serverName = "localhost";
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database);
if(!$conn){
die("Database failed to connect: " .mysqli_connect_error());
}
// dont hash password again
//$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if(password_verify($_POST['password'], $row['password'] )){
// ----------------^^^^^^^^^^^^^^^^^^--^^^^^^^^^^^^^^^^
// Plain text pwd hashed pwd from db
$_SESSION["LoggedUser"] = $_POST['username'];
$_SESSION["lastPage"] = "login.php";
header("location: profile.php");
// put exit after a redirect as header() does not stop execution
exit;
}
} else {
$errors[] = "Username or password is incorrect";
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php";
header("location: index.php");
exit;
}
?>
How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.
I have created a database with a table (UserPass) which essentially stores Usernames and Passwords.
Now in my form I want to ask a user to input his username and password and while testing this, I realized that I can input any username from the database and any password to login.
Is it possible to select in the SQL query the password that is in the same line as the username?
I tried something like:
$username = $_POST['username'];
$sql = "SELECT Password FROM UserPass WHERE Username = $username";
But the following mysqli_query failed:
$query = mysqli_query($cxn, $sql);
So here is the entire action.php script:
<?php
include "info.php";
include "god.php";
session_start();
if($_POST['god'] == $god)
{
header( "refresh:0;url=../web.html" );
}
else if(empty($_POST['god']))
{
}
else
{
echo "Can't you read: DON'T TRY!!!!!!!";
exit();
}
$cxn = mysqli_connect($host, $user, $password, $dbname) or die("Go");
//check username
$userI = $_POST["username"];
$userSql = "SELECT Username FROM UserPass ";
$result = mysqli_query($cxn, $userSql) or die("Query failed!");
while($line = mysqli_fetch_assoc($result))
{
extract($line);
foreach ($line as $key => $val)
{
if($_POST['username'] == $val)
{
//check for password
$username = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT Password FROM UserPass";
$passres = mysqli_query($cxn, $sql) or die("Request cannot be handled now.");
while ($passline = mysqli_fetch_assoc($passres))
{
extract($passline);
foreach ($passline as $k => $v)
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
}
else
{
session_destroy();
}
}
}
}
}
}
/*
if($userI == $line['Username'])
{
//check for password
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$res = mysqli_query($cxn, $sql) or die("Pass query failed");
$passline = mysqli_fetch_assoc($res);
if($pass == $passline['Password'])
{
header( "refresh:4;url=../web.html");
session_start();
echo "Login succesful, session started, session id: ";
}
}
*/
/*
if($_POST['username'] == $val)
{
//check for password
$b = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$passres = mysqli_query($cxn, $sql);
$passline = mysqli_fetch_row($passres);
foreach ($passline as $k => $v )
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
session_start();
}
}
}
*/
/*
else
{
print("Destroying Laptop...US Government...Destroying Laptop...\n");
exit();
}
*/
?>
You just need to check if there is a record that contains both username and password of the same user:
$password = mysqli_real_escape_string($password);
$username = mysqli_real_escape_string($username);
$sql = "SELECT Password FROM UserPass WHERE Username = '$username' AND Password = '$password'";
if there is 1 such result, it is OK.
BTW, you should not store passwords in plain text - instead use one-way hashing function and compare only the hashes of the passwords.
Your SQL query should contain an 'AND' like this:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM UserPass WHERE username = '{username }' AND password = '{$password}' LIMIT 1";
$query = mysqli_query($link, $sql);
if ($query && mysqli_num_rows($query)>0) {
//user is authenticated
}
?>
By using the logical operator AND your query must match two conditions to give you an answer. That conditions should be known only by the users.
Also please do not store the password field as clear text in database. It's not safe. You should use sha1 hash. For more information about this please take a look here http://en.wikipedia.org/wiki/SHA-1
I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).
i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`
Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?
You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>
I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.
I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks
Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>