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.
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'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'm working on a login page who if you login you're redirected to a upload page and i'm trying to restrict access to the upload page if you are not logged in and i don't want people to have access tot he page if they are not loggin.
So far this is my code but i don't know how to restrict access with session's.
my login script:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="ana"; // Database name
$tbl_name="user"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['user'];
$mypassword=$_POST['pass'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE user='$myusername' and pass='$mypassword'";
$result=mysql_query($sql);
// If result matched $myusername and $mypassword, table row must be 1 row
if($myusername=='ana' and $mypassword==''){
session_start();
$_SESSION["myusername"]=$myusername;
$_SESSION["mypassword"]=$mypassword;
// Register $myusername, $mypassword and redirect to file "login_success.php"
echo "Your login was succesfull!";
header("refresh:3;url=upload.php");
}
else {
echo "Wrong Username or Password, please try again.";
header("refresh:3;url=connect.php");
}
?>
and the page that redirects you to it is :
<!DOCTYPE HTML>
<!--
Astral by HTML5 UP
html5up.net | #n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<?php
session_start();
?>
<html>
<head>
<title>Ana Gemescu - Work work work | Upload </title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<!--[if lte IE 8]><script src="css/ie/html5shiv.js"></script><![endif]-->
<script src="js/jquery.min.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/init.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel.css" />
</noscript>
<!--[if lte IE 8]><link rel="stylesheet" href="css/ie/v8.css" /><![endif]-->
</head>
<body>
<!-- Wrapper-->
<div id="wrapper">
<!-- Main -->
<div id="main">
<!-- Me -->
<article id="me" class="panel">
<header>
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select image to upload:<br />
<input type="file" name="fileToUpload" id="fileToUpload"><br />
<select name="Folder" style="width:500px;margin-bottom:5px;margin-top:5px;" >
<option value="photo" style="padding:2px">Photos</option>
<option value="draw" style="padding:2px">Drawings</option>
<option value="video" style="padding:2px">Videos</option>
<option value="other" style="padding:2px">Other</option>
</select><br />
<input type="submit" value="Upload Image" name="submit">
</form>
</header>
</article>
</div>
<!-- Footer -->
<div id="footer">
<ul class="copyright">
<li>© Ana Gemescu</li><li>Design: HTML5 UP, Coded by: zapo</li>
</ul>
</div>
</div>
</body>
</html>
Can please some one help me how do i restrict access to the upload page if your not logged in ?
If you need more information please let me know
Check for the $_SESSION["myusername"], like this
if(ISSET($_SESSION["myusername"]))
{
//upload page code
}
else
{
print "access denied";
}
Always put session_start(); at the top of your page... before any output.
Verifying whether a session variable has been set is simply:
session_start(); //at the very top of your page
if(!isset($_SESSION['your_index'])){ //for example user
//do something
//for example, send the user back to the login page
header('Location: myloginform.php'); //path to where your login form is located. Headers need to be above any output or they will produce an error and thus not work as intended (or at all even!)
exit;
}
Also make sure that you take appropriate security measures in consideration for the script that does the actual uploading of the file.
For example...
Verifying file type being uploaded, you surely don't want to let a user upload anything he/she desires to your server
Correct permissions at your upload folder (e.g. full permissions 777 is just asking for problems)
Start by calling the session_start(); method on each page you need to use it. You can avoid this by calling this method once in a baseclass which sets up your mySQL connection, of course each class that inherits the connection settings will inherit the session_start() method.
As for your authenticity check, consider the below example:
//Create a new session object that will determine when a user is authenticated.
$_SESSION['isAuthenticated'] = false;
You could possibly initialise this in the class which is called when the user successfully logs in, in that case the boolean value would switch to true on successful login.
//Your welcome page, after log-in
if( isset($_SESSION['isAuthenticated']) )
{
$_SESSION['isAuthenticated'] = true
}
On each new page you could then create a condition which checks if the value is set to true (user is authenticated)
if( !isset($_SESSION['isAuthenticated']) || $_SESSION['isAuthenticated'] == false)
{
echo "You are not authenticated to view this page, please log-in";
}
else
{
//start your HTML here
}
This rules out someone simply typing the page url into the address bar and bypassing your login logic.
When a user logs in to the system, then store a flag in a session e.g. $_SESSION['loggedin'] = 1; read out the value each call. If $_SESSION['loggedin'] == 1 then user is safe.
Thank you all for your help! I've manage to made it with session_start();.
Keep up the good work guys and thanks again.
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
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()