I want to write a mysql php code
if I put the ID and passwd it will check with database
and link to the login success or login fail.
but my code it failed to go to the login success even though id and passwd is correct
$mysqli = new mysqli('localhost', 'root', '', 'project');
$username = $_POST['username'];
$password = $_POST['password'];
//to check whether the username exists or not
$stmt = $mysqli->stmt_init();
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
$stmt->bind_param('ss', $username, MD5($password));
$stmt->bind_result($result,$result2);
$stmt->execute();
Im not sure my prepare statement and the bind_param is in the right position.
it should compare the MD5(password) (encrypted) password with input password
**
if ($stmt->fetch())
{
session_start();
$_SESSION['pid'] = $username;//login id
header('Location: Login Successfully.php');
exit();
}else{
$_SESSION['pid'] = $username;
header('Location: Failed to login.php');
}
**
and this is my fetch. but it always go to the failed to login.php
this is my login.php before execute above code. it get the input id and passwd and pass it to the fetch code.
Login:
Enter your username and password below:
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
When using prepare(), you need to use placeholders ? instead of the actual variables. Also it looks like passwd should be password. So you will want to change
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
to
$stmt->prepare("select pid, password from person where pid = ? and password = ?");
Related
I have successfully created registration form with hashed password as shown below. I am not able to log In using the username and hashed password that I have stored in my SQLite db.
I can log in if the password is store as plain text, but I want the password to be hashed. Please help me how can I read the hash password which matches the username to login. I am new to php and this is the first time I am working with SQLite db as well as php. Please help me, I have been trying to do this for past few days now :(
Any help or guidance would be great.
(I have noticed there is not much with php and sqlite that I could find online and the similar questions I have seen on stack flow is related to mysql mostly. Also, I apologize if I am posting it right or if it is too easy of an answer because I am beginner and new to this. Thank you)
Here is how I am storing the password in hash in my registration.php which is working:
if(ISSET($_POST['register'])) {
//setting the variables
$user_id = $_POST['user_id'];
**//hashing the password
$password = PASSWORD_HASH($_POST['password'], PASSWORD_DEFAULT);**
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
//Inserting
$query = "INSERT INTO myTable (user_id, password, email, first_name, last_name) VALUES(:user_id, :password, :email, :first_name, :last_name)";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
//check to see if the exec of the query is success
if($stmt->execute()){
$_SESSION['success'] = "Account is created successfully";
//redirect to login
header("location:index.html");
}
}
Here is my login.php
$user_id = $_POST['user_id'];
$password = ($_POST['password']);
$query = "SELECT count(*) as count FROM myTable WHERE user_id=:user_id AND password=:password";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':password', $password);
// this is to execute
$result = $stmt->execute();
//this fetching from the db the user name and password. Where SQLite3_NUM returns an array by column number starting at 0 being the first
$row = $result->fetchArray(SQLITE3_NUM);
/*$stmt = $pdo->prepare("SELECT * FROM lit_login_credentials WHERE user_id = ?");
$stmt->execute([$_POST['user_id']]);
$stmt = $stmt->fetch();*/
//This is checking if the input login and user in the db is only entered once then it will go though else if not found then it will stay on the same page.
if($row[0] == 1 /*&& $user_id && password_verify($_POST['password'], $user_id['password'])*/){
//$out = "Success";
header('location: admin.php');
} else {
//$out = "invalid username or password";
//echo "<div class='alert alert-danger'>Invalid username or password</div>";
$_SESSION['error'] = "Invalid username or password";
header('location: index.php');
}
You need to use password_verify to compare the db password to the entered password.
Program should SELECT password from myTable WHERE user matches the entered user code. If any rows are returned (i.e. user is found), use password_verify to compare what is returned from the db and what is entered by the user. (Similar to the commented bit later in the code).
I've made this code to login in to a site, but my code always returns Onjuiste gegevens(incorrect data). I don't know why.
In my database I have made 1 account with username: sander and password: sander. When I enter this in the form I still get "Onjuiste gegevens". Could someone please help me to fix this?
<?php
$conn = mysqli_connect("localhost", "root", "", "login");
if (isset($_POST['inloggen'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND '$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1) {
echo "Juiste gegevens!";
} else {
echo "Onjuiste gegevens!";
}
echo "<br />";
}
?>
<form method="post" action="">
<label>Username</label>
<input type="text" name="username"/><br />
<label>Password</label>
<input type="password" name="password"/><br />
<input type="submit" name="inloggen" value="Inloggen"/>
</form>
There's a problem with your query, you've missed out password, it should be:
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
Also, you should prevent MySQL Injection:
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
Read more about mysqli_real_escape_string() at http://www.w3schools.com/php/func_mysqli_real_escape_string.asp.
Also read up on MySQLi Prepared Statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php, it's a good way to prevent MySQL Injection.
Tip: Remember to store passwords hashed for security purposes. Do not store them as plain-text.
Your query is not valid. You're forgetting the password column in your database.
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
Besides having a wrong query, the query is open for sql injections.
Try this
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
which improves security by using mysqli_real_escape_string() for post variables.
mysqli_real_escape_string() -
Escapes special characters in a string for use in an SQL statement,
http://php.net/manual/en/mysqli.real-escape-string.php
Your query's logic is wrong, you forget password:
SELECT * FROM users WHERE username = '$username' AND password='$password'
I found this forum thread to make a log-in and registration system, but it doesn't check if password is correct, only username.
This is my log-in page code:
<?php
include('config.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$emailusername = mysqli_real_escape_string($obj->conn,$_POST['emailusername']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$password = md5($password);
$sql="SELECT uid FROM users WHERE username='$emailusername' or email = '$emailusername' and password='$password'";
$result=mysqli_query($obj->conn,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$active=$row['active'];
$count=mysqli_num_rows($result);
// If result matched $username and $username, table row must be 1 row
if($count==1)
{
$_SESSION['login_user'] = $emailusername;
header("location: index.php");
}
else
{
$error="<div style ='color:#c53131'>Your Login Name or Password is invalid</div>";
}
}
?>
</div>
<form class="fl" action="login.php" method="post">
<label>Username:</label><br/>
<input type="text" name="emailusername"/><br />
<br/>
<label>Password:</label><br/>
<input type="password" name="password"/>
<input type="submit" value=" Submit "/><br />
</form>
This is the table I use:
"uid INT(11) PRIMARY KEY AUTO_INCREMENT,".
"username VARCHAR(30) UNIQUE,".
"password VARCHAR(50),".
"name VARCHAR(100),".
"email VARCHAR(70) UNIQUE); ";
I am new to PHP and have no clue how to make it check if password is correct or incorrect. Any suggestions?
Try your query as below :
SELECT uid FROM users
WHERE (username='$emailusername' or email = '$emailusername')
and password='$password'";
CHECK YOUR Query
$sql="SELECT uid FROM users WHERE (username='$emailusername' OR email = '$emailusername') AND(password='$password')";
Please try the bellow query :
SELECT uid
FROM users
WHERE (username='$emailusername' OR email = '$emailusername')
AND password='$password'
Hope this will help you.
The query should be like this.
$sql="SELECT uid FROM users WHERE (username='".$emailusername."' or email = '".$emailusername."') and password='".$password."'";
If you have to use different logical operators, you should add brackets individual evaluation. Moreover, you have to pass username and password as strings.
This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
This is how my users register for database, but my question is: How can I prevent the database from having copies of the same username, or in other words, how can I prompt to the user that "Your username already exists" if their username exists in the database.
<?php
$error = ""; // error
$GoodJob = "";
//When submit button is pressed, send data.
if(isset($_POST['submit'])){
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
$error = "<br>Please insert only letters or numbers.";
}else{
// Define username, firstname, lastname, email and password.
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Define database information
$hostnameV = "***";
$usernameV = "***";
$passwordV = "***";
$databaseV = "***";
//connection to the database
$connection = mysql_connect($hostnameV, $usernameV, $passwordV)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseV,$connection)
or die("Could not select company");
// To protect MySQL injection for Security purposes
$username = stripslashes($username);
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email = stripslashes($email);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
// SQL query to send information of registerd users
# FORMULA: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
$query = mysql_query("INSERT INTO `company`.`users` (`id`, `username`, `firstname`, `lastname`, `email`, `password`)
VALUES (NULL, '$username', '$firstname', '$lastname', '$email', '$password')", $connection);
//close the connection
mysql_close($connection);
} // end if statement
***
}
?>
<div id="main">
<div id="login">
<h2>REGISTER</h2>
<form action="" method="post">
<input id="name" name="username" placeholder="Pick a username" type="text">
<input id="name" name="email" placeholder="Your email" type="text">
<input id="name" name="firstname" placeholder="firstname" type="text">
<input id="name" name="lastname" placeholder="lastname" type="text">
<input id="password" name="password" placeholder="Create a password" type="password">
<input name="submit" type="submit" value=" REGISTER ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
I would first start by not using the mysql_* functions as they are deprecated and switch to PDO as it works correctly.
To answer your question, you should simply query the database for the username, if it exists, tell the user.
Before the Insert, using PDO and prepared statements.
$stmt = $dbh->prepare('SELECT count(*) FROM user WHERE username = ?');
$stmt->execute(array($username));
$res = $stmt->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
// tell the user it already exists.
} else {
// carry on with your insert.
}
As others have suggested, making the username unique should also be done. I wouldn't write my code to fail though when trying to insert a duplicate username, I would still test if it exists.
So to provide a bit more clarity, in reference to the below comments about using exceptions, here's why I wouldn't write my code to throw an exception if someone enters a username that is already taken. Exceptions, in my opinion, should be exceptions. That means that something exceptional happened. Someone entering a username that is already taken, I consider that to be a normal operation of the application and it should be handled in a normal non-exceptional fashion. If however, someone entered a valid username and between the time that I checked that it was not taken and when I'm running my insert, someone else grabbed that username (in that 2 millisecond timeframe), that would be an exception and I would handle it. To the user, that "exception" would look exactly the same, but in my code it would be handled as an exception.
So that's why I wouldn't just write my code to do an insert that throws an exception when someone enters a username that is already taken. I would check whether it's taken or not and then insert it, throwing an exception if that username was snagged between the time I checked and when it was inserted. I think that's good application design and proper use of exceptions. Others can disagree, but that's how I would do it. Exceptions should be exceptional, not part of the normal course of doing business.
You can set a validation for checking the username is exist or not.
<?php
function checkUserExist($username){
$checkExist = "SELECT username from userTable WHERE username ='" . $username . "'" or die(mysql_error());
mysql_query($checkExist);
if($checkExist > 0){//That means username is existed from the table
return true;
}else{//username isn't exist
return false;
}
}
if(checkUserExist($username)){//function return true
echo "username is already exist, please change.";
}else{
//Insert the user info into db
}
This is an example for checking the username by using function with mysql_query, you can also use PDO to implement it, Cheers!
I am trying to create a PHP login system. I am at the point where I have logged the user data into session variables, as well as into a user database using mysqli. When a user creates an account they get redirected to a profile page. On this page I am trying to display the user's email, and the user's username. I have no problem displaying the username as I stored it in a session variable. However, I can't seem to figure out how to get the email displayed. I did not store the email in a session variable. I am trying to retrieve it from the user database (not the session database). Here is some code:
showuser.php (profile page):
<?php
session_start();
$host="localhost"; // Host name
$uname="root"; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$mysqli = mysqli_connect($host, $uname, $password, $db_name);
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($em);
$stmt->fetch();
?>
<h2>Username - Email</h2>
<div id="userinfo"><? echo $_SESSION["username"] ?> - <? echo $em ?></div>
<?
$stmt->close();
mysqli_close($mysqli);
?>
storeuser.php
<?php
session_start();
$host="localhost"; // Host name
$uname="root"; // Mysql username
$password=""; // Mysql password
$db_name="itit"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$mysqli = mysqli_connect($host, $uname, $password, $db_name);
// Get values from form
$username=$_POST['username'];
$pw=$_POST['pw'];
$email=$_POST['email'];
$_SESSION["timeout"] = time();
$_SESSION["username"] = $_POST['username'];
$_SESSION["password"] = $_POST['pw'];
$_SESSION["loggedIn"] = true;
// Insert data into mysql
$sql = "INSERT INTO $tbl_name(username, password, email)VALUES(?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $username, $password, $email);
$stmt->execute();
?>
<?php
// close connection
mysqli_close($mysqli);
?>
application.js
$("#signupform").submit(function(e) {
e.preventDefault();
$.post('storeuser.php', $(this).serialize(), function(data){
$("#showuser").load("templates/showuser.php");
$("#userinfo").text(data);
$("#signupform").remove();
});
});
It was pointed out to me in a previous question I had (regarding PDO) - that for the email to get displayed on the profile page, I need to pass a "data" variable to my ajax $.post() call. Where does "data" get set? And, what is in "data"?
One weird thing is that if I replace this line:
$stmt->bind_param("s", $email);
to this:
$stmt->bind_param("s", $_SESSION["email"]);
the email gets displayed...but I never store the email in the session anywhere! There isn't even an email field! Why would the latter work, and not the former?
You are looking for an e-mail (using an undefined variable $email) instead of the user, you probably want this:
$stmt = $mysqli->prepare("SELECT email FROM users WHERE username = ?");
$stmt->bind_param("s", $_SESSION["username"]);
instead of this:
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param("s", $email);