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/
Related
<?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
I'm making a very simple login script (beginner at PHP) and here is my code. I can't figure out how to redirect after true login credentials. I know this probably is a duplicate but I can't figure this out without help on my exact script (as mentioned above I'm not that good).
update: So I have fixed name in password, form method, and the redirect . But now I'm getting to a empty page, something is wrong with my function as one comment earlier. I'm also a dummie at MySQL can someone help me further? My code is updated
Another update
Okay so i have finished all of my script, but the problem is my sql functions. So does anyone know mysqli and can translate it?
<?php $tilkobling = mysqli_connect("localhost","root","root","login_form");
if(isset($_POST["name"], $_POST["password"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$result1 = mysql_query("SELECT username, password
FROM user
WHERE username = '".$name."'
AND password = '".$password."'");
if(mysql_num_rows($result1) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>bypass to information site</h2>
<div class="login-page">
<div class="form">
<h1>Login</h1>
<form method="post" class="login-form">
<input name="name" type="text" placeholder="username"/>
<input name="password" type="password" placeholder="password"/>
<button name="submit">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script type="text/javascript">
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
You're using mysqli connector and mysql functions so let's assume you'll use mysql for all
$tilkobling = mysql_connect("localhost","root","root");
mysql_select_db( "login_form", $tilkobling );
and you'll need to add session_start() before using/setting any session variables
session_start();
$_SESSION["logged_in"] = true;
Your header needs to be in the true portion of the if/else, which is where you set your $_SESSION variables, here you are:
if(mysql_num_rows($result1) > 0 )
{
session_start();
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $name;
header("Location: information_site.php");
}
Have you Tried the HTML meta tag, this subtitutes the header() function.
Of course initially convert it into PHP code. Like this:
Echo "<meta http-equiv='refresh' content='0; URL=put your url in here to the page you like to redirect to'>" ;
This should probably operate correctly.
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.
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I am learning pHp. I have made a login page.
The problem i am facing here is that, when user clicks on signin button & if record is found then he is taken to other page which displays redirect link, the user has to click on that to go to the next page.
Now what i want that when a user click on signin button, then the details should be cross checked in the database, if the record is found then user should be directly redirected to next page else error should be displayed.
This is my html page:
<!DOCTYPE html>
<html>
<head>
<title>OpenMoz</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body style="height:650px;">
<h1 align="center" ><b><i>City Login</i></b></h1>
<div class="login">
<form action="login.php" method="post">
<input type="text" placeholder="Username" name="username" autocorrect=off autocapitalize=words required> <br>
<input type="password" placeholder="password" name="password" autocorrect=off autocapitalize=words required> <br>
<input type="submit" name="submit" value="Sign In">
</form>
<input type="submit" name="submit" value="Sign Up">
<div>
</body>
</html>
This is the login.php script to verify details :
<?php
$username = $_POST["username"];
$password = $_POST["password"];
if($username && $password)
{
$connect = mysql_connect("localhost","root","password") or die("Couldn't connect");
mysql_select_db("phplogin")or die("Couldn't connect");
$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'];
}
if($username==$dbusername && $password==$dbpassword)
{
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
}
else
{
echo ("Incorrect Password !");
}
}
else
die("The user doesn't exist");
}
else
echo ("Please enter username & password");
?>
I would be really thankful if my problem gets solved.
As long as you have not outputted anything to the browser, you can do a header redirect. This will achieve your aim.
Change this:
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
To this:
$_SESSION['username'] = $username;
header("Location: /some-new-page.php");
exit;
Always exit; after a location redirect.
Oh yeah, and CLEAN your inputs.. ..you are wide open to SQL Injection.
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Oh yeah .. and mysql_* is deprecated. Use mysqli_*
use header("Location:home.php"); its best way to redirect page in php
header("Location:whaeverpage.php");
exit();
Do it before sending any data to the browser or you will get a header allready sen error
or by javascript :
If($connected ==='yes'){//your connection statement
?>
<script>window.location.replace("whatever_page");</script>
<?
}
WOWOW NONONO HALT! DO NOT LEARN mysql_ API FOR NEW DEVELOPMENT. It's deprecated/unsupported, ancient, error-prone. learn to use mysqli_ or better yet, PDO , and here is a great tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
also here: $query = mysql_query("SELECT * FROM users WHERE username='$username'");
code is vulnerable to SQL injection attack by hackers. must use mysql_real_escape_string.
also, you should not use * , for most cases, be specific. Also, you should not store passwords in plaintext (as your login system is doing), you should hash it..
other than that, check Chris Magg's already said what i would'ev https://stackoverflow.com/a/31355969/1067003
I'm having some difficulty with PHP sessions.
The idea is to prevent users from accessing the administrator panel / pages by using the direct URL.
I have created a login form and that works well (login.php)
Once the username and password are correctly entered, the login form takes the user to the admin panel (admin.php)
However when I added the following script PHP to the (admin.php) page, it does not work.
When I enter the username and password on the login page, it always fails and re-directs me to login.php
The script on the admin.php is used to prevent users from accessing the page if
the session variable is not set
ANY help greatly appreciated :)
<link rel="stylesheet" type="text/css" href="admin_panel.css" media="all">
</head>
<body>
<form method="post">
<input type="text" name="user_name" placeholder="Username" required="required" />
<input type="password" name="user_pass" placeholder="Password" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large" name="login">Let me in.</button>
</form>
</div>
</body>
//===================================== login.php
<?php
include("includes.php");
if(isset($_POST['login'])) {
echo $user_name = mysql_real_escape_string ($_POST['user_name']);
echo $user_pass = mysql_real_escape_string ($_POST['user_pass']);
$encrypt = md5($user_pass);
$select_user = "select * from users where user_name= '$user_name' AND user_password = '$user_pass'";
$run_user = mysql_query($select_user);
if(mysql_num_rows($run_user)>0){ // what does this function DO?
$_SESSISON['user_name'] =$user_name;
echo "<script> window.open('admin_panel.php?logged=You have logged in','_self' )</script>";
}
else {
echo "<script> alert('Wrong details')</script>";
} }
?>
</html
// admin.php script ====================
<?php
session_start();
if(!isset($_SESSION['user_name'])) {
echo "<script>window.open('login.php','_self')</script>";
}
else { // ELSE CLOSED BOTTOM OF THE PAGE
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin page</title>
<link rel="stylesheet" type="text/css" href="admin_panel.css" media="all">
</head>
<body>
comments(0)
Insert New Post
Admin Logout
<?php
if(isset($_GET['insert_cat'])) {
include("insert_cat.php");
}
if(isset($_GET['insert_post'])) {
include("insert_post.php");
}
?>
</body>
<?php } ?> // CLOSE ELSE
</html>
It's better to use an authentication system from framework like Zend, Symfony, Laravel etc. than $_SESSION included in PHP.
To redirect user you can use function header()
for example:
header('Location: login.php');
it's important to set charset to 'UTF-8 without BOM' and it can't be any output before header()