Reputation: 103
I try to made login script, but I stopped at the validation of input values. Here is my html code form login.php:
<form method="post" action="loginpro.php">
Username:
<input id="field" type="text" name="username" required>
User email:
<input id="field" type="text" name="email" requerid>
Password:
<input id="field" type="password" name="password" required>
<input id="button" type="submit" value="Log in">
</form>
And this is my loginpro.php file:
<?php if(isset($_POST['username']) && $_POST['username'] !== '' && isset($_POST['email']) && $_POST['email'] !== '' && isset($_POST['username']) && $_POST['username'] !== ''){
require("../admin/libsec/connect.php");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_passoword = hash('sha384', $password);
$query = "SELECT * FROM user WHERE username = '{$username}' AND email = '{$email}' AND password '{$hashed_passoword}';";
$result = mysqli_query($con,$query);
// How to check if is query good so i can set session or if is not good to redirect to another page?
}
?>
Upvotes: 0
Views: 522
Reputation: 41885
You could use num_rows()
in this case to see if your query yielded rows:
<?php
session_start();
if(
(isset($_POST['username']) && $_POST['username'] !== '') &&
(isset($_POST['email']) && $_POST['email'] !== '') &&
(isset($_POST['username']) && $_POST['username'] !== '')
){
require("../admin/libsec/connect.php");
$username = $con->real_escape_string($_POST['username']);
$email = $con->real_escape_string($_POST['email']);
$password = $con->real_escape_string($_POST['password']);
$hashed_passoword = hash('sha384', $password);
$query = "SELECT * FROM user WHERE username = '{$username}' AND email = '{$email}' AND password = '{$hashed_passoword}'; ";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
// How to check if is query good so i can set session or if is not good to redirect to another page?
if(mysqli_num_rows($result) > 0) {
// user found
$_SESSION['logged_in'] = true;
header('Location: home.php');
} else {
// redirect the user back to login
header('Location: login.php');
}
}
?>
Sidenote: By the way, since you're using mysqli, why not utilize prepared statements.
Upvotes: 1
Reputation: 1302
Assuming your usernames are unique you'll get back either one or no result rows. If you didn't get one, the credentials are wrong, if your result has one line they were right.
And don't use string concatenation to create SQL queries! This is a big security risk. Habe a look at Prepared Statements instead.
Upvotes: 0