PHP Form Validation: Whats wrong with my code? - php

I am currently learning to validate forms in PHP and parts of my code aren't producing the desired output. I'd want the code to print out Username cant be blank when the user submits the form without a username and Password cant be blank when the password field is left blank while submitting. i have marked out, with the help of comments, the lines of code that were meant to achieve this goal (refer: //DOESNT WORK). Currently, the code is successfully able to display to the user Username/Password dont match. I am running the php scripts on XAMPP. My code:
form_with_validation.php
<?php
require_once("included_functions.php");
require_once("validation_functions.php");
$errors = array();
$message = "";
if(isset($_POST['submit']))
{ //form was submitted
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
//Validations
$fields_required = array("username", "password");
foreach($fields_required as $field) //DOESNT WORK
{
$value = trim($_POST[$field]);
if(!has_presence($value))
{
$errors[$field] = ucfirst($field) . " cant be blank.";
}
}
if(empty($errors))
{
//try to login
if($username == "mickey" && $password == "password")
{ //successful login
redirect_to("basic.html");
}
else
{
$message = "Username/Password dont match.";
}
}
}
else {
$username = "";
$message = "Please Log in.";
}
?>
<html lang = "en">
<head>
<title>Form</title>
</head>
<body>
<?php echo $message; ?> <br>
<?php echo form_errors($errors);?>
<form action="form_with_validation.php" method = "post">
Username: <input type="text" name="username" value="<?php echo htmlspecialchars($username)?>" /><br>
Password: <input type="password" name="password" value=""/><br>
<br>
<input type="submit" name= "submit" value="Submit" />
</form>
</body>
validation_functions.php
<?php
//presence
function has_presence($value)
{
return isset($value) || $value !== "";
}
//string length
//max length
function has_max_length($value, $max)
{
return strlen($value) <= $max;
}
//inclusion in a set
function has_inclusion_in($value, $set)
{
return in_array($value, $set);
}
function form_errors($errors=array())
{
$output = "";
if(!empty($errors))
{
$output .= "<div class=\"error\">";
$output .= "Please fix the following errors:"; //NOT WORKING
$output .= "<ul>";
foreach($errors as $key => $error)
{
$output .= "<li>{$error}<li>";
}
$output = "</ul>";
$output .= "</div>";
}
return $output;
}
?>
included_functions.php
{
return "Hello {$name}!";
}
function redirect_to($new_location)
{
header("Location: " . $new_location);
exit;
}
?>

Just add it:
change
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
for:
if(isset($username)){
$username = trim($_POST["username"]);
}else{
die("Username cant be blank");
}
if(isset($password)){
$password = trim($_POST["password"]);
}else{
die("password cant be blank");
}
You can change die() will stop php execution, you can just print and manage that error otherwise.

Related

My PHP code is telling me that my username is undefined on line 12, but I though I had it defined

I am struggling to understand why my code is telling me that my username is undefined whenever I try to load up this page. the error is Notice: Undefined index: username in /home/jmask072/public_html/login.php on line 12. Any help is appreciated. How would I go about defining it if I didn't define it?
<?php
$users = array("user" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi');
$isLoggedIn = false;
$errors = array();
$required = array("username", "pass");
foreach ($required as $key => $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$errors[] = "please fill out the form";
}
}
if (array_key_exists($_POST['username'],$users)) {
$userPassword = $_POST['pass'];
$dbPass = $users[$_POST['username']];
if (password_verify($userPassword,$dbPass) === true) {
$isLoggedIn = true;
} else {
$isLoggedIn = false;
$errors[] = "Username not found or password incorrect";
}
} else {
$errors[] = "Username not found or password incorrect";
}
require_once("Template.php");
$page = new Template("My Login");
$page->addHeadElement("<link rel=\"stylesheet\" href=\"styles.css\">");
$page->addHeadElement("<script src='hello.js'></script>");
$page->finalizeTopSection();
$page->finalizeBottomSection();
print $page->getTopSection();
if (count($errors) > 0) {
foreach ($errors as $error) {
print "Error";
}
}
else if ($isLoggedIn === true) {
print "Hello, you are logged in";
}
print "<form action =\"login_action.php\" method =\"POST\" class=\"form-signin\">";
print "<h1>Please sign in</h1>\n";
print "<label for=\"inputUser\">Username</label>";
print "<input type=\"password\" name=\"pass\" id=\"inputPassword\" placeholder=\"password\">";
print "<button type=\"submit\"> Sign in</button>";
print $page->getBottomSection();
?>
The issues here is you're accessing the $_POST variables on a GET request, the values you're looking for won't be set since the form hasn't been filled out and sent to the server yet, you also don't have an input for the user to input their name yet you're trying to access it with $_POST['username'].
You'll have to check whether the request is a POST or a GET before you try to access variables - because they might not exist yet, and also add an input for the username to it's accessible when posted.
<?php
$errors = array();
$isLoggedIn = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$users = array("user" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi');
$required = array("username", "pass");
foreach ($required as $key => $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$errors[] = "please fill out the form";
}
}
if (array_key_exists($_POST['username'], $users)) {
$userPassword = $_POST['pass'];
$dbPass = $users[$_POST['username']];
if (password_verify($userPassword, $dbPass)) {
$isLoggedIn = true;
} else {
$isLoggedIn = false;
$errors[] = "Username not found or password incorrect";
}
} else {
$errors[] = "Username not found or password incorrect";
}
}
require_once("Template.php");
$page = new Template("My Login");
$page->addHeadElement("<link rel=\"stylesheet\" href=\"styles.css\">");
$page->addHeadElement("<script src='hello.js'></script>");
$page->finalizeTopSection();
$page->finalizeBottomSection();
print $page->getTopSection();
if (count($errors) > 0) {
foreach ($errors as $error) {
print "$error<br/>" . PHP_EOL;
}
} else if ($isLoggedIn === true) {
print "Hello, you are logged in";
}
?>
<form action="login_action.php" method="POST" class="form-signin">
<h1>Please sign in</h1>
<label for="inputUser">Username</label>
<input type="text" name="username" id="inputUser">
<label for="inputPassword">Password</label>
<input type="password" name="pass" id="inputPassword">
<button type="submit">Sign In</button>
</form>
<?php print $page->getBottomSection(); ?>
The name attribute on inputs is the key that will later be used as the key for accessing the given value on the $_POST array. This $_POST variable array is also only populated in a POST request as stated in the documentation.
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.¹
PHP Manual: Predefined Variables: $_POST ¹

