PHP form validation failure - php

I am trying to do form field validation with php. I am checking if the submit button isset first and then if the form fields are empty, save it in a error variable, else if its not empty I have a function doing som form cleanup and setting the value to the textfield.Then submitted to another page.
But my error handling never happens and the form with empty fields are submitted to my action page url.
Whats wrong with code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$fnameErr = "";
$lnameErr = "";
$Fname = "";
$Lname = "";
if(isset($_POST["submit"])) {
if (empty($_POST["FirstName"])) {
$fnameErr = "First name is required";
} else {
$Fname = form_input($_POST["FirstName"]);
}
if (empty($_POST["LastName"])) {
$lnameErr = "Last name is required";
} else {
$Lname = form_input($_POST["LastName"]);
}
}
function form_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form action="intro.html.php" method="POST">
Förnamn: <input type="text" name="FirstName">
<span class="error">* <?php echo $fnameErr;?></span>
<br>
Efternamn: <input type="text" name="LastName">
<span class="error">* <?php echo $lnameErr;?></span>
<br>
<input type="submit" name="submit" value="Skicka">
</form>
</body>
</html>
Thank you

UPDATE
if file of action form is different with the form file you need to check the input on action.
here the index.php
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
/* get the return value when is not valid on into.html.php*/
$fname = $_GET['fName']; $lname = $_GET['lName'];
if($_GET['fName']=='false'){
$fnameErr = "First name is required"; /*set value to show notif*/
$fname ="";
}
if($_GET['lName']=='false'){
$lnameErr = "First name is required"; /*set value to show notif*/
$lname ="";
}
?>
<h2>PHP Form Validation Example</h2>
<form action="intro.html.php" method="POST">
Förnamn: <input type="text" name="FirstName" value="<?php echo $fname;?>">
<span class="error">* <?php echo $fnameErr;?></span>
<br>
Efternamn: <input type="text" name="LastName" value="<?php echo $lname;?>">
<span class="error">* <?php echo $lnameErr;?></span>
<br>
<input type="submit" name="submit" value="Skicka">
</form>
</body>
</html>
and then set your intro.html.php like this
<?php
function form_input($data) {
if($data!=""){ /*add condition if data != "" then run so we don't need more else on section if $_POST is empty*/
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}
return $data;
}
if(isset($_POST["submit"])) { /*check the submit*/
$Fname = form_input($_POST["FirstName"]); /* get post data from input val to variable $Fname*/
$Lname = form_input($_POST["LastName"]); /* get post data from input val to variable $Lname*/
if(!empty($_POST["FirstName"]) and !empty($_POST["LastName"])!=""){ /*cek if FirstName and LasName is not empty*/
/* do what you want to do here*/
echo ' FName : '.$Fname.' | LName : '.$Lname;
}
else{
/*we will redirect to index.php using javascript*/
echo '
<script>
alert("all input must be field!");
window.location.href="index.php?fName='.($_POST["FirstName"]==""?'false':$Fname).'&lName='.($_POST["LastName"]==""?'false':$Lname).'"; /* this ridect to index.php and set variable $_GET fName and variable lName */
</script>
';
}
}
else{
echo 'submit is undefined!'; /*echo submit empty, */
}
?>
if you want to check input before submit, you can use HTML <input> required Attribute here the documentation
or you can use jquery to proses ajax submit or just check the input value you can see more in here
hope this help.

Related

Attempting to use if !isset to display results without the form

