Add validation for empty inputs to current PHP Login form - php

I currently have a form that checks if the username and password exist and logs you and redirects you to the homepage. However if you leave the email and password section blank, you also are able to log into the site. I'm looking to add some sort of validation to avoid someone from just using empty input variables.
This is what I have...
<?php
session_start();
include_once 'config.php';
$email ="";
$userpassword ="";
$errors = 0;
$emailError ="";
$passwordError ="";
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
if(isset($_POST['loginBtn']))
{
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if(!empty($_POST["password"])) {
$passwordError = "Please enter a Password";
$errors = 1;
}
$email = mysql_real_escape_string($_POST['email']);
$userpassword = mysql_real_escape_string($_POST['password']);
$result=mysql_query("SELECT * FROM users WHERE emailAddress='$email'");
$row=mysql_fetch_array($result);
if($row['password']==md5($userpassword))
{
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
}
else
{
?>
<script>alert('First time visitors, please create an account to play'); </script>
<?php
}
}
?>

Client Side validation such as JavaScript and HTML5 can be turned off or directly edited via the browser. Always use server side validation as the final authority.
Also, When checking login credentials you need to do a combination check in the where clause.
WHERE username ='$u_user' AND password = '$u_pass'
This is especially the case when allowing the reuse of controlling columns (username, email). Passwords are not always unique.
In the OP's case the lookup on the email only could return multiple results.
<?php
session_start();
include_once('config.php');
IF (isset($_SESSION['user'])!="") { header("Location: home.php"); }
IF (isset($_POST['loginBtn'])) { // the form was submitted
$err = ""; // default error as empty
$email= trim($_POST['email']);
$password = trim($_POST['password']);
// validation
IF (empty($email)) { $err .= "Email is empty<br>";
}ELSE{
IF (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err .= "Email is not valid<br>";
}
}
IF (empty($password)) { $err .= "Password is empty<br>"; }
IF (!empty($err)) {
// there are errors
echo("<p>".$err."</p>");
}ELSE{
// No errors
$uemail = mysql_real_escape_string($email);
$upass = mysql_real_escape_string(md5($password));
$result = mysql_query("SELECT * FROM users WHERE emailAddress='$uemail' && password = '$upass'");
IF ($result) {
// set session
$row = mysql_fetch_array($result);
$_SESSION['user'] = $row['user_id'];
}ELSE{
echo("<p>Email address and or your password was incorrect.<br>If you do not have an account please create one.</p>");
}
// Close DB connection
mysql_close($Your_db_connection);
// redirect if session is set
IF (isset($_SESSION['user'])) { header("Location: home.php"); }
}
}ELSE{
// form not submitted
}
?>

You can use html5 validation for login form use required attributes for blank input field validation this validation is very easy and user friendly please use this way

Related

header function not redirecting to home.php, why?

Here i am using header function to redirect to home.php after login, but header function is not redirecting to that page. Even when i run same code on my local computer it works fine.
<?php
ob_start();
session_start();
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
$error = false;
if( isset($_POST['btn-logIn']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['password']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$errMsg = "Please enter valid email address.";
}
// if there's no error, continue to login
if (!$error) {
$res=mysql_query("SELECT userId, userfName, userlName,userPassword FROM userdata WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPassword']==$pass ) {
$_SESSION['user'] = $row['userId'];
header("Location:home.php");
} else {
$errMsg = "Try again...";
}
}
}
?>
You do not need the !="" on line 5 because isset() already checks for existence. Either its there or its not.
if (isset($_SESSION['user'])){
header("Location: home.php");
exit;
} else {
echo "something here";
}
You can use !isset() to get the opposite result as well.
Try your code with this code,
<?php
ob_start();
session_start();
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
?>

PHP can't determine whether user is logged in or not

