View Full Version : contact form php help
hey guys,
could do with some help.
have a contact form with name, email & message boxes set up using html & php. All works fine. But i want it to check all the fields are filled before sending, as at the moment you can leave it blank and it'll still send!!
I'm very new to php, be warned!! :)
Would be nice if it highlight the box that was blank too.
Here's the php
<?php
if(isset($_POST['submit'])) {
$to = "myemail";
$subject = "Website contact form";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n";
echo "<script>window.location = 'my thanks for contacting me page.co.uk'</script>";
mail($to, $subject, $body);
} else {
echo "error: no data sent.";
}
?>
Cheers for any help :)
You'll need to use some Javascript for this, easiest way for a little form like this is to write a javascript function that checks each form element seperately and returns "true" if everything is valid, "false" otherwise.
you can then add an attribute to the <form> like <form onsubmit='return validateForm()'>
added:
If you post the HTML I might be able to help you more :)
Added after 3 minutes:
This link should help:
http://www.w3schools.com/js/js_form_validation.asp
I'm thinking a bit slowly today, so will keep adding useful stuff ;)
The line
echo "<script>window.location = 'my thanks for contacting me page.co.uk'</script>";
would be better as
header("Location: page.php");
you do not need javascript at all!
<?php
$error='';
foreach ($_GET as $field as $key) {
if ($field == '') {
$error.=$key . ' is empty! <br />';
}
}
if ($error != '') {
die($error);
}
?>
Untested btw, but i think it should work
That should work great, assuming the form handler is the same page as the form (I think!)
I generally prefer to do user-friendly validation client side, then make sure everything is safe server side in the form handler. I guess this is less important in a little email script :D
nah, all validation should be done server side regardless, you can check client side if you like.
the code will work regardless provide a form is submitted to that page
nah, all validation should be done server side regardless, you can check client side if you like.
the code will work regardless provide a form is submitted to that page
yupyup.
Would be nice if it highlight the box that was blank too.
Sounds like a little bit of JS could come in handy for highlighting the error, however?
Thanks guys,
changed the echo to header as you said dukey.
that bit of code smifis has done, do i put that in a new file, ie. validation.php ??
edit: and then action it in the html?
iGoD ReLeNtLeS
17-02-11, 11:28
just to add, you cant use isset with $_GET or $_POST as it will always setup the variable even if $_GET or $_POST is blank. As smifis has done you just need to make sure the field has data present, rather than if its set.
can be done with the php too if you want to go a bit more indepth,
<?php
if ($_GET['field'] == '') {
?>
<span class="xxx">This is my highlighted field</span?
<?php
} else {
?>
<span> This is an okay field</span>
<?php
}
?>
yupyup.
Sounds like a little bit of JS could come in handy for highlighting the error, however?
If you have the time it's better to do JS validation AS WELL, yeah. This is because it provides a better end-user experience (i.e. they don't have to wait a second or two for a server response to find out that they missed a required field) and because it will reduce load on the server by preventing unnecessary incomplete submissions.
I don't like popup windows myself, though, aesthetically speaking. But you can do the validation with jquery and css nowadays, so they aren't necessary.
Right, i'm confused now!! lol:)
DW about it, just go with something like Smifis' post :).
Ok, just not sure where to put smifis code!! :)
it depends which bit of code you intend to use guardy :lol:
brb.....
<?php
if(isset($_POST['submit'])) {
$to = "myemail";
$subject = "Website contact form";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
//validate fields
$errormessage = "";
if($to == "") $errormessage = "Blank to";
/*NOTE ONLY WORKS ON PHP 5.3*/
if(!filter_var($email_field, FILTER_VALIDATE_EMAIL)) $errormessage = "Invalid email";
//just carry on with validations on each field ...
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n";
if($errormessage == "")
{
echo "<script>window.location = 'my thanks for contacting me page.co.uk'</script>";
mail($to, $subject, $body);
}else{
echo "<script>window.location = 'FAIL'</script>";
}
} else {
echo "error: no data sent.";
}
?>
here you go mate
<?php
if( !empty($_POST['submit'])) {
$error='';
foreach ($_GET as $field as $key) {
if ($field == '') {
$error.=$key . ' is empty! <br />';
}
}
if ($error != '') {
$to = "myemail";
$subject = "Website contact form";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n";
echo "<script>window.location = 'my thanks for contacting me page.co.uk'</script>";
mail($to, $subject, $body);
} else {
echo $error;
}
?>
I like DT's code better :D
if(!filter_var($email_field, FILTER_VALIDATE_EMAIL))
Wasn't aware of this function, looks useful :thumb:
Wasn't aware of this function, looks useful :thumb:
cool, it still amuses me to see so many regex based functions to validate data, all that code now done in a one-liner :D
http://www.php.net/manual/en/ref.filter.php
DT.
Ideal, thanks guys, works a treat DT. sorry smifis, saw his before yours :)
LOL, his is done properly anyway,
haha smifis, thanks for that anyway.
like the email validation bit. just tested and works nicely. :)
it'sa very crude way of checking that nothing in the $_GET array is empty, demonstrates foreach nicely though :P
So how about highlighting the empty box or invalid email.
Easy to do? Is that a javascript thing?
Up to you, both will work
Just noticed that if you just enter a valid email address, it'll still send even with the other 2 boxes empty!
<?php
if(isset($_POST['submit'])) {
$to = "myemail";
$subject = "Website contact form";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
//validate fields
$errormessage = "";
if($name_field == "") $errormessage = "Blank name";
if($email_field == "") $errormessage = "Blank email";
if($message == "") $errormessage = "Blank message";
/*NOTE ONLY WORKS ON PHP 5.3*/
if(!filter_var($email_field, FILTER_VALIDATE_EMAIL)) $errormessage = "Invalid email";
//just carry on with validations on each field ...
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message\n";
if($errormessage == "")
{
echo "<script>window.location = 'my thanks for contacting me page.co.uk'</script>";
mail($to, $subject, $body);
}else{
echo "<script>window.location = 'FAIL'</script>";
}
} else {
echo "error: no data sent.";
}
?>[/QUOTE]
the php comment is a dead giveaway, I tend to leave things for you to do rather than handing it on a plate ;)
//just carry on with validations on each field ...
DT.
Just noticed that if you just enter a valid email address, it'll still send even with the other 2 boxes empty!
Yeah hence DT's comment in the code:
//just carry on with validations on each field ...
;)
What he means is you'll need a validation line for each field you want to validate. As per smifis' post a simple approach is just
if ($_REQUEST['field'] == '') { $errormessage = "Empty field message blah"; };
You'll obviously need to change 'field' and the error message to values appropriate to your form.
Lovely job smifis, thats done the trick!!! :)
Aha, didn't see that andy, cheers also :)
for field highlighting, this kinda works... I'm sure there are much better ways!
<style>
input{
background-color: #FFC1C1;
}
</style>
<script>
function validatePresent(field)
{
if(field.value == null || field.value == '')
{
field.style.background='#FFC1C1';
}
else
field.style.background='#9ACD32';
}
function validateEmail(field)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
var result = emailPattern.test(field.value);
if(result)
{
field.style.background='#9ACD32';
}
else
field.style.background='#FFC1C1';
}
</script>
<form>
<div id='name_div'><input type='text' name='name' onkeyup='validatePresent(this)'></div>
<div id='email_div'><input type='text' name='email' onkeyup='validateEmail(this)'/></div>
<div id='message_div'><input type='text' name='message' onkeyup='validatePresent(this)'/></div>
<input type='submit' name='submit' value='Send ->' style='background-color: #CCC;'/>
</form>
Cheers Dukey, will have a closer look later. heads mashed now!! :)
Did you get everything looking good; Guardy, my fellow Kingsbridgian? :thumb:
All looks good thanks mate.
Haven't managed to do the highlight the boxes red thing, just have it returning to the blank form if theres any errors! Only just got to grips with html (i think), so php is another thing!
You've defected to Totnes haven't you? You're missing all the excitement of the new Tesco's opening!! :confused:
All looks good thanks mate.
Haven't managed to do the highlight the boxes red thing, just have it returning to the blank form if theres any errors! Only just got to grips with html (i think), so php is another thing!
You've defected to Totnes haven't you? You're missing all the excitement of the new Tesco's opening!! :confused:
Yea! tough how many languages you need to get your head around to build a little website!
I have indeed, did experience the new Costa's last Sunday though, and off to Kingsbridge tonight, may get a chance to pop in and do some grocery shopping! :P
Yea! tough how many languages you need to get your head around to build a little website!
I have indeed, did experience the new Costa's last Sunday though, and off to Kingsbridge tonight, may get a chance to pop in and do some grocery shopping! :P
hahaha, costas is good, and so is the new tescos! so exciting in kingsbridge at the moment!!!!!!</sarcasm>
There's like mass hysteria about the tesco's!! Don't get what all the excitement is about really!! :)
There's like mass hysteria about the tesco's!! Don't get what all the excitement is about really!! :)
me neither, went when it opened, got a free bag thing, not been since.
would probably choose it over morissons.
thinks its just that there is actually a tescos now and not just a rumour!
I think it is because there has been "OMG! Tesco is coming!" in the town paper for the last 15 years and they've finally got 'round to building it :P
yep :) what i was trying to say :P
Haha, very true.
I am glad there is a tesco's now, as morrisons is rubbish, but i'll stop short of getting excited about it!
I'll probably still have mine delivered, just so i don't have to step foot in a supermarket!! :)
My local tesco is built on marshland, every year, it's 2 inches lower. :/
lol what a thread.
Get to check out Tesco next week when I'm down from uni.
Whats the form for guardy?
I know, changed from php help, to a kingsbridge tesco chat!!
Its just a contact form mate, they fill it in and it gets forwarded to my email. I'm setting up a simple website for my work.
@smifis - That was a surveyor fail!! :)
Toonshorty
18-02-11, 16:24
Couldn't you have before the mail() method (if that's what you're using):
if ($formtextbox1 = "" || $formtextbox2 = "") {
echo 'A field is blank noob';
} else {
echo 'kthx';
mail();
}
Thats basically what is done
should be '==' though, not '='
Toonshorty
18-02-11, 16:53
should be '==' though, not '='
Well done, you spotted my intentional mistake - good too see you're awake :ninja:
I always make that mistake :knock:
Well done, you spotted my intentional mistake - good too see you're awake :ninja:
I always make that mistake :knock:
Always making it myself also..... so easy to make!
I always forget the semicolons :/
My worst habit is putting semicolons and braces into ASP.
So automatic after being trained in Java and practiced in PHP!
My worst habit is putting semicolons and braces into ASP.
So automatic after being trained in Java and practiced in PHP!
yeah! my problem is usually when I have to write something normal i start semi-coloning when I should be full stopping.
Ulgh, I hate that programming style, hard to speed skip through and so much extra work!
yeah! my problem is usually when I have to write something normal i start semi-coloning when I should be full stopping.
Haha, I dropped a few marks on an essay I did for my "History of Computing" module for doing exactly that.
Haha, I dropped a few marks on an essay I did for my "History of Computing" module for doing exactly that.
yeah did that for a whole essay once, dont think I ever use semicolon normally so search replace came in handy for that :)
Ulgh, I hate that programming style, hard to speed skip through and so much extra work!
I've gotten into the bad habit of plugging ASP code into an asp2php translator to work out how it works :P
LOL! Thats just plain bad :lol:
yeah did that for a whole essay once, dont think I ever use semicolon normally so search replace came in handy for that :)
It's worse in exams, Ctrl+F doesn't work so well with the "Pen & Paper" OS.
It's worse in exams, Ctrl+F doesn't work so well with the "Pen & Paper" OS.
It does if you get to use a computer cause you're 'special' :cop:
Woah, back on track guys.......
......so who got their free bag from tescos? :)
Woah, back on track guys.......
......so who got their free bag from tescos? :)
I got 5 :D :thumb:
I got 5 :D :thumb:
Haha, i haven't even been in there yet. The misses has and got her free bag!! :|
I'm glad costa has opened, just what this town needed, ANOTHER coffee shop!! :)
I'm glad costa has opened, just what this town needed, ANOTHER coffee shop!! :)
Haha, Costa has got one distinct advantage.
Sunday opening :D
I'm trying to organise a coffee shop crawl around town one day!! :)
Guardy, linky to site please :D
Guardy, linky to site please :D
Its not live yet mate.
Why, did you wanna check out how amateur it looks!! :)
I'm trying to organise a coffee shop crawl around town one day!! :)
I am so up for that! we have like 8 places to go, more than there are pubs!
any chance of a sneak preview Guardy? I do want to see how amateur it is :P
what about a screenshot flash?? :)
Flash is with the inlaws for the weekend :P
Screeny sounds good mate!
Sent from my Milestone using Tapatalk
Here you go. Just need to add the text on the white section. :)
http://img809.imageshack.us/img809/2696/homepagei.jpg (http://img809.imageshack.us/i/homepagei.jpg/)
Uploaded with ImageShack.us (http://imageshack.us)
Looking good! Must admit that you don't often see painters/decorators with their own website!
You do handy man work? Like putting in network cables and sockets?
Cheers guys, will hopefully get it finished this week if i get chance. I just need to sort what text i want on there and sort out some more photos.
Never been asked to do that before flash, but i'm sure i could. :)
Powered by vBulletin® Version 4.1.12 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.