Php form validate and post are working but not together? - php

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.

Related

php special character validation

I made a simple form where the user needs to enter their name and email adress, after the user has
done this they should click on the submit button and their data show for 3 seconds and after that they will be redirected to another page.
All this works but now i want to add a input validation i found a example on W3Schools and tried make this and add this to my code. Right now my code looks like this but the validation doesnt work. how can i fix this problem?
the validation doesnt show up so when a user for example puts a 2 behind his/her name the code wont give the error message: $NameErr = "only letters and white space are allowed"; instead of show this it goes straight to the "next page" were the user input is show for a short time
<?php
$NameErr = "";
$Message = false;
$Name = $_POST["Fullname"];
$Email = $_POST["Email"];
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["Fullname"])){
$NameErr = "name is required";
}else{
$Message = "your data has been sent, you will be forwarded to the next page.";
$Name = $_POST["Fullname"];
}
$Name = Input($_Post["Fullname"]);
if(!preg_match("/^[a-zA-Z-' ]*$/",$Name)){
$NameErr = "only letters and white space are allowed";
}
}
if(empty($_POST["Email"])){
$EmailErr = "Email is required";
}else{
$Message = "your data has been sent, you will be forwarded to the next page.";
$Email = $_POST["Email"];
}
$Email = Input($_Post["Email"]);
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
$EmailErr = "Only letters are allowed";
}
function Input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>form</title>
<link rel="stylesheet" type="text/css" href="formulier.css">
</head>
<body>
<main>
<?php
if(!$Message){
?>
<p> put your data here: </p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<span class="error">* <?php echo $NameErr;?></span>
<input type="text" name="Fullname" placeholder="enter your fullname">
<span class="error">* <?php echo $EmailErr;?></span>
<input type="email" name="Email" placeholder="enter your email">
<button name="SubmitBtn">submit</button>
</form>
<?php
}else{
?>
<h1 id="Message"> your data is:</h1>
<p><b>Naam:</b> <?php echo $Name; ?></p>
<p><b>E-mail:</b> <?php echo $Email; ?></p>
<p id="Message"><?php echo $Message; ?></p>
<script>
var Message = document.getElementById("Message");
setTimeout(function(){
window.location = "contact.php";
}, 3000);
</script>
<?php
}
?>
</main>
</body>
</html>

php data validation submitting bad data

I currently have my code working to some state.
When the user inputs data name, email and company they submit the form and it will echo the inputs out which is fine, but when I enter invalid data into the form and submit it will still post but displays the else statement.
Have I missed something in my Preg_match or is this just a bad way to code the validation?
<!DOCTYPE html>
<html>
<head>
<title>Visitor Sign in</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="visitor.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<img src="Wincanton.png" alt="wincantonLogo" class="wincantonLogo" />
<img src="Screwfix.png" alt="screwfixLogo" class="screwfixLogo" />
<div style="clear:both"></div><br>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $companyErr = "";
$fullname = $email = $company = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
} else {
$fullname = test_input($_POST["fullname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!preg_match("/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["company"])) {
$companyErr = "Name is required";
} else {
$company = test_input($_POST["company"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$company)) {
$companyErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Visitor Sign in</h1><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="fullname" >
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Company: <input type="text" name="company">
<span class="error"><?php echo $companyErr;?></span>
<br><br>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fullname;
echo "<br>";
echo $email;
echo "<br>";
echo $company;
echo "<br>";
?>
</body>
</html>
try if isset condition.
if(isset($_POST['submit'])){
}

separating php from html?

I have PHP code with HTML inline, yet I need them to be separate on two pages. A HTML page with a form and a PHP form with the process on it.
The bits with the PHP form verification I need on a PHP page and the form I need on a HTML sheet the rest of the website will be on
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php // define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
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"]);}
}
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" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
?>
</body>
</html>
updated HTML code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php require 'php.php'; echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php require 'php.php'; echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php require 'php.php'; echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You'd need to put your php code in an other file (for example form.php). In your html file you need to include your php script. If your php file is situated in the same directory as your html file, your include statement could look like this.
<?php include 'form.php';?>
I'd like to refer you to W3schools php include where they explain in detail how you can link your php file.
I am just giving you a basic example to separate form file and php file.
create a index.php file and write those code there
<form action="post.php" method="post">
<input type="text" name="txtName"/>
<input type="submit" name="btnSubmit"/>
</form>
Then create a post.php file and put below code there
<?php
if(isset($_POST['btnSubmit'])){
$val = $_POST['txtName'];
echo $val;
}
?>
Hope it will help.
So here you have all the code for html form in your file. Now create a new file for process the form like "process.php" and post your form on that file. place this new file on the same directory where the HTML file is being placed and give path of this file into your form action = " " like
<form method="post" action="process.php">
and in the process.php page you can process you form as you are doing.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
}

PHP form validation failure

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.

How to save field form in database with required fields

Hello I'm figuring how to save the field entered into database when there's no field required left.
I can already save from database with php and mysqli, but I don't want to include the null/blank value from the database which is why I'm using required field but I don't know how to use it. What I wanted to do is when all the required field is not null or has already value in it, it will gonna save from the database.
I don't know what to put on
form method=post action="HERE"
PS: Sorry for bad english.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
In the action="" you should point to the php file that is gonna do the back-end job. (getting the datas, checking the inputs, and storing into the database).
like this action="file.php"
to check whether an input is correctly filled, you have many ways of doing so :
`<input type="text" name="name" value="<?php echo $name;?>" required>`
(html5)
you can do it serverside ( in your php file )
if(!isset($_POST['name')) OR if(strlen(trim($_POST['name'])) !== 0) OR if($_POST['name'] !== '')
and many other ways.
Hope this was what you were searching for!

Categories