I have a simple script for user login. I have the passwords encrypted as SHA1 in mySQL database table (using charset utf8_unicode_ci).
When I run "$q" in the database with values it returns result all right. But through the script even after entering correct credentials, I am not able to login. Also, it is working fine if I remove the encryption at both places (script and database). Same problem occurs if I use MD5 instead.
I am not sure what I am missing at. I tried to echo the SHA1 output and it comes out to be different than the encrypted password visible in the database. I have checked for any extra spaces in my input as well. Please help me understand what is wrong. Let me know if you need anything else. Thanks in advance!
connection.php holds the login credentials to the database and the below line:
$dbc = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
Below is the login page : "login.php"
<?php
#Start the session:
session_start();
include('../setup/connection.php');
if($_POST) {
$q = "select * from users where email = '$_POST[email]' and password = SHA1('$_POST[password]');";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1) {
$_SESSION['username'] = $_POST['email'];
header('Location: index.php');
}
else {$msg="Username/Password incorrect. Please try again!";}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php include('config/css.php'); ?>
<?php include('config/favicon.php'); ?>
<?php include('config/js.php'); ?>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js"></script>
<![endif]-->
</head>
<body>
<!--NAVIGATION BAR-->
<?php //include(D_TEMPLATE.'/navigation.php'); ?>
<div class="container">
<div class="col-lg-4 col-lg-offset-4">
<div class="panel panel-info">
<div class="panel-heading">
<h1 class="lato fs20"><strong>Login</strong></h1>
</div>
<div class="panel-body">
<?php echo $msg; ?>
<form role="form" method="post" action="login.php">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
For the "$q" variable, you should use php sha1 function:
$q = "select * from users where email = '$_POST[email]' and password = '" . sha1($_POST[password]) . "'";
But as Fred-ii said you really shoud (have to) protect your variables before.
For example :
$_POST['email'] = mysqli_real_escape_string($_POST['email']);
It will protect your variable against SQL injection (https://php.net/manual/en/mysqli.real-escape-string.php)
Related
I am a complete beginner when it comes to PHP. I have successfully created a login form/page that requires a user to enter his/her username and password which is then added to a database. I have also managed to create a page (using php) to display the data contained in all the data fields. I have the db connection file separately which works well. I have a functions.php file which contains the functions.
Now, I have created a php file in which I should be able to update the data in the various fields in the database. Instead of updating/replacing the existing data (username & password) in the selected row (targeting the id) it creates a new row in the db with the new username & password. Herewith my code to update existing data fields.
<?php include "db.php";?>
<?php include "functions.php";?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password', ";
$query .= "WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="col-sm-6">
<form action="login_create.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="UPDATE">
</form>
</div>
</div>
</body>
</html>
I can simply not find the problem. Since people use PHP differently I am unable to find a solution based on the specific coding I have tried.
Update
Kindly note that I am working on a localhost as part of learning php and have not yet started looking at security. I am initialising the $connection via a different file (db.php) which I am calling in the first line of my previous code.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');
if(!$connection) {
die("Database connection failed");
}
?>
Since you didn't say what does the login_create.php do and what is the filename of that php code in your post. I can only guess that your login_create.php file is to create a new account not update it. Perhaps your file with that UPDATE query is not named login_create.php. Hence, my guess is that you put a wrong filename in your <form action="login_create.php" method="post">
(Posted solution on behalf of the question author).
The problem was with the incorrect naming of the form action. I used
<form action="login_create.php" method="post">
instead of
<form action="login_update.php" method="post">
I created a login form that should direct the user to the page after sending the form but it just shows me a blank page
with a link of **http://localhost/Cisu/AccHolder/holderlogin.php
Login Form
<?php
session_start();
?>
<!DOCTYPE html>
<html >
<head>
<title>Login</title>
<link type="text/css" rel="stylesheet" href="css/login.css">
</head>
<body>
<form method="" action="holderlogin.php">
<div class="container">
<div class="profile">
<button class="profile__avatar" id="toggleProfile">
<img src="images/sbma.png" alt="Avatar" />
</button>
<div class="profile__form">
<div class="profile__fields">
<div class="field">
<input type="text" id="user" name="user" class="input" required pattern=.*\S.* />
<label for="username" class="label">Username</label>
</div>
<div class="field">
<input type="password" id="pass" name="pass" class="input" required pattern=.*\S.* />
<label for="password" class="label">Password</label>
</div>
<div class="profile__footer">
<input id="Submit" name="Submit "type = "Submit" class="btn"/>
</div>
</div>
</div>
</div>
</div>
<script src="javascript/login.js"></script>
</form>
</body>
</html>
holderlogin.php
<?php
ob_start();
session_start();
include('dbconn.php');// Database connection and settings
// checking the user
if(isset($_POST['Submit'])){
$user = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from tbl_accholder where accholder_Username='$user' AND accholder_Password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user==1){
while ($row = mysqli_fetch_array($run_user)) {
$run_ID = $row['accholder_ID'];
$run_user = $row['accholder_Username'];
}
$_SESSION['accholder_Username']= $user;
$_SESSION['accholder_ID']= $run_ID;
header( 'Location: MainMenu.php');
} else
echo "please wait while redirecting...";
echo "<script> alert('Log-In Failed!'); </script>";
echo "<script> document.location.href = 'Login.php' </script>";
ob_end_flush();
}
?>
You are checking whether $_POST['Submit'] is set.
However, in your form, the name attribute is Submit with an extra space:
<input id="Submit" name="Submit "type = "Submit" class="btn"/>
This might be the cause of the problem, since you said it shows me a blank page.
also - you have no method listed for your form, but are checking the $_POST array to check for "Submit". It should be:
<form method="POST" action="holderlogin.php">
Don't know if its causing your problem, but you have a leading space before the php declaration - this can be cause problems to the php rendering if you are setting header requests later in the code - there can be no characters rendered before the header request.
<?php
also you list the action of the form as "holderlogin.php"
but list the name of the file as "Holderlogin.php" - this might just be a typo when entering the code here but worth checking.
I have a page (index.php) is a login page so I need to validate a user and redirect to other page but header(Location:"welcome.php"); is not working, the sql query is ok but I only get the message "Login Successful" and the page doest redirect to the other called welcome.php
I'm newbie in PHP so any help is great!
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="favicon.ico">
<title>Login</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label><input type="checkbox" value="remember-me"> Remember me </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
<?php
$link = mysqli_connect("localhost","root","root","testdb") or die ("error".mysqli_error($link));
$username = $_POST['username'];
$password= $_POST['password'];
if (isset($_POST['username'])) {
$sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
$result = mysqli_query($link,$sql);
if ($result);
{
$num=mysqli_num_rows($resultado);
}
if($num==1)
{
header("Location: welcome.php");
exit();
}else{
header("Location:wrong.php");
}
mysqli_free_result($result);
mysqli_close();
}
?>
It is because you are sending output before issuing the redirect. You can't change the HTTP headers once you have started printing the body of the HTTP message.
// echo "Login Successful"; // remove this line and all other HTML
header("Location: welcome.php");
exit();
Basically you have to restructure the program so that when the form is submitted you are not sending output to the browser.
Example pseudo code:
if user has submitted the form then
authenticate user
if authentication is successful then
redirect user to welcome.php
else
show login page and error message
else
show login page
thought this might help on top of the real answer that robbmj provided
Create 3 folders...
Views
Models
Controllers
In the Views folder, create a php file called "Login.php"
Inside that php page paste your html form:
<!DOCTYPE html>
<head>
</head>
<body>
<div class="container">
<form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>/Controllers/Login.php" method="POST">
<h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label><input type="checkbox" value="remember-me"> Remember me </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
</body>
</html>
Inside your Models folder, create a file called SQLDbContext.php
Inside that file place the code like so:
class SQLDbContext
{
public $link;
public function Connect()
{
$this->link = mysqli_connect( "localhost", "root", "root", "testdb")
or die ( "error" . mysqli_error( $enlace ) );
}
public function __Destruct()
{
mysql_free_result($result);
mysql_close();
}
}
Inside your Models folder, create a file called AuthenticationRepository.php
Inside that file, place the code like so:
require_once( "SqlDbContext.php" );
class AuthenticationRepository extends SQLDbContext
{
public function __Construct()
{
$this->Connect();
}
public function GetUsersByUsernameAndPassword( $username, $password )
{
$sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
$result = mysqli_query( $this->link, $sql );
return $result;
}
}
Create a Login.php file inside Controllers (You'll notice I changed your action to /Controllers/Login.php in your Login view
Inside that php file, place your logic to login:
require_once( "../Models/AuthenticationRepository.php" );
$authenticationRepository = new AuthenticationRepository();
$username = $_POST[ "username" ];
$password = $_POST[ "password" ];
$usersInDb = $authenticationRepository->GetUsersByUsernameAndPassword( $username, $password );
$num = mysqli_num_rows( $usersInDb );
if( $num == 1 )
{
header("Location: Views/Welcome.php");
}
else
{
// Set a $_SESSION here and in the Views/Login.php check for that $_SESSION being set
header("Location: Views/Login.php");
}
NOTES:
- You will notice that nothing has been echo'd to the screen before a header(...) has been issued.
- You will notice that all logic has been divided up (wrongly but itll get you started).
- YOU STILL NEED TO DO SQL injection checks and validation etc, but i'll leave that for you to do buddy
By doing all of this, you avoid alot of the problems you have at the moment... There is so much you can do here to improve this code, In fact, the above code really isn't too hot either, but it's a step in the right direction... Seperate all of your stuff out... Check out http://www.laravel.com which is an MVC framework made to help you not screw things up too much :)
Below is my code(jquery mobile and php) I am trying to insert into the database and also echo the following message (pls fill all field and registration complete) that is if the user complete the field or not the following message show display but non of it is working with my jquery mobile code and it is working with my normal site how can I fix this I will appreciate it if you work on my code thank you
<?php
$db= “user”;
$connect = mysql_connect(“localhost“, “alluser”, “six4”)or die(“could not connect”);
Mysql_select_db($db) or die (“could not select database”);
If (isset($_POST['submit'])){
If(empty($_POST['name']) OR empty($_POST['email']) OR empty($_POST['add'])){
$msg = 'pls fill all field';
$name = ($_POST['name']);
$email = ($_POST['email']);
$address = ($_POST['add']);
mysql_query(“INSERT INTO people (Name, Email, Address”) VALUES ('$name, $email, $address')”) or die (mysql_error());
$msg='registration complete ';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="css/jquery.mobile-1.0a1.min.css" />
<script src="js/jquery-1.4.3.min.js"></script>
<script src="js/jquery.mobile-1.0a1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>User</h1>
</div>
<div data-role="content">
<?php echo “$msg”; ?>
<form name=“form” action=“” method=“post”>
<label for=“name”>Name</label>
<input type=“text” name=“name” />
<label for=“email”>Email</label>
<input type=“text” name=“email” />
<label for=“address”>Address</label>
<input type=“text” name=“add” />
<input type=“submit” name=“submit” value=“Submit” />
</form>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
Check your brace positions after your if statements. You check for empty values, but you don't alter the program flow in a meaningful way if you find them.
Also, replace your curly quotes with real quotes. And check for SQL injection. And double-check your MySQL call. You'll get an error from PHP before you'll ever get $msg echoed, based on the way things are written.
I'm trying to update my database records with the following code but am having no luck what so ever. Anybody care to help? Thanks
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Project Sproom</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
if(!empty($_POST['username']) && !empty($_POST['email']))
{
$newusername = mysql_real_escape_string($_POST['username']);
$newemail = mysql_real_escape_string($_POST['email']);
$edit = mysql_query("UPDATE users (Username, EmailAddress) VALUES('".$newusername."', '".$newemail."') WHERE UserID=".$_SESSION['UserID']."");
// }
?>
<div id="container">
<div id="homemenu">
<ul id="navlist">
<li id="active">Home</li>
<li>Edit Profile</li>
</ul>
</div>
<div id="homemain">
<h1>Edit Profile</h1>
<p>This will be the edit profile when i have figured out how to do it...</p>
<br />
<form method="post" action="profile.php" name="editprofile" id="editprofile">
<label for="username">Username: </label> <input type="text" name="username" id="username" value="<?=$_SESSION['Username']?>"/><br />
<label for="email">E-Mail: </label> <input type="text" name="email" id="email" value="<?=$_SESSION['EmailAddress']?>"/> <br />
<input type="submit" name="editprofile" id="editprofile" value="Submit" />
</fieldset>
</form>
</div>
</div>
<?php
}
else
{
?>
<meta http-equiv="refresh" content="0;index.php">
<?php
}
?>
You're using INSERT syntax for an UPDATE query. The syntax should be like this:
UPDATE users SET Username = 'username', EmailAddress = 'email' WHERE UserID = 1;
Docs here.
You haven't connected to the MySQL database, have you?
I didn't see that in this code...
Or is that part of the included "base.php" on top of this script?
I am afraid you need fist establish a connection to a certain MySQL database before trying to update a row in a table.
Edit:
Okay, well then. Try issue the following line of code after the update:
echo "edit was " .$edit;
This is to check whether the update query was executed successfully (in which case it should echoes true) or failed (in which case it echoes false).
So at least you can tell the result of such a mysql_query.
$edit = mysql_query("UPDATE users SET Username='".$newusername."', EmailAddress='".$newemail."' WHERE UserID=".$_SESSION['UserID']."");
Try this