 |
| Beginning PHP Beginning-level PHP discussions. More advanced coders should post to the Pro PHP forum. |
Welcome to the p2p.wrox.com Forums.
You are currently viewing the Beginning PHP section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
|
|
|
|

July 3rd, 2003, 11:18 AM
|
|
Registered User
|
|
Join Date: Jul 2003
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Form validation and email checking
Hi,
I know its basic but this is doing my head in a bit.
Any help please!
************************************************** **
___________
HTML STUFF
___________
<?php
if ($submit){
if (!$email || BLAH || !$eCheck)
{
$error = "Required Fields Missing (*)!";
$error1 = "(*)";
}
else {
echo "<fieldset><legend>Application Received</legend><div align=\"center\"><span class=\"thanx\">
Thank you for your application.
We will contact you shortly.
</span></div></fieldset>
";
}
}
if (!$submit || $error) {
echo "<div align=\"center\"><span class=\"red\">$error</span></div>";
?>
____
Form stuff
____
//////////////////////////////////////////////////////////////////////
// Problem lies below somewhere I guess!
// On submit if email is varified
// It doesn't assign the $eCheck variable, until next submit
// Hence you have to enter submit twice
// I am stumped! And been at it for far too long- Any ideas!
// All I wanted to do was validate the form, check the email and submit the page
//////////////////////////////////////////////////////////////////////
<?php
if ($email!="" && (!eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))) { echo "Invalid E-Mail address!";
}
if ($email!="" && (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))) { $eCheck = "correct";
}
?>
</span>
</span>
</div>
</fieldset>
<input name="eCheck" type="hidden" id="eCheck" value="<?php echo $eCheck ?>" />
___________________
REST OF FORM STUFF
___________________
REST IF THE HTML
___________________
Any help greatly appreciated, cheers
Ashley:(
|
|

July 3rd, 2003, 02:05 PM
|
|
Friend of Wrox
|
|
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
First of all, I strongly suggest you rewrite your site and turning register_globals = off. For development, use error_reporting = E_ALL. For more info, read my register_globals FAQ in the archives:
http://p2p.wrox.com/archive/beginnin...2002-11/17.asp
That said, the best way to figure out your problem is to draw it out. Get a whiteboard or pencil and paper. Write all your variables out. Trace through your own execution and check the following for each variable:
1) Where do I access its value?
2) Where is the value set?
3) Are there any conditions that prevent the variable from being set?
4) Are these conditions valid?
In your code, eCheck is ONLY set if !$submit, and if eregi() returns true.
Speaking of, you perform the exact same regex match twice -- that's a lot of overhead. Why not instead do this:
if (($email != "") && (ereg(...)))
{
$eCheck = 'correct';
}
else
{
echo "invalid email."
}
See how much cleaner that is?
Hope this helps, I didn't have enough time to look too closely at your code to debug it myself.
Take care,
Nik
http://www.bigaction.org/
|
|

July 4th, 2003, 06:57 AM
|
|
Registered User
|
|
Join Date: Jul 2003
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Solution was the conditionals, what looking for and where!
Code below to see.
Cheers all for considerations and sugguestions.
<?php
// Check if form Submitted
if (isset($_POST['submit'])){
// Check if form field are completed
if (!$borrow || !$over || !$property_value || !$outstanding_mortgage || !$applicant1_name || !$address || !$town_city || !$postcode || !$home_tel || !$work_tel || !$mob_tel || !$time_call || !$call_my || !$email || !$app1_am || !$app1_earn)
{
$error = "Required Fields Missing (*)!";
$error1 = "(*)";
}
// Check if email exists and Varify its syntax
if (isset($_POST['email']) && (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $_POST['email'])) && !$error && !$error2)
{
echo "<fieldset><legend>Application Recieved</legend><div align=\"center\"><span class=\"thanx\"><br />Thank you for your application.<br />We will contact you shortly.<br /><br /></span></div></fieldset><br />";
}
// There is an Email AND not valid
elseif (($_POST['email']) && !(eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $_POST['email'])))
{
$error2 = "Invalid E-Mail address!";
}
}
// Check not submited or ruturned error MSG
if (!$submit || $error)
{
echo "<div align=\"center\"><span class=\"red\">$error</span></div>";
?>
FORM HERE
<?php
}
?>
|
|

