I am new to php and web development. I am trying to do a simple validation of text field. I want to display a red remark beside the text field after submit button was clicked.
However my problem here is: The php codes validates all input field the moment the page was loaded. How to validate it only after user clicked the submit button?
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' name='name' /><br>
Email <input type='text' name='email' /><br>
Age<input type='text' name='age' /><br>
<input type='submit' name='Done' /><br><br>
</form>
<?php
if(empty($POST['name']))
echo '<font color="red">Please enter your name.</font>';
if(empty($POST['email']))
echo '<font color="red">Please enter your email.</font>';
if(empty($POST['age']))
echo '<font color="red">Please enter your age.</font>';
?>
I have several questions here:
1) If I want to display the error message right beside each text field, shall I write a separate php code beside each input field?
2) How to echo the error message only after user clicked the submit button?
I know this is extremely simply to many people here, but this is my first time doing something related to the web.
Just check if post is send
<?php
if($_POST)
{
if(empty($POST['name']))
echo '<font color="red">Please enter your name.</font>';
if(empty($POST['email']))
echo '<font color="red">Please enter your email.</font>';
if(empty($POST['age']))
echo '<font color="red">Please enter your age.</font>';
}
?>
Please note:
<input type='submit' name='Done' /><br><br>
should be outside the PHP markup.
To display the errors beside each element, just move your if statements to the place where it should be displayed in the HTML.
Most developers use javascript for form validation. A quick Google will give you a lot information about this.
Use $_SERVER['REQUEST_METHOD'] to detect whether the page is being displayed in response to posting the form.
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST['name'])) {
echo '<span style="color: red;">Please enter your name.</span>';
}
if(empty($_POST['email'])) {
echo '<span style="color: red;">Please enter your email.</span>';
}
if(empty($_POST['age'])) {
echo '<span style="color: red;">Please enter your age.</span>';
}
}
If you want to show them separately next to each input, you can write:
Name <input type='text' name='name' /> <?php
if ($_SERVER['REQUEST_METHOD'] == "POST" && empty($_POST['name'])) {
echo '<span style="color: red;">Please enter your name.</span>';
} ?><br>
Note that the variable containing POST parameters is $_POST, not $POST.
Just add a hidden input to your form.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' name='name' /><br>
Email <input type='text' name='email' /><br>
Age<input type='text' name='age' /><br>
<input type='submit' name='Done' /><br><br>
<input type="hidden" name='form' value='wasSubmited' />
</form>
Then in the PHP script check $_POST:
if ($_POST['form'] == 'wasSubmited') {
// here you can start to validate your form
}
To follow the DRY system you can simplify your code a little and make it easy to adjust in case you add more fields to your form in the future. You only have to add your new fieldname(s) to the $fields array. It is also much easier to adjust the HTML in case you want another class or something.
if(whatever condition you need)
{
$fields = array('name', 'email', 'age');
foreach ( $fields as $field ) {
if(empty($POST[$field]))
echo '<font color="red">Please enter your ' . $field . '.</font>';
}
}
}
try this i used your form working 100% =)
<script>
function ValidateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var age = document.getElementById('age').value;
if (name == "" && email == "" && age == "")
{
document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
document.getElementById("error_age").innerHTML = "Please enter your age";
return false;
}
else if (name == "")
{
document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
return false;
}
else if (email == "")
{
document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
return false;
}
else if (age == "")
{
document.getElementById("error_age").innerHTML = "Please enter your age";
return false;
}
}
</script>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onSubmit="return ValidateForm()">
Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"></span> <br>
Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"></span><br>
Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"></span><br>
<input type='submit' name='Done' /><br><br>
</form>
Here is a pure php printing the error right beside the form fields
<?php
$fieldErrors = array();
if(isset($_POST['Done']))
{
$fields = array('name', 'email', 'age');
foreach ($fields as $field)
{
if($_POST[$field] == "")
{
$fieldErrors[] = $field;
}
}
}
if(count($fieldErrors) > 0)
print_r($fieldErrors);
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("name", $fieldErrors)) ? 'Please Enter your name' :''; ?></span> <br>
Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("email", $fieldErrors)) ? 'Please Enter your email' :''; ?></span><br>
Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("age", $fieldErrors)) ? 'Please Enter your age' :''; ?></span><br>
<input type='submit' name='Done' /><br><br>
</form>
Related
Using core PHP only and nothing else, like JavaScript or clientside programming, I need PHP to check if the form's required fields are filled in or not, and display error message if missed. I need to check using procedural style programming as I'm not into OOP yet and don't understand it.
Html Form
<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>
<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>
Php Form Validator
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels_count = count($required_labels);
for($i=0; $i!=$required_labels_count; $i++)
{
if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I don't know how to complete the code here.
{
echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
}
}
?>
I know I need to check against associated array values as it would be easier and less code, but I don't know how to do it.
Notice my error echo. It's incomplete as I don't know how to write that peace of code.
How would you check with the shortest possible code using procedural style?
Anything else I need to know?
NOTE: I do not want to be manually typing each $_POST[] to check if the required ones are filled in or not. I need PHP to loop through the $required_labels[] array and check. Or if you know of any shorter way of checking without looping then I want to know.
First we will have an empty $errors array, and then we will apply the validations, and if any of them fails, we will populate the $errors.
Finally using a helper function errorsPrinter we will print the errors under their labels.
For you PHP validation part use the below code. Note that I also added the part to validate the string and int types too.
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$inputs = $_POST;
$errors = [];
foreach($required_labels as $label) {
if(!isset($inputs[$label]) || empty($inputs[$label])) {
$errors[$label] = array_merge(
["You must fill-in the field."],
$errors[$label] ?? []
);
}
}
foreach($strings_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be string"],
$errors[$label] ?? []
);
}
}
foreach($ints_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be int"],
$errors[$label] ?? []
);
}
}
function errorsPrinter($errors, $key)
{
$output = '<ul>';
if(!isset($errors[$key])) {
return;
}
foreach($errors[$key] as $error) {
$output = $output. '<li>' . $error . '</li>';
}
print($output . '</ul>');
}
?>
inside the form you can do something like this:
<form method='POST' action="">
<?php errorsPrinter($errors, 'submission_id') ?>
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<?php errorsPrinter($errors, 'website_age') ?>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<?php errorsPrinter($errors, 'url') ?>
<label for='url'>url</label>
<input type='url' name='url' id='url' >
<br>
<?php errorsPrinter($errors, 'anchor') ?>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' >
<br>
<?php errorsPrinter($errors, 'description') ?>
<label for='description'>description</label>
<input type='text' name='description' id='description' >
<br>
<?php errorsPrinter($errors, 'keyphrase') ?>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' >
<br>
<?php errorsPrinter($errors, 'keyword') ?>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' >
<br>
<button type='submit'>Search!</button>
</form>
Note that the errorsPrinter is just a helper and you can remove it and use $errors array as you want. The sample output of errors is like this:
[
"url" => ["You must fill-in the field."],
"anchor" => ["You must fill-in the field."],
"description" => ["You must fill-in the field."],
"keyphrase" => ["You must fill-in the field."],
"keyword" => ["You must fill-in the field."],
"website_age" => ["This input should be int"]
]
$errors = [];
foreach($required_labels as $field) {
if (!isset($_POST[$field]) || $_POST[$field] == '') {
$errors[$field] = "{$field} cannot be empty";
// echo "${field} cannot be empty";
}
}
And then to output those errors:
<?php
if (count($errors)) {
?>
<div id='error_messages'>
<p>Sorry, the following errors occurred:</p>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
</div>
<?php
}
And you could directly output the errors next to the input as well:
<input type="text" id="first_name" name="first_name" placeholder="First Name" />
<?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>
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.
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.
here is my code. I am not sure why after i input the first and last name the second page does not show the proper text.. The form is suppose to take in first name and last name into a text box.. Then on the next page when person submits it should validate that the proper type of data was input, and then print out text if it was not, or print out text if it was successful.
<body>
<h2 style="text-align:center">Scholarship Form</h2>
<form name="scholarship" action="process_Scholarship.php" method="post">
<p>First Name:
<input type="text" name="fName" />
</p>
<p>Last Name:
<input type="text" name="lName" />
</p>
<p>
<input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send Form" />
</form>
my second form
<body>
<?php
$firstName = validateInput($_POST['fName'],"First name");
$lastName = validateInput($_POST['lName'],"Last name");
if ($errorCount>0)
echo <br>"Please use the \"Back\" button to re-enter the data.<br />\n";
else
echo "Thank you for fi lling out the scholarship form, " . $firstName . " " . $lastName . ".";
function displayRequired($fieldName)
{
echo "The field \"$fieldName\" is required.<br />n";
}
function validateInput($data, $fieldName)
{
global $errorCount;
if (empty($data))
{
displayRequired($fieldName);
++$errorCount;
$retval = "";
}
else
{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
$errorCount = 0;
?>
</body>
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
}