I have created a simple form which has some required fields which if not completed will pass back an error to the user to inform them that the field is require.
As there are multiple field which is checks it can output multiple error messages.
I want to know how I can define an area on my form where these errors are displayed as at the moment these error simply display at the bottom of the form, which you can't see unless you scroll down the page.
Can I define where my error are displayed.
Here is the error checking code: EDIT
Old code was here
People in the past have suggested I make a loop to check for errors one at a time but I am novice at php so not sure how to do this.
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br/>";
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errors .="You did not select a tutor<br/>";
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errors .="You did not enter a procedure<br/>";
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errors .="You did not enter a grade<br/>";
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errors .="You did not enter a reflection<br/>";
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errors .="You must enter a reasan why you ticked the alert box";
}
//Code to check the password field is completed and correct
if (empty($_POST['password']))
{
$errors .="You did not enter you password";
}
if (!empty($_POST['password']))
{
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$masterpass = $_POST['password'];
$masterpass = htmlspecialchars($masterpass);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "username";
$pass_word = "password";
$database = "name of database";
$server = "server";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$masterpass = quote_smart($masterpass, $db_handle);
$SQL = "SELECT * FROM masterpass WHERE password = $masterpass";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
echo "";
}
else {
$errors .= "Password was not recognised";
exit();
}
}
mysql_close($db_handle);
}
}
if(!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
exit();
}
}
You could do something like
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br />";
}
if(empty($_POST['tutorName'] ))
{
$errors .= "You did not select a tutor name.<br />";
}
// etc.
and then above your <form> have
if (!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
}
styling .errors with CSS so it'll stand out more. If $errors is blank higher up in your application logic, you can then perform the usual add / update to a database and redirect to a success page.
echo()ing your errors is what's adding them to the bottom. As the previous answer suggested, assigning them to a string and printing that in a defined div (if it's not empty) is how the pros do it!
Defining errors as an array also works, and allows you a bit more fine-grained control over the error process.
$errors = array();
if(empty($_POST['studentName']))
$errors[] = "You did not enter the student name";
if(empty($_POST['tutorName'] ))
$errors[] = "You did not select a tutor name.";
//etc...
//At the top of your page.
if (sizeof($errors)>0) {
echo "<div class='errordiv'>";
echo "<ul>";
foreach ($errors as $err) {
echo "<li>".$err."</li>"; //or whatever format you want!
}
echo "</ul></div>";
}
You can also pass the error array around as a parameter to other functions, log them, etc.
Related
I am newbie in PHP.
I have simple authentication script. It works incorrect: user "test" (100% existing in table in DB) can not pass auth (error text - "User is not found!").
Use PHP7, MySQL, connection method is PDO.
Need some help please.
$data = $_POST;
// check if button is pressed
if (isset($data['enter-auth'])) {
// check fileds
$errors = array();
if (trim($data['login_auth']) == '' ) {
$errors[] = 'Enter login';
}
if (($data['password_auth']) == '' ) {
$errors[] = 'Enter password';
}
// If all fields are filled, save user's data in vars
$login = $data['login_auth'];
$password = password_hash($data['password_auth'], PASSWORD_DEFAULT);
// ... and look in table
try {
if (empty($errors)) {
// Check if login and password exists in table
$stmt = $pdo->prepare("SELECT count(*) FROM users WHERE login=? AND password=?");
$stmt->execute([$login, $password]);
$count = $stmt->fetchColumn();
// If login and pwd found in table counter will be > 0, so ...
if ($count > 0) {
// ... then we can check if password is correct
if (password_verify($data['password_auth'], $password)) {
// if entered and stored passwords match, user is welcome
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Password is incorrect';
echo '<p id="message">Wrong password!</p>';
}
} else {
$errors[] = 'User not found';
echo '<p id="message">User is not found!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
// close condition check if button is pressed
}
Notes:
I tryed debugging this script using var_dump.
If I use fetchAll() when searching in table, any entered ldin is accepted (even if there is no such user).
Used try/catch construction with debug aim, I've heard that in production it is deprecated because of security reason.
Found mistakes, rewrote the code according to https://phpdelusions.net/pdo_examples/password_hash
So, correct fragment is:
try {
if (empty($errors)) {
$stmt = $pdo->prepare("SELECT login, password FROM users WHERE login=?");
$stmt->execute([$login]);
$user = $stmt->fetch();
if ($user && password_verify($data['password_auth'], $user['password'])) {
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Login or password error';
echo '<p id="message-auth">Login or password is incorrect!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
I'm making a registration form using PHP and mongodb. This form works but the problem is it's not carrying out the validations. Even if I leave all the fields empty, it updates the database with the empty fields. Its as if the whole error = array(); is invisible.
What I need is for it to perform the checks and not update the database until all the requirements are met.
<?php
session_start();
if($_POST['submit']){
$ScName=strip_tags($_POST['ScName']);
$fname=strip_tags($_POST['fname']);
$lname=strip_tags($_POST['lname']);
$email=strip_tags($_POST['email']);
$password=strip_tags($_POST['password']);
$password2=strip_tags($_POST['password2']);
$error = array();
if(empty($email) or !filter_var($email,FILTER_SANITIZE_EMAIL)){
$error[] = "Email id is empty or invalid";
}
if(empty($password)){
$error[] = "Please enter password";
}
if(empty($password2)){
$error[] = "Please Confirm password";
}
if($password != $password2){
$error[] = "Password and Confirm password are not matching";
}
if(empty($fname)){
$error[] = "Enter first name";
}
if(empty($lname)){
$error[] = "Enter last name";
}
if(count($error == 0)){
//database configuration
$host = 'localhost';
$database_name = 'mongo1';
$database_user_name = '';
$database_password = '';
$connection=new Mongo('localhost');
if($connection){
//connecting to database
$database=$connection->user;
//connect to specific collection
$collection=$database->user;
$query=array('email'=>$email);
//check for existing username
//$query=array('ScName'=>$ScName);
//checking for existing user
$count=$collection->findOne($query);
if(!count($count)){
//Save the New user
$user=array('fname'=>$fname,'lname'=>$lname,'ScName'=>$ScName,'email'=>$email,'password'=>md5($password));
$collection->save($user);
echo "You are successfully registered.";
}else{
echo "Email already exists.Please register with another Email";
}
}else{
die("Database is not connected");
}
}else{
//Displaying the error
foreach($error as $err){
echo $err.'</br>';
}
}
}
?>
You have misplaced the bracket at
if(count($error == 0)){
Since $error == 0 is false, as $error is a populated array, count(false) evaluates as 0 (i.e., false), and the if branch doesn't execute. You should close the bracket after $error:
if (count($error) == 0) {
I m trying a contact form in php where the details as to get stored in the database.If i dont enter any values it displays error msg but it gets stored in the database. How can I validate form when error message displays the data should not be entered in database.
Here is the code
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
} else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
} else {
$error .= "You didn't type your Mobile Number. <br />";
}
if (empty($error)) {
$success = "<b>Thank you! Your message has been sent!</b>";
}
}
?>
<div id="contactForm">
<?php
if (!empty($error)) {
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile)
VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
This is opposite of what it should be
if (!empty($error)) {
^
// your database stuff here
}
You should run that query when the error is empty, and not when its not empty.
if (empty($error)) {
// now save to database
}
Also go through How can I prevent SQL injection in PHP?
Check the condition on which you are inserting the data in the database. You are checking if (!empty($error)) which should denote that there is an error. Also since $error is a string, I would recommend you to check the values as if(trim($error) != "") rather than using empty()
you should use else if to check each condition..
if(isset($POST['submit'])){
if(empty($_POST['email'])){
$error[] = "email is required";
}
elseif(empty($_POST['name'])){
$error[]= "name is required;";
}
...
else{
$email = $_POST['email'];
$name = $_POST['name'];
// do all the stuff here
}
}
// also correct !empty ()
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`)
VALUES('".$name."','".$batch."','".$email."','".$mobile."');
You need to concatenate the strings. If you put $email in quotes, it will be considered a string and not a variable.
I want to make my site as secure as possible so i need to convert everything i have to PDO. I've successfully done a few things but i ran into a road block on my Sign In page.
Heres my code:
<?php
//signin.php
include 'connect.php';
include 'header.php';
session_start();
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can signout if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<div class="formdivs" id = "logindiv"><form class = "homeforms" method="post" action="">
<label>Username:<input class="forminput" id="smallinput" type="text" name="user_name" /></label>
<label>Password:<input class="forminput" id="smallinput" type="password" name="user_pass"></label>
<input class = "formbutton" type="submit" name = "button" value = "Sign In!"/>
</form></div>';
}
else
{
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
else
{
//THIS IS WHERE MY PDO PROBLEM BEGINS-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
$password = sha1($_POST['user_pass']);
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :password";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':password', $password);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if(true)
{
if(true)
{
$_SESSION['signed_in'] = true;
while($row = $stmt->fetch())
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
header('Location: /forum.php');
exit;
}
}
}
}
}
include 'footer.php';
?>
My page loads the form but when i press my submit button it turns blank (except for my header and footer) which tells me my php has an error. (obviously)
I want my page to be able to run its error checking (to see if both boxes have input) then to execute upon button press. After i press the button i want it to echo an SQL error if there is one (in situations where the database is down etc) And then also echo if the user name or password does not exist in the database. (IE the select statement returns nothing).
At the moment i have "admin" and "password" just hardcoded in, because i dont think my bindparams statements worked.
EDIT: i should also state that none of my error checking works. If i try to run it with the boxes empty nothing is still shown.
EDIT: SOLUTION: I was using $pdo when i should have been using $DBH. I didnt realize the $pdo variable from the php manual was supposed to be the actual instance i created in my connect.php file. Thanks for your help everybody
You need the colon in your SQL string
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :userpass";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':userpass', $password);
$stmt->execute();
no need for loop , since it's a single record:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
//set your session
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
Keep things simple
if(isset($_POST['submit']){
//form submitted, checking errors
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
exit();//error! let's exit
}else{
//No errors run the PDO query here
}
}else{
//no submission display the form
}
I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...