Simple Validator in PHP not working - php

I created a little form validator with PHP and having some problems with it.
MY VIEW FILE is here :
<form action="" method="post">
<?php if( isset($status) ) : ?>
<p class="notice"><?php echo $status; ?> </p>
<?php endif; ?>
<ul>
<li>
<label for="name">Your Name : </label>
<input type="text" name="name">
</li>
<li>
<label for="email">Your Email : </label>
<input type="text" name="email">
</li>
<li>
<input type="submit" value="Sign Up">
</li>
</ul>
</form>
and here's my little controller :
<?php
require 'index.tmpl.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
?>
Now what happens is that , when I open up the page and leave the form fields blank and submit it ,it just reloads ,does not echo anything.

You want to echo $status, not $name.

How about moving the require line to below the if?
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
require 'index.tmpl.php';
?>

The <form action="" points to the location where the form will be submitted. If blank, it submits the form back to itself.
<form action="yourLittleController.php" method="POST">
Edited with more info:
in php, post is not POST. Example here: https://eval.in/89002
make sure you have
method="POST">
and not
method="POST">

you should mention your second file name in your view file's form's action attribute like action = "controller.php"

Related

I don't know what i did wrong on my code, the error message for php form validation stopped working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>

How to display php form result in the html if php processing is not in the same page without using ajax?

Lets say i have this form in form.php file.
<form action="process.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result"></span>
process.php contains
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
if(!empty($message)){
echo 'Your message: '.$message;
}else{
echo 'Please enter some message.';
}
}
Now if i want to display the output of process.php inside the form.php's span tag of class result i either need to use ajax, or session/cookie or file handling. Is there any other way?
You can simply place the code in the process.php file inside the forms span tag.
<form action="form.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result">
<?php
if(isset($_POST['message']))
{
$message = $_POST['message'];
if(!empty($message))
{
echo 'Your message: '.$message;
}
else
{
echo 'Please enter some message.';
}
}
?>
</span>
Try this. It will post the form values in same page
<form action="form.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result"></span>
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
if(!empty($message)){
echo 'Your message: '.$message;
}else{
echo 'Please enter some message.';
}
}
OK this is one way of doing it: In form.php,
<form action="process.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<?php
$var = $_GET['text'];
echo "<span class=\"result\"> $var </span>";
?>
Then in process.php do this:
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
if(!empty($message)){
// echo 'Your message: '.$message;
header("location: form.php?text=$message")
}else{
echo 'Please enter some message.';
}
}
?>
There are a few drawbacks using this method:
Variable $message is passed through the URL and so should not be too long as URLs have length limits
Using $_GET[] makes message visible on the URL so passwords and other sensitive information should no be used as the message.
I hope this helps.

Validation of form in another php script?

I'd like to know if it is possible to manage error if in the form, action is set to another script.
ajoutDevis.php
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<span class="error">* <?php echo $clientErr;?></span>
</FORM>
ajoutDevisScript.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['client'])) {
$clientErr = "ERROR";
} else $client = $_POST['client'];
So, is it possible to display my error in the span if the input is empty ? Or there is no way doing it with an other script as action ?
Thanks!
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['client'])) {
$clientErr = "ERROR";
$_SESSION['error] = $clentErr;
header('location:ajoutDevis.php');
} else $client = $_POST['client'];
In your ajoutDevis.php file
session_start();
$clientErr = ($_SESSION['error']!='')?$_SESSION['error']:'';
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<span class="error">* <?php echo $clientErr;?></span>
</FORM>
You need to do the following:
Add the form code as well on the ajoutDevisScript.php page at the bottom of page.
<?php if(!empty($clientErr)) { ?>
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<span class="error">* <?php echo $clientErr;?></span>
</FORM>
<?php } ?>
This will check if there is any error in error variable it will display the form on same page with error.
Yes, it is possibile with $_SESSION variables to store values during the session and header() function to redirect user from the second script back to the first.
Supposing both files are in the root directory, ajoutDevis.php:
<?php
session_start();
?>
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<?php if (isset($_SESSION['clientErr'])) : ?>
<span class="error">* <?php echo $_SESSION['clientErr'] ?></span>
<?php endif; ?>
</FORM>
and ajoutDevisScript.php:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['client'])) {
$_SESSION['clientErr'] = "ERROR";
header('Location: ajoutDevis.php');
} else {
$client = $_POST['client'];
}
}
?>
I would suggest you to print the span only if you need to. I would also suggest you to check your brackets to avoid PHP errors.

i keep getting Undefined index: name and Undefined index: email

