Make errors show on top of a form - php

How do I make error show on top of form so that if $user->success == true, it wont show my form then. Removing that last else would help, but then form shows after success. One way is to redirect that. Maybe tehre
if (isset($_POST["submit"]))
{
if ($_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
$User->signin($_POST['username'], $_POST['password']);
}
else
$User->CheckUser();
if ($User->success == true) {
include ('in.php');
}
if ($User->error)
echo "<p>" . $User->error . "</p>";
else
echo 'Don\'t process form';
$_SESSION["formid"] = md5(rand(0,10000000));
} else {
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input id="username" name="username" type="text" /><br />
Password:
<input id="password" name="password" type="password" /><br />
<input type="hidden" name="formid" value="<?php echo $_SESSION["formid"]; ?>" />
<input type="submit" name="submit" />
<br />
Register
</form>
<?php }?>

Perhaps the simplest approach is to just create a variable $show_form to use to determine whether form is to be shown,
$show_form = true;
if(isset($_POST['submit'])) {
// do your form processing here.
// If you decide everything is good and you don't want to show the form,
// just add this line:
$show_form = false;
} // don't use else here
if (true === $show_form) {
?>
<form>...</form>
<?
}
?>

add this code before your form tag
<?php if (isset($User->error) AND $User->error)?>
<p><?php echo $User->error?></p>
<?php?>

Related

I am getting a really weird result on my php form output

