Php "How to remove an instruction after submitting" - php

my code does work properly I am just having trouble with removing "Please enter your name" and only displaying the welcome message after the user submits their name.
I've tried to use conditional statements that just led to an error
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}//$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$method = $_SERVER["REQUEST_METHOD"];
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = isset($_POST["name"])? $_POST["name"]: "";
validate_name($name, $err);
}
?>
<!-- The form -->
<form method="post">
<center><label>
<input type="text" name="name" value="<?php echo #$name;?>">
</label></center>
<!-- Show if no error -->
<?php if(empty($err)) { ?>
<span><p class="centered-text">Please enter your name</span>
<?php } else { ?>
<!-- Show if error -->
<span class="error">
<?php echo $err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php if(isset($name) && empty($err)){ ?>
<p class=" centered-text">Hi <?php echo $name?>!</p>
<p class="centered-text">Welcome to our store!</p>
<?php } ?>
My expected result is to display "please enter your name" and once the user submits to remove the instruction "please enter your name" and display the welcome message only

<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}
# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}//$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$method = $_SERVER["REQUEST_METHOD"];
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = isset($_POST["name"])? $_POST["name"]: "";
validate_name($name, $err);
}
if(isset($name) && empty($err)){ ?>
<p class=" centered-text">Hi <?php echo $name?>!</p>
<p class="centered-text">Welcome to our store!</p>
<?php } else { ?>
<!-- The form -->
<form method="post">
<center><label>
<input type="text" name="name" value="<?php echo #$name;?>">
</label></center>
<!-- Show if no error -->
<?php if(empty($err)) { ?>
<span><p class="centered-text">Please enter your name</span>
<?php } else { ?>
<!-- Show if error -->
<span class="error">
<?php echo $err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php } ?>

The error check should only be done if $name is set. If it's not set, the form hasn't been submitted and you should only show the "Please enter your name" message in that case.
Here's the basic logic (HTML not included to improve clarity):
if (!isset($name)) {
// Name has not been submitted yet, show "Please enter your name" message
else {
if (empty($err)) {
// Name was submitted and validated successfully, show welcome message
} else {
// Name was submitted with errors, show the errors
}
}

Related

Producing error messages in php validation

I am trying to validate a form using php, the code i have doesn't prevent the form from being submitted when the inputs are invalid, however, the error messages that i would like them displayed do not show on the form, the form is returned empty of error messages even tho i have them echo'ed inside the form. could you help me display the error messages upon unsuccessful submission of the form ? i added my form code and the php code. both are seperate files , the action in the form leads to the php validation code like so (action = "report_form_php.php).
<form method="post" onsubmit=" return formSubmit()" action="report_form_php.php">
<div class="error1" id= "errorMsg">* Required Fields</div>
<div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com" >
</div><br>
<div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";
// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staffname"])) {
$staffErr = "Staff Name is required";
} else {
$staff_name = test_input($_POST["staffname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
$staffErr = "Only letters and white space allowed";
}
}
// email validation:
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Please enter a valid email.";
}
}
// subject validation:
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
// check if subject only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
$subjectErr = "Only letters and white space allowed";
}
}
// problem type validation:
if (empty($_POST["problem_type"])) {
$problemErr = "Problem type is required";
} else {
$problem_type = test_input($_POST["problem_type"]);
}
// description validation:
if (empty($_POST["description"])) {
$descriptionErr = "A Description is required";
} else {
$description = test_input($_POST["description"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($staffErr == "" && $emailErr == "" &&$subjectErr == "" &&$problemErr == "" &&$descriptionErr == "") {
header("Location: insert_logs.php");
exit();
} else {
header("Location: log-it-reportsbeta.php");
exit();
}
?>
This basic php codes below should give you the ideas for 3 states of a form submission process to adjust your code properly.
success
system failure (bug or a temp. server issue for example)
invalid user data input
// data were valid && script's aim is achieved
if (isset($_SESSION['state']) && $_SESSION['state'] == 1) {
// your thanks/result page's content here;
echo 'Thanks. Transaction was successful.';
unset($_SESSION['state']);
return; // not to continue
}
// form not submitted yet
if ( false === (isset($_POST['submit']) && $_POST['submit'] = "your val")) {
require 'form.php';
return; // not to continue
}
// form submitted
require 'validate.php'; // PHP codes to validate data from POST global var.
// data are valid
if (valid($_POST)) {
// try what you aim with valid data
require 'perform_aim.php';
if (perform_aim_successful()) { // for example: record was inserted
$_SESSION['state'] = 1; // success state
header("Location: YOUR URL", TRUE, 301); // prevents reprocessing by F5 ($_POST is empty again by 301.)
exit; // exit after a redirect
}
else {
echo 'Your data was OK but script was failed. Try again later';
}
}
// invalid data
else {
print_r($err_msgs); // error messages from/by 'validate.php'
require 'form.php';
}

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']) == "")){

Using php to display welcome message on the same page using conditional statements

When the user visits the Visitor Log page, they should be able to see a prompt asking them to enter their name. Upon submitting the form, the same page should display a completely different message welcoming the user to the web page. When the user refreshes the page, the process starts over.
This is what I have tried so far, it works, but I still don't understand how I would display a whole new message after the input.
Here is the code I have I need help with only using PHP to have the correct desired result
Attempt
<?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;
}
?>
<p2 id="example-id-name" class="centered-text "></p>
<p><span class="error"></span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<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>
<?php
echo "$name";
echo "<br>";
?>
Where you're echoing name, you can check whether you have it or not and choose the message to display
<?php
if($name) {
echo "Hi $name!\n Welcome to our store!"
}
else {
echo "Please enter your name"
}
echo "<br>";
?>
You can write inline php and functions.
Code:
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}
# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}
$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = $_POST["name"] ?? "";
validate_name($name, $err);
}
?>
<!-- The form -->
<form method="post">
<label>
<input type="text" name="name" value="<?=$name ?? ""; ?>">
</label>
<!-- Show if error -->
<?php if (!empty($err)) { ?>
<span class="error">
<?=$err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php if (isset($name) && empty($err)) { ?>
<p>Hi <?=$name ?>!</p>
<p>Welcome to our store!</p>
<?php } ?>

php validation on submit when jump from one page to another

In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
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" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)

How to replace die() statement?

if(!empty($_POST))
{
if(empty($_POST['username'])) {die("Please enter a username.");}
....
Result is blank page - with the above alert.
I want to keep the form on the page. Something like:
if(empty($_POST['username']))?> <div id="info"><?php{echo "Please enter a username"};?></div>
So, just write an info, and stop the code execution from this point.
To Stop execution but you can use:
die( ' <div id="info">Please enter a username</div> ');
To allow the rest of the page to load you can use:
$errors = array();
if(empty($_POST['username'])) {
$errors[] = 'Please enter your username';
}
Then later in your html you can add
foreach($errors as $error){
echo "<div class='error'>$error</div>;
}
Rather than "stopping execution" on a single validation error, get all the errors and display them to the user:
<?php
if (!empty($_POST))
{
// validate form
$errors = array();
if (empty($_POST['username']))
{
$errors['username'] = 'Please enter a username.';
}
if (empty($_POST['address']))
{
$errors['address'] = 'Please enter an address.';
}
if (empty($errors))
{
// save to database then redirect
}
}
?>
<form>
Username:<br />
<input type="text" name="username" value="" /><br />
<?php if (!empty($errors['username'])): ?>
<div class="error">
<?php echo $errors['username'] ?>
</div>
<?php endif ?>
Address:<br />
<input type="text" name="address" value="" /><br />
<?php if (!empty($errors['address'])): ?>
<div class="error">
<?php echo $errors['address'] ?>
</div>
<?php endif ?>
</form>
Set some flag and returns/redirects to the same page. On the same page (script with form), check for the flag set and display the message.

Categories