July 7th, 2003, 02:21 PM
|
|
Friend of Wrox
|
|
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Again, you're performing the exact same email ereg twice, once for an if and once for an else if. This is a costly, inefficient, and totally unnecessary step.
Your code can be rewritten much more efficiently without loss of functionality by being a bit more careful with your flow of control.
Also, you're using $_POST['submit'] to check whether the form was submitted, but are still relying on globals for the rest of the form values... is there a reason for this? The best thing you can do is be extremely strict about register_globals. You're opening holes in your site by assuming that if $submit came from $_POST, then everything else did, too.
Take care,
Nik
http://www.bigaction.org/
|
|

July 7th, 2003, 04:30 PM
|
|
Registered User
|
|
Join Date: Jul 2003
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
<?php
// Check if form Submitted
if (isset($_POST['submit'])){
// Check if form field are completed
if (!$borrow || !$over || !$property_value || !$outstanding_mortgage || !$applicant1_name || !$address || !$town_city || !$postcode || !$home_tel || !$work_tel || !$mob_tel || !$time_call || !$call_my || !$email || !$app1_am || !$app1_earn || ($over=="") || ($time_call=="Please Select") || ($call_my=="Please Select") || ($app1_am=="Please Select"))
{
$error = "Required Fields Missing (*)!";
$error1 = "(*)";
}
// Check if email exists and Varify its syntax
if (isset($_POST['email']) && (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $_POST['email'])) && !$error && !$error2)
{
// is varified so report form submitted
echo "<fieldset><legend>Application Received</legend><div align=\"center\"><span class=\"thanx\"><br />Thank you for your application.<br />We will contact you shortly.<br /><br /></span></div></fieldset><br />";
// Mail form to us
$mail_to = "EMAIL HERE";
$mail_subject = "Application";
$mail_body = "<html>\n";
$mail_body .= "<head>\n";
$mail_body .= "<title>Application</title>\n";
$mail_body .= "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>\n";
$mail_body .= "</head>\n";
$mail_body .= "<body bgcolor='#FFFFFF' text='#A6A4BA'>\n";
$mail_body .= "<table width='468' border='0' cellspacing='0' cellpadding='0' bordercolor='#A6A4BA' bgcolor='#FFFFFF' align='center'>\n";
$mail_body .= "<tr>\n";
$mail_body .= "<td bgcolor='#FFFFFF'><img src='http://my-site/img/email/email_banner.gif' width='468' height='60'></td>\n";
$mail_body .= "</tr>\n";
$mail_body .= "</table>\n";
$mail_body .= "<table width='468' border='0' cellspacing='0' cellpadding='1' bgcolor='#A6A4BA' align='center'>\n";
$mail_body .= "<tr><td>\n";
$mail_body .= "<table width='100%' border='0' cellspacing='0' cellpadding='10' bgcolor='#FFFFFF' align='center'>\n";
$mail_body .= "<tr>\n";
$mail_body .= "<td bgcolor='#FFFFFF'>\n";
$mail_body .= "<strong><em><h3>Application details.</h3></em></strong><br />\n\n";
// rest of form to be mailed in here!!
$mail_body .= "<strong>I earn:</strong> $app2_earn <br /><br />\n\n";
$mail_body .= "</td>\n";
$mail_body .= "</tr>\n";
$mail_body .= "</table></td></tr></table>\n";
$mail_body .= "</body>\n";
$mail_body .= "</html>\n";
$header = "From: $email\r\n";
$header .= "Reply-To: $email\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$header .= "X-Priority: 3\r\n";
mail($mail_to, $mail_subject, $mail_body, $header);
}
// There is an Email AND not valid
elseif (($_POST['email']) && !(eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $_POST['email'])))
{
$error2 = "Your E-Mail address is Invalid!";
}
}
// Check not submited or ruturned error MSG
if (!$submit || $error || $error2)
{
echo "<div align=\"center\"><span class=\"red\">$error $error2</span></div>";
?>
FORM BLAH BLAH
?>
I am doing the check twice so as to report seperate error messages via variables in the form.
I haven't found any other way to do this.
I don't understand the 'your relying on globals for the rest of the variabls?!
I don't know any other way to do so!
I don't get this 'assuming that if $submit came from $_POST, then everything else did, too'
Some sugguestions and examples would be great.
nikolai I get that this is wrong in your eyes and so I guess it must be as I am very new to PHP, but as such
am not quite following what you are saying.
My code above is how I have it now. If you can show me how to amend this It will be a great learning action for me
and anyone else who is reading this thread and having the same issue I am.
Thanks for your comments
Ashley
|
|

July 8th, 2003, 02:48 PM
|
|
Friend of Wrox
|
|
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Okay, I've kinda rewritten your code to illustrate what I feel is an effective use of $_POST, arrays, flags, etc... This code should work with register_globals = off and error_reporting = E_ALL; that is, that no variables are ever used without being initialized, and at no point is the origin of a variable unknown or assumed.
I added links to the PHP manual pages for all the built-in functions I used in this code, as well as some of the trickier statements, like using the empty bracket syntax to append to an array ($arr[] = val).
Code:
<?php
// setup error variables.
$error = false; // This boolean value (flag) marks whether an error
// has been encountered.
$error_marker = '*'; // use $error_marker when generating a required form
// field that was not filled in the first time around.
// This means that if you decide later to change your
// error marker (for example, to the string
// "REQUIRED!"), you only need change this line.
$error_texts = array(); // the error_texts array will hold all error
// messages to be displayed to the user.
// currently, your only error messages are
// "Required fields missing!" and
// "Invalid email address!", but doing it this way
// gives you the flexibility to add additional
// or more descriptive error messages in the future.
// http://www.php.net/function.array
// Check if form Submitted
if (!isset($_POST['submit']))
{
$error = true;
$error_texts[] = "Form not submitted!"; // http://www.php.net/types.array
}
else // form submitted
{
// set up all the expected (required) POST form fields.
$fields = array('borrow', 'over', 'property_value', 'outstanding_mortgage',
'applicant1_name', 'address', 'town_city', 'postcode',
'home_tel', 'work_tel', 'mob_tel', 'time_call', 'call_my',
'email', 'app1_am', 'app1_earn');
// set up all the default (unacceptable) values for POST form fields.
$defaults = array('over' => '',
'time_call' => 'Please Select',
'call_my' => 'Please Select',
'app1_am' => 'Please Select');
// Check that all required form fields are completed
$num_fields = count($fields); // http://www.php.net/count
for($i = 0; !$error && ($i < $num_fields); ++$i)
{
$error = isset($_POST[$fields[$i]); // http://www.php.net/isset
}
$reset($defaults);
while(!$error)
{
list($key, $val) = each($defaults); // http://www.php.net/list
// http://www.php.net/each
// error when the posted val is the default.
$error = $_POST[$key] == $val;
}
if($error) // A required field was missing or set to the default value.
// Add an error message to the error_texts array.
{
$error_texts[] = "Required Field(s) Missing ({$error_marker})!";
}
// Check if email exists and verify its syntax
if (isset($_POST['email']))
{
$pattern = '^[a-z0-9]+([-_\.]?[a-z0-9])+@'
. '[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}';
if(eregi($pattern, $_POST['email'])) // http://www.php.net/eregi
{
// valid email verified so report form submitted
echo "<fieldset><legend>Application Received</legend>...";
// Mail form to us
$mail_to = "EMAIL HERE";
$mail_subject = "Application";
$mail_body = "<html>\n";
// ...
// rest of form to be mailed in here!!
// ...
$header = "From: $email\r\n";
// ...
mail($mail_to, $mail_subject, $mail_body, $header);
// http://www.php.net/function.mail
}
else // invalid email
{
$error = true;
$error_texts[] = "Invalid email address!";
}
}
}
// Output error messages, if any
if ($error)
{
echo '<div align="center"><span class="red">'
. join(" ", $error_texts) // http://www.php.net/join
. '</span></div>';
}
?>
Take care,
Nik
http://www.bigaction.org/
|
|

July 9th, 2003, 08:38 AM
|
|
Registered User
|
|
Join Date: Jul 2003
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Hi
thanks it looks really logical except
I get errors on the line $reset($defaults);
if the form has not been submitted i.e. on load this line executes $error_texts[] = "Form not submitted!"; which is bit pre emptive seeing as they haven't submitted as the page has just loaded and does not mean they will want ot fill in the form etc.
On load all fields are empty and so the * for required fields shows when I wanted to show them which fields are required following submission if any have been left out.
And the thank you submission complete etc. shows up above the form rather than replacing the form as I had it.
I would really love to incorporate what you have shown above as it is obviously the safer option but with the functionality layout I was looking for i.e. the page replacing itself with thanks rather than above a filled in form.
I am reading all the php.net pages you have advised within your code but that may take a little while to nderstand fully to give me the functionality.
Also next to each element I had <?php if (!$borrow) { echo $error1; } ?>
and have replaced with <?php if (!$borrow) { echo $error_marker; } ?> is this correct?
Also when the form is complete but email is NOT correct the error message showing required fields missing etc shows up rather than just 'invalid email' error.
Hope this isn't too much and I do want to say thanks and how much I appreciate what you have written, I just want to understand it further to be able to incorporate it accurately and help promote the good name of PHP as well by doing it correctly and securely.
Thanks again
V
|
|

July 9th, 2003, 03:54 PM
|
|
Friend of Wrox
|
|
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Quote:
quote:Originally posted by visionary
Hi
thanks it looks really logical except
I get errors on the line $reset($defaults);
|
That's my typo, sorry! reset() is a function, so it shouldn't have a dollar sign in front of it. Replace "$reset" with "reset".
Quote:
quote:Originally posted by visionary
if the form has not been submitted i.e. on load this line executes $error_texts[] = "Form not submitted!"; which is bit pre emptive seeing as they haven't submitted as the page has just loaded and does not mean they will want ot fill in the form etc.
|
That code there was for the purposes of example. If it doesn't fit with your scheme, by all means remove it! The only real purpose that code would serve is if the submit target page is different than the original form generating page.
Quote:
quote:Originally posted by visionary
On load all fields are empty and so the * for required fields shows when I wanted to show them which fields are required following submission if any have been left out.
|
Makes sense. Again, the logic and processing of this page is slightly different since you're having the same page both generate and process the form.
Don't get me wrong -- this is the best way to do things! I had the impression that you were using a separate page to generate the form.
Quote:
quote:Originally posted by visionary
And the thank you submission complete etc. shows up above the form rather than replacing the form as I had it.
I would really love to incorporate what you have shown above as it is obviously the safer option but with the functionality layout I was looking for i.e. the page replacing itself with thanks rather than above a filled in form.
I am reading all the php.net pages you have advised within your code but that may take a little while to nderstand fully to give me the functionality.
|
Yeah, it takes some time to get the hang of things. The code I wrote is, of course, by no means the perfect way to do things -- I merely wanted to illustrate how things could be done more efficiently (only calling eregi() once, etc.), with links to a lot of appropriate and useful function reference pages in the manual.
Quote:
quote:Originally posted by visionary
Also next to each element I had <?php if (!$borrow) { echo $error1; } ?>
and have replaced with <?php if (!$borrow) { echo $error_marker; } ?> is this correct?
|
Almost -- I'd prefer
if(!isset($_POST['borrow'])) { echo $error_marker; }
The reason I changed the name is that $error_marker is a much more descriptive name than $error1. If you come back to the code after leaving it for 3 months, you'll likely have a much easier time remembering what $error_marker is than $error1. If someone else were to read your code (say, a client or supervisor), they'd have a much easier time reading it with better variable and function names, which gives the impression of a much more well-put-together site.
Quote:
quote:Originally posted by visionary
Also when the form is complete but email is NOT correct the error message showing required fields missing etc shows up rather than just 'invalid email' error.
|
That's strange -- I thought that I'd only added the "Required Fields Missing" string to the error_texts array if there was a field missing or set to the default value.
Quote:
quote:Originally posted by visionary
Hope this isn't too much and I do want to say thanks and how much I appreciate what you have written, I just want to understand it further to be able to incorporate it accurately and help promote the good name of PHP as well by doing it correctly and securely.
|
No problem! I'm happy to help when/if I have the time.
The one change we'd need to make is to create another flag variable. There are essentially three states the page can be in:
1: The user has not submitted the form.
2: The user has submitted the form, but with errors.
3: The user has submitted the form, without errors.
You're going to display the form in cases 1 and 2. You're going to process the input in cases 2 and 3.
So you need two flags to tell you which state you're in: "form submitted" and "errors exist" come to mind. We already have the 2nd -- that's our boolean $error.
Code:
<?php
$error = false; // default value
$form_submitted = isset($_POST) && is_array($_POST);
// it's not enough to check if $_POST['submit'] exists, because
// a user can submit the form by hitting 'enter' in a text field
// which submits all form data EXCEPT the submit buttons.
if($form_submitted)
{
// process incoming form data and check for errors.
// Note: The *ONLY* thing you need to do here is check
// for errors. You do NOT need to send your verification
// email or echo ANY data out to the user.
}
// Do we need to generate the form?
if(!$form_submitted || $error)
{
// generate the form here.
// When generating the form, wrap all the error checks and
// output in
// if($form_submitted)
// or
// if($error)
// You can use if($error) because $error _only_ gets set to
// true if $form_submitted is true and errors were found.
// Therefore, $error == true implies that $form_submitted == true.
// For example:
if($error && !isset($_POST['borrow']))
{
echo $error_marker;
}
} // if(generate form)
else // we do not have to generate the form --
// it must be a valid submission!
{
// Being in this part of the script implies that the form
// was submitted and there were no errors.
// This is the appropriate place to echo out a
// confirmation message to the user, send your emails,
// and do whatever else is necessary upon a valid
// form submission.
}
?>
How does this organization look to you? Make sense?
Take care,
Nik
http://www.bigaction.org/
|
|

July 14th, 2003, 08:00 PM
|
|
Registered User
|
|
Join Date: Jul 2003
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
HI Nik,
Sorry haven't been around for a couple of days.
Am currently putting together all the CSS with accessability via WC3 standards for the site together and finishing the touches to layout and design (images to be placed etc.)
Will post back when have completed and integrated the PHP structure as layed out above which by the way looks very logical to me and makes sense as a structure.
Thanks for all your help so far, will let you know how I get on with it.
Cheers
V
|
|

July 15th, 2003, 01:06 PM
|
|
Friend of Wrox
|
|
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Best of luck! Lemme know how it goes. Again, there's a million ways to do it, my way is just a suggestion. If you are more comfortable with another way, feel free to explore your own ideas.
Personally, I like breaking the page into separate functional units. I don't like the same code to process form input to output anything to the user.
Take care,
Nik
http://www.bigaction.org/
|
|
 |