this is my first form
<style>
.wrap-form{
width: 700px;
min-height: 20px;
background-color: lightblue;
margin: 0 auto;
}
</style>
<div class="wrap-form">
<form method="post" action="advanced-form-send"></form>
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</div>
And this is my form 2 where the data will send to
<?php
$name = $_POST["name"];
$email = $_POST["email"];
echo $name;
echo $email;
?>
How would I fix this?
That's how your form code should be, surrounding your submit button by <a href="..." is causing the form not to be submitted, at the place you're just telling the browser that when this button is clicked, take the user to the page advanced-form-search.php. What you should do is put the script name where the form should be submitted in the action of the form tag then just add a submit button. And don't forget to close your tags... you missed the </form>
<div><?php if(isset($_GET['err'])){ if($_GET['err']==1){ echo 'You didn\'t fill in your name'; } elseif($_GET['err']==2){ echo 'You didn\'t fill in a correct email address';}}?></div>
<div class="wrap-form">
<form method="post" action="advanced-form-send.php">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
</div>
Here's the PHP code to send an email:
<?php
if(isset($_POST['name']) && !empty(trim($_POST['name']))){
$name = $_POST["name"];
} else {
header("Location: page_where_the_form_is.php?err=1");
die()
}
if(isset($_POST['email']) && filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL)){
$email = $_POST["email"];
}
else {
header("Location: page_where_the_form_is.php?err=2");
die()
}
$subject='Form Submitted On The Website';
$message="Name: {$name}\nEmail: {$email}";
mail($to_email, $subject, $message);
?>
You've wrapped your <input type="submit" name="submit"... button with an <a href=.... What this does is prevents your form from being submitted as a POST request, and instead gets linked to as a GET request.
git rid of the <a href..., and and change your action=advanced-form-send to action="advanced-form-send.php".
You can improve your php code:
<?php
if (isset($_POST["name"])) {
$name = $_POST["name"];
echo $name;
} else {
echo 'Eror: Attribute "name" is missing!';
}
if (isset($_POST["email"])) {
$email = $_POST["email"];
echo $email;
} else {
echo 'Eror: Attribute "email" is missing!';
}
?>
And your form should be changed:
<form method="post" action="advanced-form-send.php">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
You need to wrap your variables. The other answers are about the form. This answer is about your handling of variables. PHP will throw a notice if you use a variable that haven't been set. By using isset() you can determine if the variable is set and then use it.
<?php
$name = isset($_POST["name"]) ? $_POST["name"] : '';
$email = isset($_POST["email"]) ? $_POST["email"] : '';
echo $name;
echo $email;
?>
Doing it this way ensures that you wont get a notice if one of your fields haven't been posted. If they have you will have the value in $name and $email. If not then the variables will be empty strings.
Try Like this,
<div class="wrap-form">
<form method="post" action="advanced-form-send">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
</div>
The submit button should be in the two "form" markups. Also the link is unnecessary because the input "submit" will send the form with the data to the page you set in the attribute "action" of the form markup.
<div class="wrap-form">
<form method="post" action="advanced-form-send.php">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
</div>
Youre missing an enctype ... you ALL forgot it. Shame above you!
<form method="post" action="advanced-form-send.php" enctype="multipart/form-data"></form>

loading blank page despite form action location upon error

I am creating a simple form that a user submits and email. I am trying to pose an error if the form is blank or it's not a valid email and if successful, then reload the page with a success message.
When I submit blank it reloads the page without an error, and if I enter anything in ( valid or invalid email ) it reloads the page white, despite the form action being correct. I've been stuck on this and need help. Thanks.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/system/init.php');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Please enter a valid email";
}else{
$success = true;
mysql_query("INSERT INTO survey
(email) VALUES('".$_POST['email']."' ) ")
or die(mysql_error());
}
}
?>
<div class="email-survey">
<?php if(isset($success)) { ?>
<div class="success">Thank You!</div>
<?php } ?>
<?php if(isset($error)) { ?>
<div class="error">
<?php echo $error; ?>
</div>
<?php } ?>
<form name="settings" action="/survey-confirm.php" method="post">
<input type="text" name="email" /> <br />
<input type="submit" name="submit" value="submit" />
</form>
</div>
<?php
function control($type, $text)
{
echo '<div class="'.$type.'">'.$text.'</div>';
}
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/system/init.php');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
control('error', 'Type valid mail!');
}else{
control('success', 'All done!');
mysql_query("INSERT INTO survey
(email) VALUES('".$_POST['email']."' ) ")
or die(mysql_error());
}
}
else
{echo 'echo '<form name="settings" action="/survey-confirm.php" method="post">
<input type="text" name="email" /> <br />
<input type="submit" name="submit" value="submit" />
</form>
</div>';}
?>
This is small function named control, you can call this and put your custom div name and text to show user.
control('THIS IS DIV NAME','THIS IS MESSAGE FOR USER')

Categories