I am attempting to display the results without the form being shown at the same time. So, initially when they go to the URL they see the form, and after they fill out the form and the form validation and required fields and URL is valid. Here is what I started with.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = test_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurl = "";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
?>
</body>
</html>
Here is what I have tried.
I've tried adding else statements after body and before results. I'd like the results not to show until after form submitted.
Here's what I have so far...
I tried to add the below after the body
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['name']) == "")){
?>
Then I added:
<?php
} else {
//Retrieve show string from form submission.
Just after
// define variables and set to empty values
Finally added:
<?php
} ?>
Before /body
Here is what I tried.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['TXTlinkname'] && $_POST['TXTurl']) == "")){
?>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = HTML_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurl = "";
} else {
$TXTurl = HTML_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = HTML_input($_POST["TXTurl"]);
}
}
function HTML_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
} else {
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
?>
<button onclick="location = location.href">Go Back</button>
<?php
} ?>
</body>
</html>
So, initially when they go to the URL they see the form, and after they fill out the form and the form validation and required fields and URL is valid.
The big issue I see with your code is the if statement. The variables are not defined unless form hasn't been submitted. What I've changed is moved the function to be defined globally along with the variable names, and inverted the if statement. PHP Tags, you don't need them everywhere. One wrapper is good enough.
I'm not sure about what your result is, but for what you asked, I shall provide.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
function HTML_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$TXTlinkname = $TXTurl = "";
$TXTlinknameErr = $TXTurlErr = "";
//If form not submitted, display form.
if (isset($_POST['submit'])){
if (empty($_POST['TXTurl'])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = HTML_input($_POST['TXTurl']);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST['TXTname'])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = HTML_input($_POST['TXTname']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
}
if (empty($TXTurlErr) && empty($TXTlinknameErr) && isset($_POST['submit'])) {
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
echo '<button onclick="location = location.href">Go Back</button>';
} else {
echo '<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'">
Name: <input type="text" name="TXTname" value="'.$TXTlinkname.'">
<span class="error">* '. $TXTlinknameErr .'</span>
<br><br>
URL: <input type="text" name="TXTurl" value="'.$TXTurl.'">
<span class="error">'.$TXTurlErr.'</span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>';
}
?>
</body>
</html>
Tested locally on XAMPP
You have to have a variable that tells you if you're going to show the textarea or not...
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
$show_textarea = false; //DEFAULT
if (isset($_POST['submit'])) { //The form is sent...
$show_textarea = true; //Then this is DEFAULT!!
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = test_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurl = "";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurlErr = "URL is required";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($show_textarea === false) {
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
if (isset($_POST['submit'])) { //The form is sent...
if ($show_textarea === true ) { //...AND the form has valid values
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">
' . $TXTlinkname . '
</textarea>';
}
}
?>
</body>
</html>
try this one:
if (!$_POST) || $_POST['TXTlinkname'] == "" && $_POST['TXTurl']) == "")){

Simple server-side validation using php

i have a problem with the validation my input and select fields.
If the inputs are empty and click on submit the warning "this field is required" appears.
But when i fill the ClientID input and the selection box is empty the validation will fail. Or invers, when the select box is selected and the input is empty.
here my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $katalogErr = $selectKatalog = "";
$kdn = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["kdn"])) {
$nameErr = "This field is required";
} else {
$kdn = test_input($_POST["kdn"]);
// check if kdn only contains letters, numbers and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/", $kdn)) {
$nameErr = "Only letters, numbers and white space allowed";
}
}
if($_POST["selectKatalog"] == 'default'){
$katalogErr = "This field is required";
}
else {
$selectKatalog = $_POST["selectKatalog"];
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Order a Catalog</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
ClientID: <input type="text" name="kdn">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Catalog: <select name="selectKatalog">
<option value="default">Bitte wählen:</option>
<option value="Catalog1">Catalog1</option>
<option value="Catalog2">Catalog2</option>
<option value="Catalog3">Catalog3</option>
</select>
<span class="error">* <?php echo $katalogErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $kdn;
echo "<br>";
echo $selectKatalog;
?>
</body>
</html>

PHP - Form validation of fields and messages in PHP

I would like to validate the information before its send it to me. For instance that an email address has an # on it.
I have the following code to introduce: Name, LastName and email. I validated it that they are not empty, but:
How do I send a message to the user to let them know that they need to fill it up? I tried: if ($nameErr == ''){echo "Need to introduce a name"}
but it doens't work
How do I make validation of type: making sure that email address has an # or that a telephone is numeric and has 9 digits?
Thank you so much
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = "";
$name = $email = $surname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["surname"])) {
$surname = "";
} else {
$surname = test_input($_POST["surname"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Last Name: <input type="text" name="surname">
<span class="error">*<?php echo $surnameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
you don't actually need to code all validation yourself. It is more convenient if you use a library like http://respect.github.io/Validation/ this.

How to $_Post data from submit form PHP after validation

I just saw this codes from this website and thinking to implement it to my project however I cannot get my data on the next page. I am using the test.php as a index and submit.php as a page that will catch the post
here is the codes
test.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.
if (empty($_POST["firstName"])) {
$firstNameErr = "First name is required";
$valid = false; //false
}
else {
$firstName = test_input($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
$valid = false;
}
else {
$lastName = test_input($_POST["lastName"]);
}
//if valid then redirect
if($valid){
header('Location: submit.php');
exit();
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Find Customer</h2>
<p><span class="error">* required</span></p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
First Name: <input type="text" name="firstName" value="<?php echo $firstName; ?>"><span class="error">* <?php echo $firstNameErr; ?></span><br><br>
Last Name: <input type="text" name="lastName" value="<?php echo $lastName; ?>"><span class="error">* <?php echo $lastNameErr; ?><br><br>
<input type="submit">
</form>
</body>
</html>
submit.php
<?php
$test=$_POST['lastName'];
echo $test;
?>
Your form action should be the file where you want to get the form submitted values .
change this <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post"> to <form action="submit.php" method="post">

Php form validate and post are working but not together?

In order to work properly my form needs to be set up to first check the validation and then post the data if the validation passes. This is fine but I am not sure how to combine the validation code with the post code in the form action. Example if the action is: action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> the form validates correctly but does not send anywhere! If I change the form action to action="contact-engine.php"> then the form is posted but without validation! With this in mind I need to combine into the action both the validation and then (once passed validation) the contact-engine.php problem is I simply do not know how to do this? I really am a learner in php and this is complicated for me! Any help is really appreciated I have been working on this from now for a few days! (N.B. both pages are .php) Full code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Help!</title>
<style type="text/css">
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Name
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}}
//Email
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><span class="error">* required field.</span></p><br />
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Name:<br />
<input type="text" name="name" class="border" size="25" value="<?php if(isset($_POST['name'])) {echo $_POST['name']; } ?>">
<span class="error"><?php echo $nameErr;?></span>
</div>
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Email: (please double check enty)<br />
<input type="text" name="email" class="border" size="25" value="<?php if(isset($_POST['email'])) {echo $_POST['email']; } ?>"><span class="error">
<?php echo $emailErr;?></span>
</div>
<div>
<input type="submit" value="Send" id="submit">
</div>
</form>
</body>
</html>
And below is the contact-engine code:
<html>
<head>
<title>Contact Engine</title>
</head>
<body>
<br />Name:<?php echo htmlspecialchars($_POST['name']); ?><br />
<br />Email:<?php echo htmlspecialchars($_POST['email']); ?><br />
</body>
</html>
You can try this. This is a simple code below through which you can achieve this:
//sample index.php file
<?php
include 'submitted.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="foo" />
<input type="submit" value="submit">
</form>
</body>
</html>
Here, I am submitting the form to the same page using post method. But, I have included another file which is include 'submitted.php'.
Here is the test script inside the submitted.php
//sample submitted.php
<?php
if(isset($_POST['foo']))
{
if(strlen($_POST['foo']) < 5){
echo "String length too small";
}
else
{
echo $_POST['foo'];
}
}
?>
For test, it simply checks if the length is more than five or not. If it is not, the error message is displayed on the same page where your page is present.
Test it yourself too.

Categories