PHP Login Page Always Returning Incorrect Username and Password

I have a basic login page that takes user inputted username and password and checks the entered details against an XML document with user details.
The problem is, even if the username and password are correct the PHP document is still displaying that the credentials are incorrect.
Thanks
<?php
if(isset($_GET['login'])) {
$id = "";
$errors = "";
$dom = DomDocument::load('../../data/customer.xml');
if(empty($_GET['email'])) {
$errors .= "Email field cannot be empty <br />";
}
else {
$inputEmail = $_GET['email'];
}
if(empty($_GET['password'])) {
$errors .= "Password field cannot be empty <br />";
}
else {
$inputPassword = $_GET['password'];
}
if(isset($inputEmail) && isset($inputPassword)) {
$email = $dom->getElementsByTagName('email');
$password = $dom->getElementsByTagName('password');
for($i = 0; $i < $email->length; $i++) {
if($inputEmail == $email->item($i)->textContent && $inputPassword == $pwd->item($i)->textContent) {
$id = $dom->getElementsByTagName("id")->item($i)->textContent;
break;
}
}
}
if($id == "") {
$errors .= "Incorrect username or password";
}
if($errors == "" ) {
echo true;
}
else {
echo $errors;
}
}
?>
As requested, here an example of the XML:
<customers>
<details>
<firstname>Example</firstname>
<lastname>Example</lastname>
<email>example#email.com</email>
<id>1</id>
<password>cb750e88</password>
</details>
</customers>
You are Taking $pwd variable instead of $password :
if($inputEmail == $email->item($i)->textContent && $inputPassword == $pwd->item($i)->textContent) {
Replace It :
if($inputEmail == $email->item($i)->textContent && $inputPassword == $password->item($i)->textContent) {

page getting redirected to wrong page

I have a simple login form that allows a user to login, although the form is working fine, but there is one condition where i wish to redirect it to someother page, instead of regular index page.
piece of code where i am facing issue is
if($spid=="")
{
header('Location:index.php');
}
else
{
header('Location:new.php?id=$spid');
}
the issue is even if the $spid has a value it is getting redirected to index.php page. can anyone please tell why this is happening
the whole code from which the above code has been extracted is
<?php
$spid=$_GET['spid'];
$emailErr = $pswrdErr = $loginErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}
else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"])) {
$pswrdErr = "password is required";
}
else {
$password = test_input($_POST["password"]);
}
$sql = "SELECT * FROM usertable where email='".$email."' and password='".$password."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
if($spid=="")
{
header('Location:index.php');
}
else
{
header('Location:new.php?id=$spid');
}
}
}
else {
$loginErr = "Invalid Credentials";
}
}
function test_input($data) {
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" role="form">
<input type="text" class="form-control" name="email">
<input type="password" class="form-control" name="password">
</form>
As you said you are getting value in $spid=$_GET['spid']; So instead of following above mentioned method take your $spid as hidden i/p text inside form and then pass it in your code as
$finalspid=$_POST["spid"]
and then put your if else condition according to $finalspid
Try this:
if(!isset($spid) && $spid==''){
header('Location:index.php');
} else {
header("Location:new.php?id=".$spid);
}

log in script working on dev server but not live

Okay, on my local dev server I can login with my simple form on index.php. it will redirect me to admin.php because my username and password has matched that in the database.
However when I upload this to my live server it doesn't work. I don't understand. To create the username and password in the database I use new_admin.php. Then using index.php i login which willa cces my functions from functions.php.
functions.php:
//*****************************************************************/
//mysql_prep();
//
function mysql_prep($string) {
global $connection;
$escaped_string = mysqli_real_escape_string($connection, $string);
return $escaped_string;
}
//*****************************************************************/
//confirm_query();
//
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
//////////////LOG IN FUNCTIONS
/////////////////////////////////////////////////////////////////////////
//*****************************************************************/
//password_encrypt();
//
function password_encrypt($password) {
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22; // Blowfish salts should be 22-characters or more
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
//*****************************************************************/
//generate_salt();
//
function generate_salt($length) {
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
//*****************************************************************/
//password_check();
//
function password_check($password, $existing_hash) {
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
//*****************************************************************/
//find_admin_by_username();
//
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM admins ";
$query .= "WHERE username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
//*****************************************************************/
//attempt_login();
//
function attempt_login($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["hashed_password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
//*****************************************************************/
//logged_in();
//
function logged_in() {
return isset($_SESSION['admin_id']);
}
//*****************************************************************/
//confirm_logged_in();
//
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("index.php");
}
}
new_admin.php:
<?php
session_start();
require_once("includes/db_connection.php");
require_once("includes/functions.php");
?>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$username = mysql_prep($_POST["username"]);
$hashed_password = password_encrypt($_POST["password"]);
$query = "INSERT INTO admins (";
$query .= " username, hashed_password";
$query .= ") VALUES (";
$query .= " '{$username}', '{$hashed_password}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Admin created.";
redirect_to("admin.php");
} else {
// Failure
$_SESSION["message"] = "Admin creation failed.";
}
}
?>
<form action="new_admin.php" method="post">
username:
<input type="text" name="username"/><br/>
password:
<input type="password" name="password"/></br>
<input type="submit" name="submit"/>
</form>
index.php:
<?php
session_start();
require_once("includes/db_connection.php");
require_once("includes/functions.php");
?>
<?php
$username = "";
if (isset($_POST['submit'])) {
// Process the form
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login($username, $password);
if ($found_admin) {
// Success
// Mark user as logged in
$_SESSION["admin_id"] = $found_admin["id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
} else {
// Failure
$_SESSION["message"] = "Username/password not found.";
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<?php
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
}
?>
<h1>Login</h1>
<form action="index.php" method="post">
<p>Username:
<input type="text" name="username" value="" />
</p>
<p>Password:
<input type="password" name="password" value="" />
</p>
<input type="submit" name="submit" value="Submit" />
</form>
I know that i am putting in the correct login username and password but all i get is "Username/password not found." from my session error message.
Any ideas why this is happening?
EDIT:
Ive just noticed that i am not getting the error "Username/password not found" So this means that my attempt_login() function must be returning true. doesnt it?

AJAX Login Form - Clicking submit doesn't work

I'm trying to create my own login form, having a few difficulties though.
I want to have a form where the user can log into the website, using AJAX:
If user doesn't enter username, show message
If user doesn't enter password, show message
Check with database if password is correct, if incorrect, show message
The problem is, I've done a little jQuery and next to no AJAX before. I'm trying to learn but haven't had any luck so far! My PHP/PDO script works fine without any AJAX/jQuery and checks all the requirements fine.
My code so far is below:
index.html
$(document).ready(function(){
$("#add_err").css('display', 'none', 'important');
$("#login-submit").click(function(){
username=$("#username").val();
password=$("#password").val();
if (username.length < 1)
errors = errors + "Please enter your username<br/>";
if (password.length < 1)
errors = errors + "Please enter your password<br/>";
var errors = "";
$.ajax({
type: "POST",
url: "process-login.php",
data: "username="+username+"&password="+password,
success: function(html) {
if(html=='true') {
window.location="account.php";
}
if (errors != "") {
$("add_err").html(errors).slideDown("fast");
}
}
});
return false;
});
});
</script>
<div id="login">
<form method="post" id="form" action="process-login.php">
<div class="err" id="add_err"></div>
<fieldset>
<p><input type="text" id="username" name="username" placeholder="Username"></p>
<p><input type="password" id="password" name="password" placeholder="Password"></p>
<input type="hidden" name="redirect" value="<?php echo "$redirect" ?>" />
<p><input type="submit" id="login-submit" name="submit" class="button" value="Let me in!"/></p>
<p>Not a member? Sign up now <i class="fa fa-arrow-right"></i></p>
</fieldset>
PHP
<?php
session_start();
try
{
$dbuser = "XXXXXXXXXXX";
$dbpass = "XXXXXXXXXXX";
$dbh = new PDO('mysql:host=XXXXXXXXXXX', $dbuser, $dbpass);
//Min length validation
function validateMinLength($length, $number){
//if it's NOT valid
if(strlen($length) < $number)
return false;
//if it's valid
else
return true;
}
//Max length validation
function validateMaxLength($length, $number){
//if it's NOT valid
if(strlen($length) > $number)
return false;
//if it's valid
else
return true;
}
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$password = strtoupper(hash('whirlpool', $password));
$redirect = $_POST["redirect"];
$err = array();
if(!validateMinLength($_POST['username'], 2))$err[]='The username field is too short or empty';
if(!validateMaxLength($_POST['username'], 21))$err[]='The username field must be less than 21 characters';
if(!validateMinLength($_POST['password'], 2))$err[]='The password field is too short or empty';
if(count($err)){
foreach($err as $one_er){
echo $one_er . "<br/>";
}
exit();
}
if (empty($error) === true) {
$query = $dbh->prepare("SELECT * FROM user WHERE username = ? LIMIT 1");
$query->execute(array($username));
if ($query->rowCount() > 0) {
$data = $query->fetch(PDO::FETCH_OBJ);
if ($data->password != $password)
{
$err[] = "Invalid password";
}
if(count($err)){
foreach($err as $one_er){
echo $one_er . "<br/>";
}
exit();
}
else {
$query = $dbh->prepare("SELECT * FROM user WHERE username = ? AND isadmin = '1'");
$query->bindParam(1, $username, PDO::PARAM_STR, 25);
$query->execute();
if ($query->rowCount() == 1) {
$_SESSION["admin"] = $username;
$admin = $_SESSION["admin"];
$_SESSION['start_time'] = time();
$online = $dbh->query("UPDATE user SET online=1 WHERE username='$admin'");
header('location:http://www.colorshare.co' . $redirect);
echo "Success";
} else {
$_SESSION["member"] = $username;
$member = $_SESSION["member"];
$_SESSION['start_time'] = time();
$online = $dbh->query("UPDATE user SET online=1 WHERE username='$member'");
header('location:http://www.colorshare.co' . $redirect);
echo "Success";
}
}
}
}
}
$dbh = null;
}
catch (PDOException $e)
{
print "Error: " . $e->getMessage() . "<br/>";
die();
}
?>
Is there something I'm missing or doing completely wrong?
first thing you should check if the php script returning the right values that you testing on the JS side .
then you should check this :
if(html=='true') {
window.location="account.php";
}
if (errors != "") {
$("add_err").html(errors).slideDown("fast");
}
you should make it , i think :
if(html=='true') {
window.location="account.php";
}else{
errors = html ;//when 'html' variable is not returning 'true' the its returning errors
}
if (errors != "") {
$("add_err").html(errors).slideDown("fast");
}
i hope give us more information about the problem like what it's showing when you tested it .

Categories