<?php
session_start();
include("includes/db.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Login</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="container"><!-- container starts-->
<form class="form-login" action="" method="Post"><!-- form-login starts-->
<h2 class="form-login-heading"> Admin Login</h2>
<input type="text" class="form-control" name="admin_email" placeholder="Email Address" required>
<input type="password" class="form-control" name="admin_pass" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="admin_login">
Log In
</button>
</form><!-- form-login ends-->
</div><!-- container ends-->
</body>
</html>
<?php
if(isset($_POST['admin_login']))
{
$admin_email=mysqli_real_escape_string($con,$_POST['admin_email']);
$admin_pass=mysqli_real_escape_string($con,$_POST['admin_pass']);
$get_admin="select * from admins where admin_email='$admin_email' AND admin_pass=' $admin_pass'";
$run_admin=mysqli_query($con,$get_admin);
$count=mysqli_num_rows($run_admin);
if($count==1){
$_SESSION['admin_email']=$admin_email;
echo"<script>alert('You are logged in into admin panel')</script>";
echo"<script>window.open('index.php?dashboard','_self')</script>";
}
else{
echo"<script>alert('Email Or password is wrong')</script>";
}
}
?>
I have a problem in my query. In my login panel when i write the email and password which I have stored in my database the if condition fails and the else portion of the code is run even if I use the same password and email which I stored in my database.
I've just noticed that your query:
$get_admin="select * from admins where admin_email='$admin_email' AND admin_pass=' $admin_pass'";
has a space before the $admin_pass variable is used.
Try adjusting this to:
$get_admin="select * from admins where admin_email='$admin_email' AND admin_pass='$admin_pass'";
There's a space in your query where you pass in the admin password:
"AND admin_pass=' $admin_pass'"
should be:
"AND admin_pass='$admin_pass'"
Rather than fixing this bug though you should make some more major changes:
Don't build queries by manually appending variables passed in by your users otherwise you will be vulnerable to SQL injection attacks. You should be using prepared statements instead. See http://php.net/manual/en/mysqli.prepare.php. Although you are using mysqli_real_escape_string which will help prevent SQL-I its quite error prone compared to using prepared statements.
Don't store passwords in a database, you should at a minimum store them encrypted but preferably store a password hash instead. php even has 2 functions which do this for you password_hash to generate hashes: http://php.net/manual/en/function.password-hash.php and password_verify to check them: http://php.net/manual/en/function.password-verify.php
Related
I am trying to make an update Password page for an exercise. I have created an old Password field a new Password field and a repeat Password field.
I have created this on my own. I would be glad if you guys can tell me what my mistakes in my code are cause i somehow cant make the page work. Also it would be interesting to know what i could do better when it Comes to security.(I also have a login, Register, welcome page that all work)
Greetings
session.php:
<?php
include('connection.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($db,"select * from clients where email = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$_SESSION['email']=$row['email'];
$_SESSION['username']=$row['username'];
$_SESSION['firstname']=$row['firstname'];
$_SESSION['lastname']=$row['lastname'];
$_SESSION['birthdate']=$row['birthdate'];
$_SESSION['street']=$row['street'];
$_SESSION['streetnr']=$row['streetnr'];
$_SESSION['city']=$row['city'];
$_SESSION['plzz']=$row['plzz'];
if(!isset($_SESSION['login_user'])){
header("location:http://localhost:81/Left_over_youth_website/pages/login.php");
}
?>
Connection.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'leftoveryouth');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
changepd:
<?php
include("../php/session.php");
?>
<html>
<head>
<title>Forgot Password</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" name="viewport">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="../scripts/newpd.js"></script>
<link rel="stylesheet" href="../css/changepd.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body class="img">
<div class="placeholder">
<h1 class="logo">Leftover Youth</h1>
<img class="logoo" src="../img/logoo.png" alt="firstimage">
<form class="form">
<hr class="verticalline">
<input class="oldpd" id="oldpd" value="Old Password"
onblur="this.value'Old Password':this.value;"
onfocus="this.select()"
onclick="if (this.value=='Old Password'){this.value=''; this.type='password'}">
<input class="newpd shine" id="newpd" value="New Password"
onblur="this.value'New Password':this.value;"
onfocus="this.select()"
onclick="if (this.value=='New Password'){this.value=''; this.type='password'}">
<input class="repeatpd shine" id="repeatpd" value="Repeat Password"
onblur="this.value'Repeat Password':this.value;"
onfocus="this.select()"
onclick="if (this.value=='Repeat Password'){this.value=''; this.type='password'}">
<p hidden style="color:red;" id="pdontmatch">☒ Password doesn't match</p>
<p hidden style="color:lightgreen;" id="pmatch">☑ Password matches</p>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myoldpassword = sha1($_POST['oldpd']);
$newpassword = sha1($_POST['newpd']);
$repeatpassword = sha1($_POST['repeatpd']);
$sql = "SELECT password FROM clients WHERE password = '$myoldpassword'";
$result = mysqli_query($db,$sql);
if($result){
if($newpassword===repeatpassword){
$_SESSION["password"] = $newpassword;
$update = "UPDATE CLIENTS SET password = mynewpassword";
header("location:http://localhost:81/Left_over_youth_website/php/logout.php");
}
else{
echo('<p>password not updated</p>');
}
}
}
?>
<input id="button" type="button" value="Submit" onclick="ausgabe(); marginn();">
<script>
function marginn(){
document.getElementById('button').style.marginTop = "5px";
}
</script>
</form>
</div>
</body>
</html>
If you need further explenation or code pls tell me.
-EDIT-
cause i somehow cant make the page work.
You edited your question and added that line. I thought you were only looking for advice on security. What exactly is not working?
You're open to SQL injection attack every time you embed variables in
your queries. where email = '$user_check'").
You should use parameterized queries instead. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
https://phpdelusions.net/pdo
Don't use SHA1 for password hashing - it is not secure.
Secure hash and salt for PHP passwords. How to use password_hash
Don't store very sensitive data (like passwords) in the session.
$_SESSION["password"] = $newpassword; Even though the session
resides on the server, the data is often stored in files which can be
accessed by other users especially if used in a shared hosting
environment.
Is email a primary key? If not, your query will return multiple
rows and then you'd be accessing a random row in PHP.
mysqli_query($db,"select * from clients where email = '$user_check'");
Make sure $row exists and is not empty before using it. What
happens if you enter a non-existent email address?
By using JS to check if the value is the default value you are adding unnecessary complexity.
onclick="if (this.value=='Old Password'){this.value=''; this.type='password'}"
Instead, just use the placeholder attribute.
https://html.com/attributes/input-placeholder/
I am creating a login form, profile page and logout, but when I receive a wrong username message on the page and click the x button, it does not close. Also, when I add just the username and click on the log in button, the page goes blank. Could someone assist me in identifying what is askew here?
<?php
/*
STEPS WE NEED TO TAKE...
1. Build Login HTML form
2. Check if form has been submitted
3. Validate form data
4. Add form data to variables
5. Connect to database
6. Query the database for username submitted
6.1 If no entries: show error message
7. Store basic user data from database in variables
8. Verify stored hashed password with the one submitted in the form
8.1 If invalid: show error message
9. Start a session & create session variables
10. Redirect to a "profile page"
10.1 Provide link to "logout" page
10.2 Add cookie clear to logout page
10.3 Provide link to log back in
11. Close the MySQL connection
*/
if(isset($_POST['login'])) {
// build a function to validate data
function validateFormData($formData) {
$formData = trim(stripslashes(htmlspecialchars($formData)));
return $formData;
}
// create variables
// wrap the data with our function
$formUser = validateFormData($_POST['username']);
$formPass = validateFormData($_POST['password']);
// connect to database
include('connection.php');
// create SQL query
$query = "SELECT username, email, password FROM users WHERE username='$formUser'";
//store the result
$result = mysqli_query($conn, $query);
// verify if result is returned
if(mysqli_num_rows($result) > 0) {
// store basic user data in variables
while($row - mysqli_fetch_assoc($result)) {
$user = $row['username'];
$email = $row['email'];
$hashedPass = $row['password'];
}
// verify hashed password with the typed password
if(password_verify($formPass, $hashedPass)) {
// correct login details!
// start the session
session_start();
// store data in SESSION variable
$_SESSION['loggedInUser'] = $user;
$_SESSION['loggedInEmail'] = $email;
header("Location: profile.php");
} else { // hashed password didn't verify
// error message
$loginError = "<div class='alert alert-danger'>Wrong username / password combination. Please try again.</div>";
}
} else { // there are no results in database
$loginError = "<div class='alert alert-danger'>No such user in database. Please try again. <a class='close' data-dismiss='alert'>×</a></div>";
}
// close the mysql connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login</title>
<!--Bootstrap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!--HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries-->
<!--WARNING: Respond.js doesn't work if you view the page via file://-->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<h1>Login</h1>
<p class="lead">Use this form to log into your account</p>
<?php echo $loginError; ?>
<form class="form-inline" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-group">
<label for="login-username" class="sr-only">Username</label>
<input type="text" class="form-control" id="login-username" placeholder="username" name="username">
</div>
<div class="form-group">
<label for="login-password" class="sr-only">Password</label>
<input type="password" class="form-control" id="login-password" placeholder="password" name="password">
</div>
<button type="submit" class="btn btn-default" name="login">Login!</button>
</form>
</div>
<!--Bootstrap JS-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
"Fred, the varchar on my db for password is set to 255. There is no existing hashed password as of yet. I am trying to create a login page to create one in the db. – Daniel Cortes"
The problem is that there isn't a hashed password in your database to be compared with.
You will need to create one using the password_hash() function.
http://php.net/manual/en/function.password-hash.php
Sidenote:
Using stripslashes(htmlspecialchars doesn't safeguard against an SQL injection. It's best to use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
Also Your alert is not disappearing because Bootstrap depends on Jquery lib, and you did not imported it.
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)
I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O
In the following code, data from html form is not received by php variables. The code directly executes if-else statement without waiting for input.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("fb");
$id=$_POST["email"];
$pwd=$_POST["password"];
$sql=mysql_query("SELECT* FROM admin WHERE id='$id' AND pass='$pwd'");
if($sql)
{
die ("Login");
}
else
{
die ("Failed");
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<!--<link rel="stylesheet" type="text/css" href="style.css" />!-->
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
I know this code is vulnerable to SQL injection but who care if its an home assignment. :)
The code directly executes if-else statement without waiting for input.
The reason being is that you have your entire code (HTML/PHP/SQL) inside one file with no conditional statement to control it.
Using your submit button's name element with if(isset($_POST['Login'])) will fix that.
Another option would be to use two seperate files. One with your form and the other with the PHP/SQL and setting action="handler.php" for your form's action.
<form method="POST"> is equivalent to <form method="POST" action=""> (self).
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("fb");
$id=$_POST["email"];
$pwd=$_POST["password"];
if(isset($_POST['Login'])){
$sql=mysql_query("SELECT * FROM admin WHERE id='$id' AND pass='$pwd'");
if($sql)
{
die ("Login");
}
else
{
die ("Failed");
}
} // brace for if(isset($_POST['submit']))
?>
The following links will help you later on.
For passwords, CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Plus, mysqli with prepared statements, or PDO with prepared statements.
Always use error reporting this will help you to debug code.
Plus, use or die(mysql_error()) to mysql_query() instead of just the way you have it now. It will signal the actual error, should there be any.
The code directly executes if-else statement without waiting for input.
Then tell it to do those action after input.
if($_POST) {
$id=$_POST["email"];
$pwd=$_POST["password"];
$sql=mysql_query("SELECT* FROM admin WHERE id='$id' AND pass='$pwd'");
if($sql)
{
die ("Login");
}
else
{
die ("Failed");
}
}
I know this code is vulnerable to SQL injection but who care if its an home assignment.
Never give up security just because of the nature of the project. You'll fall into a trap, and then it will bite you later on in life. Make sure you secure your application irregardless of the project.