Here is my code:
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$age = $_POST['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_GET['getName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$age = $_GET['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
I have two forms. Both displaying the exact same thing, but one form using POST and one using GET.
I have gotten so close to finishing this off but now I have another small/weird issue.
The code technically works correctly, but here's the output explanation:
when I first open up the page the GET form already has the result "Sorry, try again when you're 16 or older." When I fill out the first 'simple' form, it displays the result correctly but then the POST form shows the "Sorry, try again..." result. Then, when I fill in the information and click submit, it displays the correct result and the other two forms are blank as they're supposed to be, and then the same result when I fill out the GET form.
Any help on this is much appreciated.
Try this code :
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
if (isset($_POST['firstName']) && $_POST['lastName'])
{
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
}
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_POST['postName']))
{
echo $_POST['postName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['age']))
{
$age = $_POST['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_GET['getName']))
{
echo $_GET['getName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if (isset($_GET['age']))
{
$age = $_GET ['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
Please try this. I hope it will help.
Replace
if ($_SERVER['REQUEST_METHOD'] == "POST") {
with
if (isset($_POST['age'])) {
Similarly,Replace
if ($_SERVER['REQUEST_METHOD'] == "GET") {
with
if (isset($_GET['age'])) {
When you first enter on page, default REQUEST_METHOD is GET so you should check if isset($_GET['age']) {
and here check if it is more than 16
}
also you should check this one
echo $_GET['getName']; and change on this
echo isset($_GET['getName']) ? $_GET['name'] : "";
You should also check $_POST request like this and your program will work correctly.

In php validation when wrong data is found the page get refreshed and the data's already entered will became empty.How to prevent the loss?

I am a very beginner in php.I tried a form validation in php while validating my form.when wrong data is found the browser will show an alert box, when i click it the browser reloads the page and the details already entered in the form get refreshed and i need to enter it from the first.
How to avoid the page refresh while validating.
sorry for my poor english
Thank you in advance
This is my php form coding
formvalidate.php
<html>
<head>
<title>USER REGISTRATION</title>
</head>
<body>
<form name="registrationform" id="formid" method="get";>
name:<input type="text" id="n1" name="name"> <br><br>
username:<input type="text" id="u1" name="username"> <br><br>
password:<input type="password" id="p1" name="password"> <br><br>
confirm password:<input type="password" id="p2" name="password2"> <br><br>
Address :<textarea name="address" id= "a1"rows="4" cols="40"> </textarea><br><br>
phone :<input id="ph" type="numbers" name="phone" ><br><br>
<input type="submit" name="register" value="register" >
<input id="button" type="button" value="cancel">
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="userlogin";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("connection failed".mysqli_connect_error());
}
?>
<?php
if (isset($_GET['register'])) {
if(empty($_GET['name']))
{
echo'name should not empty';
}
if ( empty($_GET['username'])) {
echo 'user name should not be empty';
} else {
$name1=$_GET['name'];
$uname=$_GET['username'];
$sql = "select * from contact where username='$uname'";
$result=mysqli_query($conn,$sql);
if($result->num_rows==1)
{
echo"username already exists";
}
else
{
echo"username available";
}
return false;
}
if((empty($_GET['password']))||(empty($_GET['confirmpassword'])))
{
echo'password and confirm password should not be empty';
return false;
}
else{
$pwd=$_GET['password'];
$cpwd=$_GET['confirmpassword'];
if($pwd.length==6){
echo'password should not lesser than 6';
}
else
{
if($pwd==$cpwd){
echo'password accepted';
}
else
{
echo 'password does not matched';
return false;
}
}
}
if(empty($_GET['address']))
{
echo'address should not be empty';
return false;
}
if(empty($_GET['phone']))
{
echo'phone should not be empty';
return false;
}
}
?>
</body>
</form>
</html>
You could perform the check at the start of page, something like;
$sParam1 = "";
if (isset ($_GET['param1']) ){
$sParam1 = (string)$_GET['param1'];
}
Leave the form at the bottom of the page and echo the variables in the value param;
<form method="get">
<input type="text" name="param1" value="<?php echo htmlspecialchars($sParam1); ?>" />
</form>
Yoy can also set something like
if(isset($_GET['name'] ){echo "value=$_GET[name]";}
for each of the input attributes.
Though i believe you should use POST attribute in form rather tham GET.
Also, you have not set the 'action' attribute for the form !

Why this validation code does not work as expected?

I have a form and the action of the for m is same page.
I am trying to :
Show a thanks message upon the successful form submission
Show error messages next to the field where the error is detected
All the above must be shown in the same page.
My code is :
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
else {
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
?>
I've limited the validation and showing only for first part in this QUESTION.
When I submit this form If there is NO any errors the I am getting the message Thanks, We have received your feed back
That's fine and works as expected.
When an error exists / the field Guest name is empty I am getting the message during the form submission Errors!
Please check the fields which have errors below. Error hints are in Red.
That's also fine.
But my form is just disappear when I get the above message. Why?
Also I want show that Please type your name! next to the field.
Try bellow code. I have removed else part and set flag with true/false to check from is valid or not.
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
$chkValidate = "true";
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
$chkValidate = "false";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';
$chkValidate = "false";
}
if($chkValidate == "true"){
echo 'Thanks, We have received your feed back';
}
}
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?php if(!empty($errors) && $chkValidate != "false") { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
?>
Just remove else condition cause actually your form will not be display if $_POST["Ask_the_Question"] is set
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
The reason why is here:
<?php
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
} else {
// your form code will never be called if $_POST['Ask_the_Question'] is set
TO do what you want to achieve you probably want to do something like this instead:
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
} else { ?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
}
?>
Other answers are fine, but just to clarify what happens.
But my form is just disappear when I get the above message. Why?
Your form disappear because if you pass the first if you can't get to your else.
if (isset($_POST["Ask_the_Question"])) {
...
} else {
xxx;
}
That means if you want to see your form you have to put it somewhere it can be shown like elseif (with more restrictions), or ifs inner or outer.
if (isset($_POST["Ask_the_Question"]) && empty($errors)) {
...
} elseif (isset($_POST["Ask_the_Question"]) && !empty($errors)) {
...
} else {
...
}
Also I want show that Please type your name! next to the field.
To show all errors you could use eg. foreach anywhere you want to show them.
foreach ($errors as &$error) {
echo "Error: $error<br />\n";
}
Btw be careful with the empty(); function.

How to show error messages in HTML page in PHP?

I have following login form (login.php) in which I am asking for username and password.
<form action="processlogin.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
Following is the code snippet from my processlogin.php file
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
echo $msg;
//header("Location:http://localhost/login.php");
}
This code checks whether all the mandatory fields are filled on not. If not, it shows the error message.
Till now everything is fine.
My problem is that, error message is shown in plain white page. I want to show it above the login form in login.php file. How should I change my code to get
my functionality.
I would prefer Jquery Validation or Ajax based Authentication. But still you can do it this way:
Put your Error Message in Session like this :
$_SESSION['Error'] = "You left one or more of the required fields.";
Than simple show it like this:
if( isset($_SESSION['Error']) )
{
echo $_SESSION['Error'];
unset($_SESSION['Error']);
}
In this case you can assign multiple messages in different Operations.
header("Location:http://localhost/login.php?x=1")
In the login.php
if(isset($_GET('x'))){
//your html for error message
}
Hope it helps you,
In processlogin.php,
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
$msgEncoded = base64_encode($msg);
header("location:login.php?msg=".$msgEncoded);
}
in login.php file,
$msg = base64_decode($_GET['msg']);
if(isset($_GET['msg'])){
if($msg!=""){
echo $msg;
}
}
You can display the message in table or span above the form.
<span>
<?php if(isset($_REQUEST[$msg]))
echo $msg;
?>
</span>
<form>
</form>
And also don't echo $msg in the form's action page.
Try this:
html:
<form action="processlogin.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
<span>
<?php if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</span>
</form>
php:
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
header("Location:http://localhost/login.php?msg=$msg");
}
Use only one page (your login.php) to display the form and also to validate its data if sent. So you don't need any $_SESSION variables and you have all in one and the same file which belongs together.
<?php
$msg = null;
if(isset($_GET['send'])) {
if(!$_POST["username"] || !$_POST["password"]){
$msg = "You left one or more of the required fields.";
//header("Location:http://localhost/login.php");
}
}
?>
<?php echo ($msg !== null)?'<p>ERROR: ' . $msg . '</p>':null; ?>
<form action="?send" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
use these functions:
<?php
session_start();
define(FLASH_PREFIX,'Flash_')
function set_flash($key,$val){
$_SESSION[FLASH_PREFIX.$key]=$val;
}
function is_flash($key){
return array_key_exits(FLASH_PREFIX.$key,$_SESSION);
}
function get_flash($key){
return $_SESSION[FLASH_PREFIX.$key];
}
function pop_flash($key){
$ret=$_SESSION[FLASH_PREFIX.$key];
unset($_SESSION[FLASH_PREFIX.$key]);
return $ret;
}
?>
And when you want to send a message to another page use
set_flash('err_msg','one field is empty');
header('location: another.php');
exit();
another.php
<html>
.
.
.
<body>
<?php if(is_flash('err_msg')){?>
<span class="err_msg"><?php echo pop_flash('err_msg'); ?></span>
<?php } ?>
.
.
.
</body></html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
echo $msg;
//header("Location:http://localhost/login.php");
}
}
?>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>

Allow Submission of Form Multiple but Up to Allowed Times on PHP

I have a form that a user can enter in first name, last name and email. You can submit this form multiple times in case you would like to send to more users by simply clicking on submit (of course, so long as the fields are entered correctly using sanitation and validation).
if (isset($_POST['Submit'])) {
//sanitize if field (like email) is not empty, then validate it using a function
// such as FILTER_VALIDATE_EMAIL and FILTER_SANITIZE_STRING
//like if ($_POST['email'] != "") { do the sanitation and validation here }
//then if no error send the email
//then $_POST = array(); to clear up form for the next entry
}
<form> form here</form>
Do you guys have an idea by just laying out this concept? Or do you need a sample code? Thanks for your help.
Was trying to use what Joe suggested but didn't work. Any further help?
session_start();
if (isset($_POST['Submit'])) {
if (isset($_SESSION['submission_count'])) {
if ($_SESSION['submission_count'] > 10) {
echo "You can't submit so many!";
exit;
}
}
else {
$_SESSION['submission_count'] = 0;
}
$_SESSION['submission_count'] += 1;
// Form validation and sanitation
// Send email
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:
<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" size="50" /><br />
Last Name:
<input type="text" name="lastname" value="<?php echo $_POST['lastname']; ?>" size="50" /><br />
Email Address:
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><hr />
<br/>
<input type="submit" class="button" name="Submit" />
</form>
You can store a counter in $_SESSION.
http://www.php.net/manual/en/intro.session.php
<?php
// Starting the session
session_start();
if (isset($_POST['Submit'])) {
if (isset($_SESSION['submission_count'])) {
if ($_SESSION['submission_count'] > 5) {
echo "You can't submit so many!";
exit;
}
}
else {
$_SESSION['submission_count'] = 0;
}
$_SESSION['submission_count'] += 1;
// Do the rest of your form submission
}

Categories