I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.
Related
I am trying to make a login system and i want to create a conditional statement that checks whether the global variable $_POST['submit-form'] is set.
If the global variable $_POST['submit-form'] is set then i want to echo out the fields of the submitted forms. This works fine..
The problem comes when i want to check whether the global variable $_POST['submit-form'] is empty, i get a blank page when i submit the form with nothing. It is supposed to echo out something like "You have entered nothing, please try again'.
I don't know what is wrong.
This is the code for the form.
<form action="test-form2.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" name="submit-form" value="submit">
</form>
..and this is the code for the form handler.
<?php
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
// header('refresh=3;url = /test-form1.php');
}
?>
Your $_POST always have submit-form (and it's always not empty), so if statement always returns true. Try to check (for example) only that $_POST['name'] and $_POST['email'] are not empty.
The problem with your code is that checking if it's set isn't enough .. Because it may be set and be empty -- Realistically what you want is to check both isset and whether it's empty IE:
if (isset($_POST['submit-form'] && $_POST['submit-form'] != '' && $_POST['submit-form'] != null)
If the above if statement fails your value for $_POST['submit-form'] is most likely not being submitted.
UPDATE
Check for blank fields
if ($_POST['name'] != '' && $_POST['email'] != ''){
// Do stuff
}else{
if ($_POST['name'] == ''){
echo "name is empty";
}
if ($_POST['email'] == ''){
echo "email is empty";
}
}
That's because isset($_POST['submit-form']) returns true even if you don't input anything in Name and E-mail fields, it's value would be submit string when hit submit button to submit the form. This is the reason else part of below block is not getting executed.
if(isset($_POST['submit-form'])) {
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
Use var_dump($_POST); to see the complete array structure. having said these, you can use the following snippet to achieve the desired result,
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}else{
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
}
Validation and scrutinization of user inputs should be your next action items in the list.
I have some if statements validating email addresses submitted to my form below. However the form submits even though not all the if conditions below are met. The one it seems to respect is the filter_var condition. Why would it do this? the validation that is failing is the last if statement saying the email is unreachable. on the form it says the email address is unreachable. but it submits the form by email anyways. $scrubbed is a function I use in my form to clean the form fields from possible spam
if (isset($scrubbed["email"])) {
if (strlen($scrubbed["email"]) > 254) {
echo "<p>The email address is too long: it must be 254 or less.</p>";
}
// Validate syntax with PHP.
if ((($email = filter_var($scrubbed["email"], FILTER_VALIDATE_EMAIL)) === false)) {
echo "<p>The email address has an invalid syntax.</p>";
}
// Validate DNS reachability.
$host = substr($email, strrpos($email, "#") + 1) . ".";
if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
echo "<p>The email address is unreachable.</p>";
}
}
It would be nice if you accept the answers to your questions.
$scrubbed["email"] is simply empty and therefor the email is always invalid.
Let's create a simple form that will be submitted to us.
<!doctype html>
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
/**
* Validate submitted email address.
*
* #return null|string
* Returns <code>NULL</code> if the email address is valid, if the
* email address is invalid a string explaining the problem is returned.
*/
function validate_email() {
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email === false) {
return "The email address has an invalid syntax.";
}
if (strlen($email) > 254) {
return "The email address is too long: it must be 254 or less.";
}
$host = substr($email, strrpos($email, "#") + 1) . ".";
if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
return "The email address is unreachable.";
}
}
// Check if we were called via POST.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate the email address and display the error message (if any).
if (($error = validate_email())) {
echo "<p>{$error}</p>";
}
// Otherwise let the user know that everything is okay.
else {
echo "<p>The email address is valid, not too long, and reachable.</p>";
}
}
?>
<form action="/" method="post" accept-charset="utf-8">
<input type="email" name="email">
<input type="submit">
</form>
</body>
</html>
Please note that this is only some code for illustration purposes and has nothing to do with proper software design, re-usability, … well anything that is part of good software.
In this script I am checking if fields are not empty and email address is syntactically correct. How to add a text input at the bottom of my form for a basic sum question, e.g. (2+5)= I want to add a validation element to my current script to check if this equals 7.
if (empty($name) || empty($phone) || empty($email) || empty($enquiry))
{
echo " * Sorry all fields are required.";
}
elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email))
{
print "<p>Sorry the email address you entered looks like it's invalid.</p>";
}
else
{
mail($to, $sub, $mes, $headers);
print "<p>Thank you ".$name." for contacting us.<br /><br />We will be in touch shortly.</p>";
}
If you are just wanting to validate a static sum, e.g. you know it is always going to be ( 2 + 5 ) = 7
Then you could just write a simple function to check the posted value.
// this being your posted value;
$validate = 7;
function SumCheck($value){
if ( 2 + 5 == $value ){
return true;
}
else{
return false;
}
}
Then change your initial line to;
if (empty($name) || empty($phone) || empty($email) || empty($enquiry) || !SumCheck($validate))
However, I would suggest using RECAPTCHA as Robert Podwika has suggested.
1 If your session is not started use in the very first line
session_start();
2 Before form is shown. Add this code. Also remember that session start must be also in file where validation is.
$numa = rand(1,5);
$numb = rand(0,4);
$_SESSION['valid_res'] = $numa+$numb;
echo "<p>To submit form please solve this equatation $numa + $numb = ?";
echo '<input type="text name="result_val" />';
3 In validation functions you should check
if(intval($_POST['resul_val']) != $_SESSION['valid_res'])
{
echo "sorry you put wrong result in validation form";
}
However, if I were you I'd use RECAPTCHA
I am trying to wrap up this contact/quote form which has same page validation but external processing. I have set up a variable to go in the form action and the variable/url changes from the same page to the processing page when the form validates. However, it is taking two clicks on the submit button to process the form after all the required fields have been filled in: All the required fields will be filled in, I click submit, the page reloads with the saved data variables and then when I hit submit agin, it finally goes through, sending the email and loading the thankyou page. I have searched the posts here and tried multiple things but have not found a solution. I am definitely not a php expert, still a newbie so this may not be the best way to accomplish this but I'd appreciate any ideas on how to finish this up. Here is what I have:
<?php
....
if (empty($Name) && empty($Company) && empty($Address1) && empty($City) && empty($State) && empty($Phone))
{
echo '<p class="tan">The fields marked with an * are required.</p>';
$Process = 'samepageurl';
}
/*else if (empty($Name) || is_numeric($Name))
{
echo '<p class="tan"><b>Please enter your name.</b></p>';
}*/
else if (empty($Company) || is_numeric($Company))
{
echo '<p class="tan"><b>Please enter your company name.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Address1) || is_numeric($Address1))
{
echo '<p class="tan"><b>Please enter your address.</b></p>';
$Process = 'samepageurl';
}
else if (empty($City) || is_numeric($City))
{
echo '<p class="tan"><b>Please enter your city.</b></p>';
$Process = 'samepageurl';
}
else if (empty($State) || is_numeric($State))
{
echo '<p class="tan"><b>Please enter your state.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Phone) || ctype_alpha($Phone))
{
echo '<p class="tan"><b>Please enter your phone number.</b></p>';
$Process = 'samepageurl';
}
else if (strlen($Phone) < 10 || strlen($Phone) > 12 || ctype_alpha($Phone) || ctype_space($Phone))
{
echo '<p class="tan"><b>Please enter a phone number with an area code.</b></p>';
$Process = 'samepageurl';
}
else if (isset($Name) && isset($Company) && isset($Address1) && isset($City) && isset($State) && isset($Phone))
{
$Process = 'processingurl';
}
?>
<form action="<?php echo $Process; ?>" method="post" class="print" >
<p><input type="hidden" name="recipient" value="responses#url.com"/>
<input type="hidden" name="subject" value="Web Site Response"/>
<input type="hidden" name="redirect" value="thankyou.html"/></p>
... form fields ...
</form>
Thank you in advance!
First check for missing variables, then extract and validate the variables, then serve content based on them.
<?php
function verifyPostContains(&$req) {
global $_POST;
$missing = array();
foreach($req as $var => $_) {
if(!isset($_POST[$var])) {
$missing[] = $var;
}
}
return $missing;
}
$requirements = array('name'=>'','city'=>'','state'=>'',...);
$missing = verifyPostContains($requirements);
if(count($missing)>0) {
$content = formErrorReport($missing);
sendHeaders();
echo $content;
exit();
}
// extract, making sure to sanitize
$name = sanitize($_POST["name"]);
...
$errorHtml = array();
// validate by reference. Effectively call testName($name).
if(failsValidation($name, "testName")) {
$errorHtml [] = generateError(NAME_ERROR, $name);
} else { $requirements["name"] = $name; }
if(failsValidation($city, "testCity")) {
$errorHtml [] = generateError(CITY_ERROR, $city);
} else { $requirements["city"] = $name; }
...
if(count($errorHTML)>0) {
generateErrorPage($requirements, $missing, $errorHTML);
} else { processForm($requirements); }
?>
this code assumes you have functions to do the various bits that need to be done, and has some string constants for generating error HTML.
As a newcomer you may want to google for some tutorials that explain doing form processing using PHP at the server, and JavaScript at the client. If you find a tutorial that gives you code that echos errors while it's testing the data, such as you code does, move along. It's not a good tutorial. If you find one that stops after it finds one error, move along too. If you find one that tells you to make sure the values are right in JavaScript, and then says "we already validated this at the client so we use the values directly in PHP", move along, too. Look for a tutorial that explains:
ensuring there's data in all the form fields, using JavaScript, so the submit button is disabled until there's data for all the fields.
ensuring the data matches your criteria, in PHP, so that people who just POST to your server without ever using your page don't get away with injecting all manner of fun stuff they weren't supposed to be able to do
you generate a page with all the errors explained, if there are any, and the form repopulated with the wrong data, but highlighted as wrong
you process the post request if there are no errors.
(Bonus points if the tutorial explains that a POST request is not required to actually ever generate page content as a response, other than a header that indicates whether or not the POST call was accepted or rejected.)
I have a rough php script that sees if a user has filled in the html form input after they have clicked submit. I am having a problem with getting isset() and is_string() to work. If I use isset() the form is emailed even if the form inputs are left blank, is_string() throws an error messages even if the form input are filled in. I have tried !isset() and that still sends blank input. The only thing working is if I use == NULL. At this moment in time I am not going to validate the input as I am trying to understand why this isn't working as I am pretty new to PHP.
$subject = "Feedback from Your Website.";
$email = ($_POST['email']);
$name = ($_POST['name']);
$message = ($_POST['feedback']);
if (isset($_POST["name"]))
{
//send message
mail($subject, $name, $email, $message);
}
else
{
//error message
echo "Please do not miss out any fields";
}
I also tried:
if (isset($_POST["name"], $_POST['email']))
{ }
if (isset($name, $email))
{ }
if (is_string($name || $email))
{ }
But all failed, so far all that's working is:
if ($name == NULL || $email == NULL || $message == NULL)
{ }
Thank you in advance.
Try to use empty(). This function return TRUE if a variabile is empty or non set, FALSE otherwise.
if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["feedback"]))
{
//error message
echo "Please do not miss out any fields";
}
else
{
//send message
mail($subject, $name, $email, $message);
}
is_string($name || $email) is not working because $name || $email is cast to a boolean and a boolean is not a string.
isset() function will return a True value after your form submitting. Actually, your field has been sent to your target file. So your code will send emmial. For what you need, you must use the code below:
if (isset($_POST["name"]) && $_POST["name"] != '') {
// do something
}
isset checks if value is created in the array. It IS going to be there always as the form always have the same fields, empty or not. You need to check their content
isset() returns true because $_POST['email'] has been set. It simply is empty. Since you submit the form all the variables of the form have been set.
You have to write this
if (isset($_POST["email"]) && $_POST["email"] != '')
How about empty( ) you can check the details of the function in te php manual .