I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
echo "Login!";
} else {
echo "Welcome!";
}
?>
is the code that checks if the user is logged in or not.
My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userEmail, userPass FROM users WHERE
userName='$name'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be
1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.
I've spent a long-while trying to figure this out, and can't.
Thanks!
In your code
if ( isset($_SESSION['user'])!="" ) {
you are comparing true|false != ""
change it to if (isset($_SESSION['user'])) {
or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {

How to redirect to different page after form is submitted using header()?

I've looked at lots of answers to redirect to a different page after submitting a form, but haven't been able to get it to work thus far, probably because I have no idea where to actually put the code. Can anyone help? The rest of this code is working fine, i just need to know where to place header():
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connects to database, checks username & password against database to see is user exists
if($username && $password)
{
include ("connect.php");
$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 and password are correct
if($username==$dbusername&&md5($password)==$dbpassword)
{
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
}
//if password is incorrect
else
echo "Your password is incorrect.";
}
//if username is incorrect
else
die("Username does not exist.");
}
//if no information is submitted
else
die("Please enter your login details.");
//prevents errors from displaying on page
error_reporting(0);
?>
I also need to know where it goes for this page:
<?php
//Check if register button was pressed
$button = $_POST['button'];
//if button was pressed,
if ($button)
{
//get data from form,
$username = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
}
//check if all information has been entered,
if ($username && $password && $retype_password && $first_name && $last_name)
{
//check if password and retype_password are the same
if($password==$retype_password)
{
//check if username already exists
include("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows == 0)
{
//encrypt password
$password = md5($password);
//sends data from form to database - creates new user
$register = mysql_query("INSERT INTO users VALUES ('', '$username', '$password', '$first_name', '$last_name')");
echo "You are now registered. <a href='main.php'>Continue to site.</a>";
}
else
echo "Username is unavailable.";
}
else
echo "Password did not match.";
}
//prevents errors from displaying on page
error_reporting(0);
?>
Thanks in advance!
if($username==$dbusername&&md5($password)==$dbpassword)
{
$_SESSION['username'] = $username;
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
You should put it once the job is done : that is after
//echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Don't forget the "exit" or what follow will be executed.
That said, you cannot echo something before a doing redirection, that's logical because the echo can't be seen.
So, either you do not echo :
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Or you do a HTML (or javascript) redirection, with a 5 seconds delay:
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
exit;
In which case you have to put it in the < head > section, to do the HTML redirection:
<meta http-equiv="refresh" content="0; url=http://example.com/main.php" />
Also
error_reporting(0);
Should be put at the beginning of the page, unless you want errors for previous lines to be shown.
BUT : error_reporting(0); should NEVER be used on a development site (and always on a production site).
You should turn on display_errors('on') and error_reporting(E_ALL) to see errors - errors are very useful for a developer.

mysql check account type to see if admin on login

hi in my script i have it logging in users , but i want to have the script also check if the user is an admin by seeing if the account_type is a,b,c account type "c" is the admin and i would like it to redirect the admin to the admin page ...
<?php // Start Session to enable creating the session variables below when they log in
// Force script errors and warnings to show on page in case php.ini file is set to not display them
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("security/checkuserlog.php");
if (isset($_SESSION['idx'])) {
echo '<script language="Javascript">';
echo 'window.location="home.php"';
echo '</script>';
}
//-----------------------------------------------------------------------------------------------------------------------------------
// Initialize some vars
$errorMsg = '';
$username = '';
$pass = '';
$remember = '';
if (isset($_POST['username'])) {
$username = $_POST['username'];
$pass = $_POST['pass'];
if (isset($_POST['remember'])) {
$remember = $_POST['remember'];
}
$username = stripslashes($username);
$pass = stripslashes($pass);
$username = strip_tags($username);
$pass = strip_tags($pass);
// error handling conditional checks go here
if ((!$username) || (!$pass)) {
$errorMsg = '<font color="red">Please fill in both fields</font>';
} else { // Error handling is complete so process the info if no errors
include 'connect_to_mysql.php'; // Connect to the database
$username = mysql_real_escape_string($username); // After we connect, we secure the string before adding to query
//$pass = mysql_real_escape_string($pass); // After we connect, we secure the string before adding to query
$pass = md5($pass); // Add MD5 Hash to the password variable they supplied after filtering it
// Make the SQL query
$sql = mysql_query("SELECT * FROM members WHERE username='$username' AND password='$pass'");
$login_check = mysql_num_rows($sql);
// If login check number is greater than 0 (meaning they do exist and are activated)
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
// Create session var for their raw id
$id = $row["id"];
$_SESSION['id'] = $id;
// Create the idx session var
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$id");
$username = $row["username"];
$_SESSION['username'] = $username;
} // close while
// Remember Me Section
// All good they are logged in, send them to homepage then exit script
header("location: home.php");
exit();
} else { // Run this code if login_check is equal to 0 meaning they do not exist
$errorMsg = '<font color="red">The Username And Password did not match.</font>';
}
} // Close else after error checks
} //Close if (isset ($_POST['uname'])){
?>
if ($row["account_type"] == "c") { header("Location: admin.php"); }; in your while loop should do it.
This will basically set the "Location" header to "admin.php" or whatever admin page you want, however don't forget to check in your admin page if the user is actually logged in, to avoid users simply going manually to "admin.php" and bypassing the permission check.
$account_type= $row["account_type"];
$_SESSION['account_type'] = $account_type;
then change header("location: home.php"); into
if($account_type=='admin')
{
header("location: adminpanel.php");
}
else
{
header("location: home.php");
}

Log in returns blank for incorrect password?

I have been using a tutorial for a registration and log in page. Everything is perfect except when a user inputs an incorrect password.
If no password is entered then the stated error is displayed fine.
If the correct password is entered it logs them in.
If the incorrect password is entered it goes to a blank page?!
I want an incorrect password to display a message just like when the wrong username is entered. I've included my entire login.php code:
include('db.php');
if(!isset($_POST['login'])) {
include('form.php');
} else {
if(isset($_POST['user'])&&$_POST['user']==""||!isset($_POST['user'])) {
$error[] = "Username Field can't be left blank";
$usererror = "1";
}
if(!isset($usererror)) {
$user = mysql_real_escape_string($_POST['user']);
$sql = "SELECT * FROM users WHERE user = '$user'";
if(mysql_num_rows(mysql_query($sql))=="0") {
$error[] = "Can't find a user with this username";
}
}
if(isset($_POST['pass'])&&$_POST['pass']==""||!isset($_POST['pass'])) {
$error[] = "password Field can't be left blank";
}
if(isset($error)) {
if(is_array($error)) {
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('form.php');
}
}
if(!isset($error)) {
$suser=mysql_real_escape_string($_POST['user']);
$spass=md5($_POST['pass']);//for secure passwords
$find = "SELECT * FROM users WHERE user = '$suser' AND password = '$spass'";
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())) {
session_start();
$_SESSION['username'] = $suser;
header("Location: loggedin.php");
} else {
echo "<div class=\"warning\"><span>Some Error occured durring processing your data</div>";
}
}
}
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())){
If wrong password is entered, mysql_num_rows(mysql_query($find)) is 0 so it results in die(mysql_error()). But since there is no mysql_error(), you see a blank page.
Try this
$result = mysql_query($find) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
// proceed
} else {
// authentication failed
}
EDIT: This is just for illustration purpose only. Use MySQLi or PDO when dealing with MySQL.
The code is little bit confusing for me, consider using this code.
<?php
include('db.php');
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['user']);
$password = md5($_POST['pass']);
if(empty($username) || empty($password)) {
echo "Empty username or password.";
} else {
mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `password.md5` = '$password'");
if(mysql_num_rows() == 1) {
// login successfull
session_start();
$_SESSION['username'] = $username;
header("Location: loggedin.php");
} else {
echo "Invalid username or password.";
}
}
} else {
include ('form.php');
}
?>

Categories