Im trying to allow users that are on the database to log in if their credentials are present, problem is, whenever I enter details into the login screen, it will always return Invalid Login Credentials, regardless of whether or not the name/password is on the database.
Here is what I'm working with:
loginSubmit.php
<?php
//begin our session
session_start();
//Check the username and password have been submitted
if(!isset( $_POST['Username'], $_POST['Password']))
{
$message = 'Please enter a valid username and password';
}
else
{
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$query = "SELECT * FROM
customers WHERE name =
('$_POST[Username]' AND password = '$_POST[Password]')";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $username;
}
else
{
echo "Invalid Login Credentials";
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
echo "Hello " . $username;
}
}
catch(Exception $e)
{
$message = 'We are unable to process your request. Please try again later"';
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
Login.php
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Here</h2>
<form action="loginSubmit.php" method="post">
<fieldset>
<p> <label for="Username">Username</label>
<input type="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</fieldset>
</form>
</body>
</html>
AddUser
//Enter the valid data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = sha1($password);
//Connect to the database
$SQLusername = "root";
$SQLpassword = "";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (name, password)
VALUES
('$_POST[Username]','$_POST[Password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
//Unset the form token session variable
unset( $_SESSION['formToken'] );
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
if($ex->getCode() == 23000)
{
$message = 'Username already exists';
}
else
{
$message = 'We are unable to process your request. Please try again later"';
}
It might be because of this, the way you have the brackets.
-Please see my notes about using prepared statements and password_hash() below.
SELECT * FROM customers
WHERE name = ('$_POST[Username]'
AND password = '$_POST[Password]')
Change it to:
SELECT * FROM customers
WHERE name = '$username'
AND password = '$password'
and for testing purposes, try removing
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
that could be affecting / rejecting characters. Make sure there is no white space also.
Also changing if($count == 1) to if($count > 0)
or replacing $count = mysql_num_rows($result); if($count == 1) { with if(mysql_num_rows($result) > 0){
Your password is not being hashed
After testing your Adduser code, I noticed is that your hashed password isn't being stored as a hash.
Change ('$_POST[Username]','$_POST[Password]') in your Adduser page to ('$username','$password').
I suggest you move to mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, your present code is open to SQL injection.
Here is a good site using PDO with prepared statements and password_hash().
http://daveismyname.com/login-and-registration-system-with-php-bp
See also:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Try this mate
$query = "select * from customer where name = '" .$username ."' and password = '" .$password ."'";
//use the SANITIZED data
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row) {
$_SESSION['name'] = $row['name'];
$_SESSION['password'] = $row['password'];
}
else { //not found
header('Location: go back.php?error=2');
}
echo "Hello " . $username;
Related
I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>
I've made/copied a fitting and nice inlog page.
I've made it fully functional except there is one mistake, when the username and password arent in the DB it still redirects?
The login form:
<div class="login">
<h1>Login</h1>
<form method="post" action="connectivity.php">
<input type="text" name="user" placeholder="Gebruikersnaam" required/>
<input type="password" name="pass" placeholder="Wachtwoord" required/>
<input id="button" type="submit" class="btn btn-primary btn-block btn-large" name="submit" value="Log-In">
</br>
And the php code where its getting posted:
<?php
session_start();
$user = $_POST['user'];
$_SESSION['user'] = $user;
define('DB_HOST', 'localhost');
define('DB_NAME', 'mkuiper1');
define('DB_USER','mkuiper1');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn($data){
//checking the 'user' name which is from Sign-In.html, is it empty or have some text
if(!empty($data['user'])){
//$query = mysql_query("SELECT * FROM WebsiteUsers where userName = '".$data['user']."' AND pass = '".$data['pass']."'") or die(mysql_error());
// The above query is sql-injecation valnerable query, use the below query instead
// Also do not use mysql erxtension anymore is deprecated, use mysqli instead
// Let us say that your db connection is stored in $con variable
$stmt = $con->prepare("SELECT * FROM WebsiteUsers where userName = '$_POST[user]' AND pass = '$_POST[pass]'");
$stmt->bind_param('ss', $data['user'],$data['pass']);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows>0){
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$_SESSION['userName'] = $row['pass'];
//echo "Login Succesvol!"; do not echo anything here before redirecting !!!
$_SESSION['loggedin'] = 1;
header("Location: index.php");
}
}
}
} else{
$message = "Verkeerde Gebruikersnaam/Wachtwoord!";
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('$message')
window.location = '/Sign-In.php';
</SCRIPT>");
}
}
if(isset($_POST['submit'])){
SignIn($_POST);
}
?>
But it still goes and stays on connectivty.php, even when the pass and username are incorrect.
Sorry for the bad english
Jesse
As I said in my comment, there are many issues with your code, this function should solve them:
function SignIn($data){
//checking the 'user' name which is from Sign-In.html, is it empty or have some text
if(!empty($data['user'])){
//$query = mysql_query("SELECT * FROM WebsiteUsers where userName = '".$data['user']."' AND pass = '".$data['pass']."'") or die(mysql_error());
// The above query is sql-injecation valnerable query, use the below query instead
// Also do not use mysql erxtension anymore is deprecated, use mysqli instead
// Let us say that your db connection is stored in $con variable
$stmt = $con->prepare('SELECT * FROM WebsiteUsers where userName = ? AND pass = ?');
$stmt->bind_param('ss', $data['user'],$data['pass']);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows>0){
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$_SESSION['userName'] = $row['pass'];
//echo "Login Succesvol!"; do not echo anything here before redirecting !!!
$_SESSION['loggedin'] = 1;
header("Location: index.php");
}
}
}
} else{
$message = "Verkeerde Gebruikersnaam/Wachtwoord!";
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('$message')
window.location = '/Sign-In.php';
</SCRIPT>");
}
}
if(isset($_POST['submit'])){
SignIn($_POST);
}
i want to create a login page, display the data from database of particular user in table form upto 4 columns and 1 row and also should be able to update the table data's and then logout. can anyone help me in this with a script. i need it to be done using php, mysql. i have tried till this, but i don't know what to do beyond this.
<html>
<form action="login.php" method="post">
Username: <input type="text" name="username"><p>
Password: <input type="password" name="password"><p>
<input type="submit" value="Log in!" >
</form>
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("localhost", "root", "") or die("Couldn't connect to the database!");
mysql_select_db("login") or die("Couldn't find database");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows!==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password']; # code...
}
if ($username==$dbusername&&$password==$dbpassword)
{
echo "You are logged in!";#
#$_SESSION['usernme'] = $username;
}
else
echo "Your password is incorrect!";
# code...
}
else
die("That user doesn't exists!");
}
else
die("Please enter a username and password!")
?>
Why not directly let MySQL check if the combination of username and password is correct?
$query = mysqli_query("SELECT * FROM users WHERE username='" . $username . "' AND password = '" . $password . "'");
Only if mysqli_num_rows($query) == 1, there is a valid login. More than 1 row should not be possible.
I am trying to display an error message in php ( $error="Username or Password is invalid";
) when the username or password is not in the database. But without even running the code(clicking login in index.php the error message is displaying. Thanks :)
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
}
if (isset($_POST['submit'])) {
// Define $username and $password
$name=$_POST['username'];
$pass=$_POST['password'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
if($name==$row["username"] && $pass== $row["password"]){
header("location: profile.php"); // Redirecting To Other Page
}else{
$error="Username or Password is invalid";
}
}
}
else {
echo "Server is down";
}
$conn->close();
}
?>
My index.php
<?php
include('../php/login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
I updated your security a little. Make sure you always validate user input. The code below is secure against SQL injections. No way of injection possible! Also HEX attacks are not possible.
<?php
if (!isset($_SESSION)) { session_start(); }
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "company";
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errmessage = $error = '';
function checkUsername($data) {
if (preg_match('/[^A-Za-z0-9.]{8,50}/', $data)) { // A-Z, a-z, 0-9, . (dot), min-length: 8, max-length: 50
$data = false;
}
return $data;
}
function checkPassword($data) {
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,50}$/', $data)) { // A-Z, a-z, 0-9, !, #, #, $, %, min-length: 8, max-length: 50
$data = false;
}
return $data;
}
if (isset($_POST['submit']) && isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (checkUsername($username) === false) {
$error = "Username is not valid!";
exit();
}
if (checkPassword($password) === false) {
$error = "Password is not valid!";
exit();
}
$secure_name = bin2hex(htmlspecialchars($username));
//$secure_pass = hashpassword($securepass); // Hash your passwords!
$secure_pass = bin2hex(htmlspecialchars($password));
$sql = "SELECT * FROM login WHERE username = UNHEX('$username') AND password = UNHEX('$password')";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
session_regenerate_id();
$_SESSION['login_user'] = true;
header("location: profile.php");
} else {
$error = "Username and/or Password is invalid";
}
$conn->close();
} else {
echo "Error";
}
?>
Source for HEX against injection: How can I prevent SQL injection in PHP? (Zaffy's answer)
Extra information:
Do not check only if the session login exist, but check also its value!
if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
Must be
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] === true){
header("location: ../php/profile.php");
exit();
} else {
// Loginscript
}
The PHP script seems to take ALL username/password pairs from DB
$sql = "SELECT id, username, password FROM login";
Later in while loop first pair not matching with user input would trigger an error message assignment
Okay, I'm new to PHP, SQL, and HTML and I after several days I finally got my website fully coded. Now I am writing code for users to register and login. I got the register to work, but not the login.
I get the following error:
Parse error: syntax error, unexpected T_STRING in /home/u190182631/public_html/index.html on line 58
What am I doing wrong?
PHP:
<?php
$mysql_host = "xxx";
$mysql_database = "xxx";
$mysql_user = "xxx";
$mysql_password = "xxx";
$errorU = $errorP = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["username"]))
{
$errorU = "Please Enter your Username";
}
if(empty($_POST["pword"]))
{
$errorP = "Please eneter a Password";
}
if ($errorU == "" && $errorP == "")
{
$con=mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
$username = $_POST["username"];
$password = $_POST["pword"];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons WHERE Username = '$username' and Password = '$password',$con) or exit('$sql failed: '.mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows==0)
{
echo('okay');
}
else
{
echo('no');
exit;
}
}
}
?>
Form in HTML:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="pword">
<input type="submit" value="Login">
</form>
You are not closing this string
$result = mysqli_query($con,"SELECT * FROM Persons WHERE Username = '$username' and Password = '$password',$con) or exit('$sql failed: '.mysql_error());
it should be
$result = mysqli_query($con,"SELECT * FROM Persons WHERE Username = '$username' and Password = '$password'") or exit('$sql failed: '.mysql_error());
On another note. Please do not use unfiltered data when getting things from a database. You will have problems with sql injection. Also don't store the password in plain text. Hash it with salt.
EDIT: You really should use PDO's. See this link: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
probably you missed " in
$result = mysqli_query($con,"SELECT * FROM Persons WHERE Username = '$username' and Password = '$password',$con) or exit('$sql failed: '.mysql_error());
try:
$result = mysqli_query($con,"SELECT * FROM Persons WHERE Username = '$username' and Password = '$password',$con)" or exit('$sql failed: '.mysql_error());