Sorry about the title. Didn't really know how to put it. But I'm open for suggestions so people who have a similar issue can find this topic easy.
I've made a simple login/registration script in php. The issue that I'm having is that "user messages" don't get displayed and I can't figure out what I'm doing wrong.
When I user registers he/she needs to confirm his/her email address.
Once this is done and the user login he/she should be redirected to the profile page...profile.php
But for some reason this doesn't work. Anyone knows why?
index.php
<?php
/* Main page with two forms: sign up and log in */
require 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
<?php include 'css/css.html'; ?>
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require 'login.php';
}
elseif (isset($_POST['register'])) { //user registering
require 'register.php';
}
}
?>
<body>
<div class="form">
<ul class="tab-group">
<li class="tab">Sign Up</li>
<li class="tab active">Log In</li>
</ul>
<div class="tab-content">
<div id="login">
<h1>Welcome Back!</h1>
<form action="index.php" method="post" autocomplete="off">
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" required autocomplete="off" name="email"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" required autocomplete="off" name="password"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block" name="login" />Log In</button>
</form>
</div>
<div id="signup">
<h1>Sign Up for Free</h1>
<form action="index.php" method="post" autocomplete="off">
<div class="top-row">
<div class="field-wrap">
<label>
First Name<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" name='firstname' />
</div>
<div class="field-wrap">
<label>
Last Name<span class="req">*</span>
</label>
<input type="text"required autocomplete="off" name='lastname' />
</div>
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email"required autocomplete="off" name='email' />
</div>
<div class="field-wrap">
<label>
Set A Password<span class="req">*</span>
</label>
<input type="password"required autocomplete="off" name='password'/>
</div>
<button type="submit" class="button button-block" name="register" />Register</button>
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Login.php
<?php
/* User login process, checks if user exists and password is correct */
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
if ( password_verify($_POST['password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: profile.php");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error.php");
}
}
profile.php
<?php
/* Displays user information and some useful messages */
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
}
?>
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Welcome <?= $first_name.' '.$last_name ?></title>
<?php include 'css/css.html'; ?>
</head>
<body>
<div class="form">
<h1>Welcome</h1>
<p>
<?php
// Display message about account verification link only once
if ( isset($_SESSION['message']) )
{
echo $_SESSION['message'];
// Don't annoy the user with more messages upon page refresh
unset( $_SESSION['message'] );
}
?>
</p>
<?php
// Keep reminding the user this account is not active, until they activate
if ( !$active ){
echo
'<div class="info">
Account is unverified, please confirm your email by clicking
on the email link!
</div>';
}
?>
<h2><?php echo $first_name.' '.$last_name; ?></h2>
<p><?= $email ?></p>
<button class="button button-block" name="logout"/>Log Out</button>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
error.php
<?php
/* Displays all error messages */
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<?php include 'css/css.html'; ?>
</head>
<body>
<div class="form">
<h1>Error</h1>
<p>
<?php
if( isset($_SESSION['message']) AND !empty($_SESSION['message']) ):
echo $_SESSION['message'];
else:
header( "location: index.php" );
endif;
?>
</p>
<button class="button button-block"/>Home</button>
</div>
</body>
</html>
Use ob_start(); before outputting anything on your script. It looks like you become a victim of filled up output jars.
<?php
ob_start();
//Make sure you use ob_start() before any outputting anything.
//Rest of your code
?>
Suggestions: As mentioned in the comment too Please define a type of login button like type="submit" and last thing escape_string() won't save you from sql injection. Either use PDO or Prepared statement.
Related
Trying to make a login form become hidden once a successful login has happened within the form, so that the form cannot be seen by the user once they are logged in, but I still need a success message to be displayed when a successful login has happened.
I have the form and the login sorted and it displayed a success message when a successful login has been made but I cant hide the form upon successful login.
i have an if statement set up using isset but that's as far as I got I don't know what needs to go inside the if statement for me to hide the form.
This is the PHP code for my login page -
<?php
require('includes/application_top.php');
$page_title='Login!';
if (isset($_POST['action'])) {
$username_input = $_POST['username'];
$password_input = $_POST['password'];
$login_ok = login($username_input, $password_input);
}
require('includes/site_header.php');
?>
<style>
<?php
require('css/login.css');
?>
</style>
<br>
<br>
<br>
<?php
if (isset($login_ok)) {
?>
<div class="row">
<div class="col-sm-12">
<?php
if ( ! $login_ok) {
?>
<div class="alert alert-danger">
<p>Your credentials were invalid</p>
</div>
<?php
} else {
?>
<div class="alert alert-success">
<p>Login successful</p>
</div>
<?php
}
?>
</div>
</div>
<?php
}
?>
<!-- This is the if statement I mention -->
<?php
if !isset($login_okay){
?>
<div class="wrapper dafswInDown" hidden>
}
?>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Icon -->
<div class="fadeIn first">
<br>
<img src="images/Head1.jpg" style="height: 40%; width: 60%;" id="icon" alt="User Icon" />
<br>
<h3> Login! </h3>
</div>
<br>
<!-- Login Form -->
<form id="login_form" action="login_page.php" method="post">
<input type="text" class="fadeIn second" id="username" name="username" placeholder="Username" value="<?= isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '' ?>" maxlength="100" />
<input type="password" class="form-control" id="password" name="password" placeholder="Password" value="" />
<input type="submit" class="fadeIn fourth" name="action" value="Login"/>
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" href="#">Forgot Password?</a>
</div>
</div>
</div>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>
There are a number of different ways you can approach this problem, but i think the best way to do this is with a session variable. Make your login function create a session variable that will follow the logged in user around throughout the website, then its just a matter of checking for the value and either displaying or hiding the form based on that. Here is a simplified example:
<?php function login($username_input=false, $password_input=false){
// Do all your verification here
// If logged in then:
session_start();
$_SESSION["user"] = true;
}
// Then on the form side just do this:
if(!$_SESSION["user"]){ ?>
FORM HERE
<?php } ?>
I wrote a code when a user clicks "delete" but it doesn't delete the account, only logs out, I tried searching on internet but nothing was found that helped me.
Here's the code:
<?php include('server.php');
session_start();
if (isset($_GET['delete'])) {
$query = "DELETE FROM `users` WHERE `username` = '$username', `password`='$password'";
mysqli_query($db, $query);
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['money']);
header("location: login.php");
}
?>
Is there any solutions to this code? should I use AND instead of comma, because it didn't work that way, maybe there's an mistake.
$query has the same code that was used on phpmyadmin and it was successful there.
Sorry about the server.php
Here is the code of it:
Also using md5 for encrypting passwords is not good idea, I probably need to change it.
Here is login.php where the first code came from (the register button is not programmed properly):
<?php include('server.php');
session_start();
if (isset($_GET['delete'])) {
$stmt = $db->prepare('DELETE FROM users WHERE username = ? AND password = ?');
$stmt->bind_param('ss', $_SESSION['username'], $_SESSION['password']); // 's' specifies the variable type => 'string'
$stmt->execute();
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['money']);
header("location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
function register() {
header("location: register.php");
}
</script>
</head>
<body>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
<form method="post" action="login.php" align="center">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" >
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password">
</div>
<br/>
<div class="input-group">
<button type="submit" class="btn" name="login_user">Login</button>
</div>
<p></p></br>
<p>
<small class="input-group"> Not yet a member? </small> <button type="button" class="btn2" onclick="register()" name="register">Register</button>
</p>
</form>
</body>
</html>
This is register.php:
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
</br></br></br></br></br></br></br>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
This is errors.php:
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
This is index.php:
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['money']);
header("location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="content">
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<p>Welcome <strong><?php echo $_SESSION['username']; ?></strong></p>
<p> logout </p>
<p> delete </p>
<?php endif ?>
</div>
</body>
</html>
Without knowing what the content of server.php is, I can see a few error. First, your code is vulnerable for SQL Injections. There are several topics about this on SO, rather read that one here.
Starting with your code - $db,$username, $password are undefined. Guessing from the next lines, it has to be $_SESSION['username'] and $_SESSION['password'] instead.
Also, the SQL doesn't look valid to me, but that's one thing I am not sure about - according to my brain it should be
$stmt = $db->prepare('DELETE FROM users WHERE username = ? AND password = ?');
$stmt->bind_param('ss', $_SESSION['username'], $_SESSION['password']); // 's' specifies the variable type => 'string'
$stmt->execute();
Also I hope you don't store passwords in plaintext.
I am working on a verification for my sign in using php for a side project. Right now I have one user which is the admin and the password is just 123. If the user enter the wrong password or username, it will throw a message saying Wrong Password or Wrong Username. At the moment it doesn't do either and I am trying to figure out why. I will post the html and php down below.
Update: I have added the method = post. Not sure where to go from here.
<?php
$uname = $_POST['uname'];
$passwd = $_POST['psw'];
$error = "";
$success ="";
if(isset($_POST['submit'])){
if($uname == 'admin'){
if($passwd == '123'){
$error = "";
$success = "Welcome Admin";
}
else{
$error = " Wrong Password!!";
$success = "";
}
}
else{
$error = " Wrong Username!";
$success = "";
}
}
?>
<html lang="en">
<head>
<title>Hangman Home Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-
width, initial-scale=1">
<link rel="stylesheet" type="text/css"
href="home.css">
</head>
<body>
<div class="header">
<div class="a">Hangman</div>
<br>
<br>
<br>
<!--column start here -->
<div class="hi">
<table id="leader">
<tr>
<th><img src="crown.gif"></th>
</tr>
<tr>
<td>Leader Board</td>
</tr>
<tr>
<td>1st. John : 4 guess</td>
</tr>
<tr>
<td>2nd. Smith : 6 Guesses</td>
</tr>
<tr>
<td>3rd. Tom : 7 Guesses</td>
</tr>
<tr>
<td>4th. Allen : 8 Guesses</td>
</tr>
</table>
</div>
<!-- form start here -->
<br><br>
<div class="b">Think You Can Beat #1 ?</div>
<center><button
onclick=
"document.getElementById('id01').
style.display='block'"
style="width:auto;">Play Now!!!
</button></center>
<div id="id01" class="modal">
<form class="modal-content animate" action="/action_page.php">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="hang1.gif" alt="logo" class="avatar">
</div>
<div class="container">
<p class="error">
<?php echo 'error'; ?>
</p>
<p class="success">
<?php echo 'success'; ?>
</p>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
There's some mistakes at your script. First, let's check your form:
<form action="/action_page.php">
<input type="text" placeholder="Enter Username" name="uname" required>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<input type="checkbox" checked="checked" name="remember"> Remember me
</form>
This code when filled and submitted, will result at those variables at your PHP script:
$_GET["uname"], $_GET["psw"] and $_GET["remember"].
You're trying to reach the data using $_POST, but this will happen only when you add the attribute method="post" at your <form> tag.
You can also reach the mixed $_GET and $_POST arrays using $_REQUEST.
Another mistake it's the way you check if data has been submitted at the top of the code. There's no variable $_POST["submit"] (neither $_GET["submit"] or $_REQUEST["submit"]), because there's no variable with this name at the form, and you're probably thinking about submit button. To check if the form was submitted, the best way is to check if the username and password was not empty.
Also, you're echoing 'error' and 'success' at the form, and you're probably trying to echo the result of $error and $success.
Cause you don't display either the error message or the success message. Here a code that should resolve your problem:
..............
<!-- in your form tag add attribute method="POST" -->
<!-- Your code -->
<!-- in your div class="container"> -->
<?php if($success) { ?>
<p class="success"><?php echo $success; ?></p>
<?php } else if ($error) { ?>
<p class="error">
<?php echo $error; ?>
</p>
<!-- Your code -->
Happy coding ;)
you are echoing a string called success and error <?php echo 'success'; ?> what you should do is to echo the variables:
<?php echo $error; ?>
and:
<?php echo $success; ?>
I am very new at php and I'm trying to create a login div on the right side bar. Well it's seems to work but when I login it shows me:
user name [ textbox ]
password [ textbox ]
[ login button ]
welcome new2
Obviously, I'm not intrested of showing the textboxing and the login button because the user is already login.
Here is the code of the home page (templat.php):
<?php
session_start();
$db=mysqli_connect("localhost","root","","mydb");
?>
<!DOCTYPE html>
<html lang="he">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo $title; ?></title>
<link rel="stylesheet" type="text/css" href="Styles/Stylesheet2.css" />
</head>
<body dir="rtl">
<div id="wrapper">
<div id="banner">
</div>
<nav id="navigation" dir="rtl">
<ul id="nav">
<li>home</li>
<li>topics</li>
<li>on us</li>
</ul>
</nav>
<!--
<div id="content_area">
<?php
//echo $content; ?>
</div>
-->
<div id="sidebar">
<div id="main-wrapper">
<center><h2>Login Form</h2></center>
<div class="imgcontainer">
<center>
<img src="images/avatar.png" width='60' height='60' alt="Avatar" class="avatar">
</center>
</div>
<form action="Template.php" method="post">
<div class="inner_container">
<label><b>Username</b></label>
<br/>
<input type="text" placeholder="Enter Username" name="username" required>
<br/>
<label><b>Password</b></label>
<br/>
<input type="password" placeholder="Enter Password" name="password" required>
<br/>
<button class="login_button" name="login"
type="submit">Login</button>
</div>
</form>
<?php
if(isset($_POST['login']))
{
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password=md5($password); //Remember we hashed password before storing last time
$sql="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($db,$sql);
$row = mysqli_fetch_array($result);
$num = mysqli_num_rows($result);
if($num==1)
{
$_SESSION['message']="You are now Loggged In";
$_SESSION['username']=$username;
$id=$row['id'];
$_SESSION['id']=$id;
?>
<div id="main-wrapper">
<center><h3>Welcome <?php echo $_SESSION['username']; ?></h3></center>
<form action="Template.php" method="post">
<div class="imgcontainer">
<img src="images/avatar.png" alt="Avatar" width='60' height='60' class="avatar">
</div>
<div class="inner_container">
<button class="logout_button" type="submit">Log Out</button>
</div>
</form>
</div>
<?php
}
else
{
$_SESSION['message']="Username and Password combiation incorrect";
}
}
?>
</br>
</div>
</div>
<footer>
<p>aaa</p>
</footer>
</div>
</body>
</html>
update : logout.php:
<?php
session_start();
session_destroy();
unset($_SESSION['username']);
$_SESSION['message']="You are now logged out";
header("Location:login.php");
?>
You need to check if user is already logged in. You can check if $_SESSION['username'] is empty or not.
Update your login form like that:
<?php if(!isset($_SESSION['username'])) { ?>
<form action="Template.php" method="post">
<div class="inner_container">
<label><b>Username</b></label>
<br/>
<input type="text" placeholder="Enter Username" name="username" required>
<br/>
<label><b>Password</b></label>
<br/>
<input type="password" placeholder="Enter Password" name="password" required>
<br/>
<button class="login_button" name="login"
type="submit">Login
</button>
</div>
</form>
<?php }; ?>
Okay, So I have this log in page here all I want it to do is log me in and send me too "index.php". I know my email is correct and the password and everything is good. it all works it just stays on the same page though instead of actually sending me to "index.php". Im new to php and it is probably something stupid but any help would be greatly appreciated. Please and Thank you! :)
<link rel="stylesheet" href="styles.css" />
<?php
session_start();
if(isset($_SESSION['usr_id'])!="") {
header("Location: index.php");
}
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
header("Location: index.php");
$successmsg = "SWEET YOU'RE IN!";
//echo "success";
} else {
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Login Script</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<div class="container-fluid">
<!-- add header -->
<div class="navbar-header">
</div>
<!-- menu items -->
<div class="collapse navbar-collapse" id="navbar1">
<ul class="navbar">
<li class="active">Login</li>
<li>Sign Up</li>
</ul>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 well">
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
<fieldset>
<legend>Login</legend>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Your Email" required class="form-control" />
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Your Password" required class="form-control" />
</div>
<div class="form-group">
<input type="submit" name="login" value="Login" class="btn btn-primary" />
</div>
</fieldset>
</form>
<span class="text-danger"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
<span class="text-success"><?php if (isset($successmsg)) { echo $successmsg; } ?></span>
</div>
</div>
</div>
</body>
</html>
Where you have this:
if(isset($_SESSION['usr_id'])!="") {
You want this:
if(isset($_SESSION['usr_id']) && $_SESSION['usr_id'] != "") {
Note that what's in $_SESSION['usr_id'] will be the id column from your database. It's not clear from context if such a column exists, so perhaps double check that there really is a value there before the initial redirect (i.e., just after checking the credentials).
Side note: don't use MD5() to hash passwords. MD5 isn't as secure as you'd want a password hash to be.