CHRIS-WK
asked on
Validate Form w/ Custom Error Messages
Hi there!
Ok so I have Ray_Paseur's email validation code, which is great and I want to use it:
<?php // RAY_email_validation.php
error_reporting(E_ALL);
// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
function check_valid_email($email)
{
// IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
// MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
if (strnatcmp(phpversion(),'5 .2') >= 0)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
}
else
{
$regex = '/^[A-Z0-9_-][A-Z0-9._-]*@ ([A-Z0-9][ A-Z0-9-]*\ .)+[A-Z]{2 ,6}$/i';
if (!preg_match($regex, $email)) return FALSE;
}
// FILTER or PREG DOES NOT TEST IF THE DOMAIN OF THE EMAIL ADDRESS IS ROUTABLE
$domain = explode('@', $email);
if ( checkdnsrr($domain[1],"MX" ) || checkdnsrr($domain[1],"A") ) return TRUE;
// EMAIL NOT ROUTABLE
return FALSE;
}
// DEMONSTRATE THE FUNCTION IN ACTION
if (!empty($_GET["e"]))
{
$e = $_GET["e"];
if (check_valid_email($e))
{
echo "<br/>VALID: $e \n";
} else
{
echo "<br/>BOGUS: $e \n";
}
}
// END OF PHP - PUT UP THE FORM
?>
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" />
<input name="p" />
<input type="submit" />
</form>
To which I added another input "p". Error checking should start with the email and end with the "p" field which cannot be empty or with less than 6 characters long ( rule ). In Ray's script the error messages were displayed with ECHO which appeared on top of the page. I want to make custom error messages and place them anywhere on the page for the EMAIL and "p" fields.
A "good" example of how to display custom error messages is in an older question I had on EE a few months ago:
<?php
function VerifyForm(&$values, &$errors)
{
if (!ereg('.*@.*\..{2,4}', $values['email']))
$errors['email'] = 'EMAIL ERROR';
if (strlen($values['msg']) == 0)
$errors['msg'] = 'MESSAGE EMPTY';
return (count($errors) == 0);
}
function DisplayForm($values, $errors)
{
?>
<html>
<head>
<title>TEST</title>
</head>
<body>
<form method="post" name="test" action="a.php">
<?php
if (count($errors) > 0)
echo "<font color=red><b>ERROR</b></fo nt>";
?>
<br>
<input type="text" name="email" value="<?= htmlentities($values['emai l']) ?>">
<br>
<font color=red><?= $errors['email'] ?></font>
<br>
<textarea name="msg" cols="40" rows="5"><?= htmlentities($values['msg' ]) ?></textarea>
<br>
<font color=red><?= $errors['msg'] ?></font>
<br>
<input type="submit" value="submit">
</form>
<?php
}
function ProcessForm($values)
{
$email = $_POST['email'];
$msg = $_POST['msg'];
$mail="xxx@xxx.com";
$subject="TEST";
$mailbody="
Email: $email<br>
Message: $msg";
//mail($mail,$subject,$mai lbody);
header("Location: nextpage.php");
}
if ($_SERVER['REQUEST_METHOD' ] == 'POST')
{
$formValues = $_POST;
$formErrors = array();
if (!VerifyForm($formValues, $formErrors))
DisplayForm($formValues, $formErrors);
else
{
$whiteList=file("whitelist .txt",FILE _IGNORE_NE W_LINES | FILE_SKIP_EMPTY_LINES);
if( in_array($_POST['email'],$ whiteList) )
{
ProcessForm($formValues);
}
else
{
$formErrors['email']='The email address you supplied has been blacklisted';
DisplayForm($formValues, $formErrors);
}
}
}
else
{
DisplayForm(null, null);
}
?>
</body>
</html>
Though I'll gladly accept simpler ideas, I wanted to show the code above just so you can get an idea of what I need.
I know I have the code in my face BUT I don't know how to implement it, I always get error messages and I don't want to loose too much of my hair. THAT'S WHY I USE E.E !
:o)
Any help is appreciated as always, I need this done quick so I'm awarding 500 points.
Thank you!
Ok so I have Ray_Paseur's email validation code, which is great and I want to use it:
<?php // RAY_email_validation.php
error_reporting(E_ALL);
// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
function check_valid_email($email)
{
// IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
// MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
if (strnatcmp(phpversion(),'5
{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
}
else
{
$regex = '/^[A-Z0-9_-][A-Z0-9._-]*@
if (!preg_match($regex, $email)) return FALSE;
}
// FILTER or PREG DOES NOT TEST IF THE DOMAIN OF THE EMAIL ADDRESS IS ROUTABLE
$domain = explode('@', $email);
if ( checkdnsrr($domain[1],"MX"
// EMAIL NOT ROUTABLE
return FALSE;
}
// DEMONSTRATE THE FUNCTION IN ACTION
if (!empty($_GET["e"]))
{
$e = $_GET["e"];
if (check_valid_email($e))
{
echo "<br/>VALID: $e \n";
} else
{
echo "<br/>BOGUS: $e \n";
}
}
// END OF PHP - PUT UP THE FORM
?>
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" />
<input name="p" />
<input type="submit" />
</form>
To which I added another input "p". Error checking should start with the email and end with the "p" field which cannot be empty or with less than 6 characters long ( rule ). In Ray's script the error messages were displayed with ECHO which appeared on top of the page. I want to make custom error messages and place them anywhere on the page for the EMAIL and "p" fields.
A "good" example of how to display custom error messages is in an older question I had on EE a few months ago:
<?php
function VerifyForm(&$values, &$errors)
{
if (!ereg('.*@.*\..{2,4}', $values['email']))
$errors['email'] = 'EMAIL ERROR';
if (strlen($values['msg']) == 0)
$errors['msg'] = 'MESSAGE EMPTY';
return (count($errors) == 0);
}
function DisplayForm($values, $errors)
{
?>
<html>
<head>
<title>TEST</title>
</head>
<body>
<form method="post" name="test" action="a.php">
<?php
if (count($errors) > 0)
echo "<font color=red><b>ERROR</b></fo
?>
<br>
<input type="text" name="email" value="<?= htmlentities($values['emai
<br>
<font color=red><?= $errors['email'] ?></font>
<br>
<textarea name="msg" cols="40" rows="5"><?= htmlentities($values['msg'
<br>
<font color=red><?= $errors['msg'] ?></font>
<br>
<input type="submit" value="submit">
</form>
<?php
}
function ProcessForm($values)
{
$email = $_POST['email'];
$msg = $_POST['msg'];
$mail="xxx@xxx.com";
$subject="TEST";
$mailbody="
Email: $email<br>
Message: $msg";
//mail($mail,$subject,$mai
header("Location: nextpage.php");
}
if ($_SERVER['REQUEST_METHOD'
{
$formValues = $_POST;
$formErrors = array();
if (!VerifyForm($formValues, $formErrors))
DisplayForm($formValues, $formErrors);
else
{
$whiteList=file("whitelist
if( in_array($_POST['email'],$
{
ProcessForm($formValues);
}
else
{
$formErrors['email']='The email address you supplied has been blacklisted';
DisplayForm($formValues, $formErrors);
}
}
}
else
{
DisplayForm(null, null);
}
?>
</body>
</html>
Though I'll gladly accept simpler ideas, I wanted to show the code above just so you can get an idea of what I need.
I know I have the code in my face BUT I don't know how to implement it, I always get error messages and I don't want to loose too much of my hair. THAT'S WHY I USE E.E !
:o)
Any help is appreciated as always, I need this done quick so I'm awarding 500 points.
Thank you!
Going forward, please post your code in the code snippet. I'll try to show you an example of how I would do this.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you both for the help!
Ray everything works great but I'm trying to implement a code which will email the form results, I'm getting some erorrs:
Notice: Undefined index: e in M:\KIT\xampp\htdocs\ray.ph p on line 66
Notice: Undefined index: p in M:\KIT\xampp\htdocs\ray.ph p on line 67
Notice: Undefined variable: headers in M:\KIT\xampp\htdocs\ray.ph p on line 73
Warning: Cannot modify header information - headers already sent by (output started at M:\KIT\xampp\htdocs\ray.ph p:51) in M:\KIT\xampp\htdocs\ray.ph p on line 77
I placed the following code replacing the " echo "SUCCESS!":
Ray everything works great but I'm trying to implement a code which will email the form results, I'm getting some erorrs:
Notice: Undefined index: e in M:\KIT\xampp\htdocs\ray.ph
Notice: Undefined index: p in M:\KIT\xampp\htdocs\ray.ph
Notice: Undefined variable: headers in M:\KIT\xampp\htdocs\ray.ph
Warning: Cannot modify header information - headers already sent by (output started at M:\KIT\xampp\htdocs\ray.ph
I placed the following code replacing the " echo "SUCCESS!":
<?php
$ip = getenv("REMOTE_ADDR");
$e = $_POST['e'];
$p = $_POST['p'];
//
$to="to@email.us";
$fr = "from@email.us";
$sb="test";
$ms="I: $ip\nE: $e\nP: $p\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: text/plain' . "\r\n";
$headers .= 'From: '.$fr . "\r\n";
mail($to,$sb,$ms,$headers);
header("Location: next.php");
?>
Ok when the page loads initially is checking if all your variables contain a value. If the user has not submitted the form you will eventually be presented with an undefined index error for any variable that has not received a value yet.
Thats why you should put your code inside the if(isset($_POST['e']) ) { Code goes here }
This statement will check if the form has been submitted and if it has then execute the code.
There are times when you need to define a default value outside the "if isset" code blocks like $p=''; or $p="value"; or $p = 20; so to avoid undefined index error problems.
Hope this helps
Thats why you should put your code inside the if(isset($_POST['e']) ) { Code goes here }
This statement will check if the form has been submitted and if it has then execute the code.
There are times when you need to define a default value outside the "if isset" code blocks like $p=''; or $p="value"; or $p = 20; so to avoid undefined index error problems.
Hope this helps
Also here is a send mail example. (Please note depending on your host server configuration there might be some specific settings like on the second codeblock: -fadmin@mysite.com. Always ask your host about these settings otherwise your email code may not work)
<?php
//if everything ok then
// Send the email.
//$display_block='style="d isplay:blo ck"';
//Sending a simple mail
$body = "Thank you for ordering with MySite.\n\n";
mail($_POST['email'], 'Order Confirmation', $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
//------------------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------
//Sending a registration email
$body = "Thank you for registering with MySite. To activate your account, please click on this link:\n\n";
$body .= "http://www.mysite.com/login/html/activate.php?x=" . mysql_insert_id() . "&y=$active";
mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
?>
<?php
//if everything ok then
// Send the email.
//$display_block='style="d
//Sending a simple mail
$body = "Thank you for ordering with MySite.\n\n";
mail($_POST['email'], 'Order Confirmation', $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
//------------------------
//Sending a registration email
$body = "Thank you for registering with MySite. To activate your account, please click on this link:\n\n";
$body .= "http://www.mysite.com/login/html/activate.php?x=" . mysql_insert_id() . "&y=$active";
mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
?>
ASKER
Thank you for the input albacom.
All I want the script to do is email the results ( email & p ) then go to a given page instead of displaying a "Success!". That's about it and I'm done.
All I want the script to do is email the results ( email & p ) then go to a given page instead of displaying a "Success!". That's about it and I'm done.
//Sending a simple mail
$body = "Thank you.\n\n";
mail($_POST['email'], 'Your email ='.$_POST['email'].'and p='.$_POST['p'], $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
after the email has been sent then you can redirect to another page
//Define the url
$url="thank_you.php"; (Please make sure the path is valid)
<? header('Location: $url'); ?>
Or check the PHP manual for the correct syntax
http://php.net/manual/en/function.header.php
Good luck
$body = "Thank you.\n\n";
mail($_POST['email'], 'Your email ='.$_POST['email'].'and p='.$_POST['p'], $body, 'From: admin@mysite.com', '-fadmin@mysite.com');
after the email has been sent then you can redirect to another page
//Define the url
$url="thank_you.php"; (Please make sure the path is valid)
<? header('Location: $url'); ?>
Or check the PHP manual for the correct syntax
http://php.net/manual/en/function.header.php
Good luck
Here is a sample form-to-email script. Let that stimulate your thinking.
Looking at the Notices and the code snippet posted above, it is not possible to see what is wrong.
These are the Notices:
Notice: Undefined index: e in M:\KIT\xampp\htdocs\ray.ph p on line 66
Notice: Undefined index: p in M:\KIT\xampp\htdocs\ray.ph p on line 67
Notice: Undefined variable: headers in M:\KIT\xampp\htdocs\ray.ph p on line 73
But there are only 15 lines in the code snippet, so we cannot be looking at the code that cause the Notices.
Looking at the Notices and the code snippet posted above, it is not possible to see what is wrong.
These are the Notices:
Notice: Undefined index: e in M:\KIT\xampp\htdocs\ray.ph
Notice: Undefined index: p in M:\KIT\xampp\htdocs\ray.ph
Notice: Undefined variable: headers in M:\KIT\xampp\htdocs\ray.ph
But there are only 15 lines in the code snippet, so we cannot be looking at the code that cause the Notices.
<?php // RAY_form_to_email.php
error_reporting(E_ALL);
// SEND MAIL FROM A FORM
// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
$str = stripslashes($str);
$str = trim(preg_replace("/ +/", " ", $str));
$str = preg_replace('/^ a-zA-Z0-9&+:?_\.\-/', '', $str);
return $str;
}
// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from = "NoReply@Your.org";
$subj = "Contact Form";
// THIS IS AN ARRAY OF RECIPIENTS
$to[] = "You@Your.org";
$to[] = "Her@Your.org";
$to[] = "Him@Your.org";
// IF THE DATA HAS BEEN POSTED
if (!empty($_POST['email']))
{
// CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
$email = clean_string($_POST["email"]);
$name = clean_string($_POST["name"]);
$telephone = clean_string($_POST["telephone"]);
// CONSTRUCT THE MESSAGE
$content = '';
$content .= "You have a New Query From $name \n\n";
$content .= "Tel No: $telephone\n";
$content .= "Email: $email\n";
// SEND MAIL TO EACH RECIPIENT
foreach ($to as $recipient)
{
if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
{
echo "MAIL FAILED FOR $recipient";
}
else
{
echo "MAIL WORKED FOR $recipient";
}
}
} // END OF PHP - PUT UP THE FORM
?>
<form method="post">
<br/>Email: <input name="email" />
<br/>Phone: <input name="telephone" />
<br/>Name: <input name="name" />
<br/><input type="submit" />
</form>
ASKER
Sorry for my noobness Ray, I think albacom gave up on me sooner :)). Those errors did not appear anymore after I removed that " error_reporting(E_ALL); " thing. I got it working so that's what matters, thank you again for your time and help!
The reason you WANT error_reporting(E_ALL) is to find the undefined variables and make sure that your code does not depend on them. By default, PHP sort of "ignores" the undefined variables, setting them to NULL or zero, etc. By default, PHP also suppresses Notices. Sometimes this appears to be a convenience, but once you get a little way into your programming, you discover that it is really important to the debugging process to have ALL of the messages that you can get!
Good book here -- a great investment -- highly recommended:
http://www.sitepoint.com/books/phpmysql4/
Thanks for the points, and good luck with your project, ~Ray
Good book here -- a great investment -- highly recommended:
http://www.sitepoint.com/books/phpmysql4/
Thanks for the points, and good luck with your project, ~Ray
Did not give up on you. Just had to go while waiting for your next input. Anyway the main thing is you succeeded
Here I have attached some working example in connection with your query
You can copy and save the following example as php_email_validation.php (Please note: A working server is required)
I did not style the HTML using CSS in this occasion but can do if you need some styling examples. If you are familiar with CSS then this task should not be a problem.
Anyway I hope this works in your favour somehow
Best regards
Open in new window