Log in

View Full Version : Help needed with PHP Contact Form



dog
06-19-2007, 09:39 PM
Hello,

I'm using PHP to send some information from a form. It's working fine in terms of the emails but there are two things that I can't seem to do.


Ensure that the email address uses a valid format.
Stop the inputted data from being cleared in the case that the form has been filled out incorrectly.


The form from contact.php


<form action="formSender.php" method="post">
<h3>Contact Form</h3>
<label for="name" id="firstLabel">Name:</label>
<input type="text" name="name"><br>

<label for="email">Email:</label>
<input type="text" name="email"><br>

<input type="submit" value="Send" />
</form>

<?php
$send = $_REQUEST['send'];

if ($send == "yes")
{echo 'Your details have been sent. Thankyou! '; }

if ($send == "no")
{echo 'Something went wrong. Please try again.'; }
?>


formSender.php

<?php

// prepare the redirect
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');


//get details for the emails from the form

$name = $_REQUEST['name'];
$email = $_REQUEST['email'];


//check to see if the form has been filled out

if($name != "" & $email != "") {


//send the emails
//[....]

//redirect to the original page and show a success note.

$extra = "contact.php?send=yes";
}


//if the form hasn't been filled out
else {
//redirect to orginal page and show an error message.
$extra = "contact.php?send=no";
}

header("Location: http://$host$uri/$extra");
exit;

?>

Can anybody help?

Thanks,
dog

alexjewell
06-20-2007, 01:07 AM
Yes, I use javascript to check emails. There's a way to do it with preg_match in PHP, but I haven't been able to make it work. I use the following javascript:



var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

function checkmail(e){
var returnval=emailfilter.test(e.value)
if (returnval==false){
alert("Please enter a valid email address.")
e.select()
}
return returnval}


Then, in the form, you add an onclick event to the submit button:



<input type="submit" value="Send" onclick="return checkmail(this.form.email)" />


Now, I've messed with some different solutions to the carrying back the info question. I tried adding those to the url along with the error message back to the contact page. However, especially with textarea's, that's a lot of info to be sending over the url. The best way would be to create a session. Add a session_start(); at the very top of the page and do something like this:



if($name != "" & $email != "") {
$_SESSION['name'] = '';
$_SESSION['email'] = '';
// REST OF YOUR CODE HERE
}

else{
if($name == ''){$_SESSION['name'] = '';}
else{$_SESSION['name'] = $name;}
if($email == ''){$_SESSION['email'] = '';}
else{$_SESSION['email'] = $email;}
// REST OF YOUR CODE HERE
}


Then, in contact.php, get those session variables at the top of the page:



session_start();
if(@$_SESSION['name']){$sname = $_SESSION['name'];}
else{$sname = '';}
if(@$_SESSION['email']){$semail = $_SESSION['email'];}
else{$semail = '';}


Then, put them in the form:



<form action="formSender.php" method="post">
<h3>Contact Form</h3>
<label for="name" id="firstLabel">Name:</label>
<input type="text" name="name" value="<?=$sname?>" /><br />

<label for="email">Email:</label>
<input type="text" name="email" value="<?=$semail?>" /><br />

<input type="submit" value="Send" />
</form>


I didn't test this, but it should work.

dog
06-20-2007, 12:15 PM
thanks alexjewell for the help,

i've put the javascript in place and have tried it out. it works swimmingly! the reason i wasn't looking for a javascript solusion is that i don't like the style of alert boxes. Is there some way to make them more stylish or some option other than an alert?

another thing, the real form that i'm working on has five of six fields that all need to be checked for content. if the required fields aren't all filled i'd ideally like to reveal some red stars next to the required fields and a message saying that the required fields need to be filled. obviously the email check would be an extra something on top of this.

if the validation process is done in contactSender.php and the result is sent back in the url i know how to display and format the error messages to my liking.. it's the validation itself that's got me stuck.

i'll try out the PHP you've sent and get back about that.

thanks again,
dog

alexjewell
06-20-2007, 01:16 PM
Alright, check out preg_match, too:

http://us.php.net/manual/en/function.preg-match.php

And yes, you could have a div come up instead of an alert. That involves some detailed css, too, as well as more javascript, though. You might want to post the javascript I gave you in the javascript section, asking if someone can give you code to make a div "popup" instead of an alert box.

Now, for the fields...work with the sessions again, maybe doing something like $_SESSION['fieldname'] = 'empty' if the field is empty or $_SESSION['fieldname'] = $fieldname if it's full, then do if statements. Something like if $_SESSION['fieldname'] == 'empty' then $star = '<img src="star.jpg" alt="Please fill this field in!" />';. Else, $star='<!--field filled in-->'; or something. Still putting using if statements, too, to figure out $sfieldname, which would be the value of the input. If $sfieldname exists, it equals $_SESSION['fieldname']. Else, it equals a space. Something along those lines. I also have a javascript to check if fields are filled in, but again, it uses an alert. Here's the javascript:



function formCheck(formobj){

var fieldRequired = Array("name", "email"); //Actual field names

var fieldDescription = Array("Name", "Email Address"); //What to call the field when the popup comes up

var alertMsg = "One or both of the login fields were left empty:\n\n";

var l_Msg = alertMsg.length;

for (var i = 0; i < fieldRequired.length; i++){
var obj = formobj.elements[fieldRequired[i]];
if (obj){
switch(obj.type){
case "select-one":
if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "select-multiple":
if (obj.selectedIndex == -1){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "text":
case "textarea":
if (obj.value == "" || obj.value == null){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
default:
}
if (obj.type == undefined){
var blnchecked = false;
for (var j = 0; j < obj.length; j++){
if (obj[j].checked){
blnchecked = true;
}
}
if (!blnchecked){
alertMsg += " - " + fieldDescription[i] + "\n";
}
}
}
}

if (alertMsg.length == l_Msg){
return true;
}else{
alert(alertMsg);
return false;
}
}


Then, in the form:



<form action="formSender.php" method="post" onsubmit="return formCheck(this);">
...


But again, it uses a popup. And I'd still check if the fields are filled with PHP, especially with the system you want. Javascript is client side and thus, can be disabled. You can't rely on JavaScript, but it's a useful tool nonetheless.

soloWebDev
06-20-2007, 05:15 PM
php email check

<?php

if (isset($_POST["submit"]))
{
$email = $_POST['email'];

if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
{
require 'sendEmail.php';
echo 'Thanks man!';
//print '<meta http-equiv="refresh" content="0;url=thankyou.php">';
exit;
}
else {
echo '<p align="center"><font color="cc0033"><b>Please Fix - Invalid email address.</b></font></p>';
}
}
?>

alexjewell
06-20-2007, 06:04 PM
Yeah, actually eregi would be better to use.

dog
06-20-2007, 07:24 PM
[edit: "OOOPS! Didn't see the more recent replies before posting the following"]

Hey man,

Thanks again for the help.

I'm gonna put something up in the Javascript section as you suggested but I've persisted with the PHP option too. I'm trying to get this PHP to send the form data back into the form when it's not filled out properly.

I've put your code in place as best I can but it's not working. If I only fill out one of the fields, a name with no email for example, it comes back as not sent but the form gets cleared.

Here's the exact code I'm trying. See if you can see where I'm going wrong. I've put a load of notes explaining the code to myself, but I don't know if I'm understanding it correctly so feel free to edit them.

test_contact.php

<?php

session_start();
if(@$_SESSION['name']){$sname = $_SESSION['name'];}
else{$sname = '';}
if(@$_SESSION['email']){$semail = $_SESSION['email'];}
else{$semail = '';}


?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head>
<title>Contato</title>
</head>
<body>
<form action="test_formSender.php" method="post">
<h3>Formulario de Contato</h3>
<label for="name">Name:</label> <input type="text" name="name" value="<?=$sname?>"><br>

<label for="email">Email:</label> <input type="text" name="email" value="<?=$semail?>"><br>

<input type="submit" value="Send" />

</form>

<?php
$send = $_REQUEST['send'];

if ($send == "yes")
{echo '
<div id="successNote">
<p>Sua mensagem foi enviada com sucesso! Obrigado!</p>
</div>';
}

if ($send == "no")
{echo '
<div id="successNote">
<p>Sua mensagem n&atilde;o foi enviada.</p>
</div>';
}

?>


</body>
</html>


test_formSender.php

<?php
//first set up the variables for the redirect
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');


//define the variables for the form fields
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];


//if the name and email are something other than nothing...
if($name != "" & $email != "") {

//...session 'name' and session 'email' equal nothing,
$_SESSION['name'] = '';
$_SESSION['email'] = '';


//send the emails
//[....]

//and define the location of the redirect with a note to show a success note.
$extra = "test_contact.php?send=yes";
}


//else (if the name and email do contain something)...
else {

//...take the values from the form and keep them in the session
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;


//and define the location of the redirect with a note to show an error message.
$extra = "test_contact.php?send=no";
}

//now redirect to the appropriate version of the original page
header("Location: http://$host$uri/$extra");
exit;

?>

dog
06-20-2007, 07:41 PM
soloWebDev, thanks for the post.

I've got a couple of questions:

Where do I put that script?:o

And what's going on here?


require 'sendEmail.php';
echo 'Thanks man!';
//print '<meta http-equiv="refresh" content="0;url=thankyou.php">';
exit;

I'm guessing that 'require' calls 'sendEmail.php' into play, just like 'action="formSender.php"' inside a form tag calls 'formSender.php' into play.
The echo I can understand, but where does it echo?
And, what's going on with '//print' I thought anything that started with '//' would just be skipped.

Where should I be learning all of this?
Thanks again! :D

alexjewell
06-22-2007, 01:27 PM
The problem is you need a session_start(); in test_formSender.php too. Every page including session stuff needs that.

And he made that line a comment in case you didn't want it (If you're using a header location redirect instead) However, you can't use a header location redirect after echoing anything, so you would have to use the meta redirect in that case to get back to text_contact.php.

dog
06-22-2007, 10:06 PM
Thanks again for all the help.

The form is working nicely now. I'm using a bit of PHP underneath the form itself to echo an error or thankyou message. I've also put a couple of features in, a couple of types of indicators to show the user where the problems lie if she/he creates any. These are hidden or visible depending on the CSS specified by the PHP.


I'm going to post the code up for anyone that's interested.

The form now has a textarea and this has created another challenge. The other fields are inputs and their input gets stored in a session and sent back as the value of the input. How can this be done for a textfield [which obviously doesn't have 'value']?

Here's all the code:
form.php

<?php

session_start();
if(@$_SESSION['name']){$sname = $_SESSION['name'];}
else{$sname = '';}
if(@$_SESSION['telephone']){$stel = $_SESSION['telephone'];}
else{$stel = '';}
if(@$_SESSION['email']){$semail = $_SESSION['email'];}
else{$semail = '';}
if(@$_SESSION['message']){$smessage = $_SESSION['message'];}
else{$smessage = '';}
if(@$_SESSION['contactType']){$scontact = $_SESSION['contactType'];}
else{$scontact = '';}
if(@$_SESSION['timeTable']){$stime = $_SESSION['timeTable'];}
else{$stime = '';}

$send = $_REQUEST['send'];

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head>
<title>[...]</title>

<link href="../css/contatos.css" rel="stylesheet" />

<script type="text/javascript" src="../js/showHide.js"></script>

<style type="text/css">
<?php
if ($send == "invalidEmail") { echo '.requiredMark2 { visibility: visible; } .requiredMark { visibility: hidden;} input.required {background: #F7E9E9;'; }

elseif ($send == "no") { echo '.requiredMark, .requiredMark2 { visibility: visible;}'; }

else { echo '.requiredMark, .requiredMark2 { visibility: hidden;}'; }

?>
</style>

</head>

<body>

<form action="formSender.php" method="post">
<h3>Formulario de Contato</h3>

<label for="name">Nome:<span class="requiredMark"> *</span></label>
<input type="text" name="name" value="<?=$sname?>"><br>

<label for="telephone">Telefone:<span class="requiredMark"> *</span></label>
<input type="text" name="telephone" value="<?=$stel?>"><br>

<label for="email">Email:<span class="requiredMark2"> *</span></label>
<input type="text" name="email" class="required" value="<?=$semail?>"><br>

<label for="message">Mensagem:<span class="requiredMark"> *</span></label>
<textarea name="message" value="<?=$smessage?>"></textarea><br>

<div class="options">
<div class="label">Contato por:</div>

<label for="tel" onclick="show('horario')">Tel: </label>
<input type="radio" onclick="show('horario')" name="contactType" id="tel" value="tel">

<label for="e-mail" onclick="hide('horario')">E-mail: </label>
<input type="radio" onclick="hide('horario')" name="contactType" id="e-mail" value="e-mail">

</div>

<div id="horario">
<label for="timeTable">Horario:</label>
<input type="text" name="timeTable" value="<?=$stime?>">
</div>

<div id="formButtons">
<input type="reset" value="Limpar">
<input type="submit" value="Enviar">
</div>
</form>

<?php

if ($send == "yes") {
echo '<div id="successNote"><p><span class="green"> * </span>Sua mensagem foi enviada com sucesso! Obrigado.</div>';
}

if ($send == "no") {
echo '<div id="successNote"><p>N&atilde;o foi poss&iacute;vel enviar a sua mensagem.<p><span class="requiredMark"> * </span>- Por favor, preencha todos os campos marcados.</div>';
}

if ($send == "invalidEmail") {
echo '<div id="successNote"><p>N&atilde;o foi poss&iacute;vel enviar a sua mensagem.<p><span class="requiredMark2"> * </span>- O formato de e-mail n&atilde;o &eacute; v&aacute;lido.</div>';
}

?>
</body>
</html>


formSender.php


<?php
session_start();
if(@$_SESSION['name']){$sname = $_SESSION['name'];}
else{$sname = '';}
if(@$_SESSION['telephone']){$stel = $_SESSION['telephone'];}
else{$stel = '';}
if(@$_SESSION['email']){$semail = $_SESSION['email'];}
else{$semail = '';}
if(@$_SESSION['message']){$smessage = $_SESSION['message'];}
else{$smessage = '';}
if(@$_SESSION['contactType']){$scontact = $_SESSION['contactType'];}
else{$scontact = '';}
if(@$_SESSION['timeTable']){$stime = $_SESSION['timeTable'];}
else{$stime = '';}

//set up the variables for the redirect
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');


//define the variables for the form fields
$name = $_REQUEST['name'];
$tel = $_REQUEST['telephone'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$contact = $_REQUEST['contactType'];
$time = $_REQUEST['timeTable'];


//If the name and email are something other than nothing...
if($name != "" & $tel != "" & $email != "" & $message != "" ) {

//check if the email is valid

//If it is...
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {

//send the emails
//[....]

//effectively clear the 'name' and 'email' fields
$_SESSION['name'] = '';
$_SESSION['telephone'] = '';
$_SESSION['email'] = '';
$_SESSION['message'] = '';
$_SESSION['contactType'] = '';
$_SESSION['timeTable'] = '';


//and define the location of the redirect to show a success note.
$extra = "form.php?send=yes";
}


else { // the email is invalid.
//...take the values from the form and keep them
$_SESSION['name'] = $name;
$_SESSION['telephone'] = $tel;
$_SESSION['email'] = $email;
$_SESSION['message'] = $message;
$_SESSION['contactType'] = $contact;
$_SESSION['timeTable'] = $time;


//and define the location of the redirect with a note about the email address being invalid
$extra = "form.php?send=invalidEmail";
}
}

else { //something is missing from one of the required fields

//...take the values from the form and keep them
$_SESSION['name'] = $name;
$_SESSION['telephone'] = $tel;
$_SESSION['email'] = $email;
$_SESSION['message'] = $message;
$_SESSION['contactType'] = $contact;
$_SESSION['timeTable'] = $time;


//define the location of the redirect with a note to show an error message.
$extra = "form.php?send=no";
}

// redirect to the appropriate version of the original page
header("Location: http://$host$uri/$extra");
exit;

?>

alexjewell
06-22-2007, 10:31 PM
Just put the variable between the textarea tags:



<textarea name="message"><?=$smessage?></textarea>

dog
06-22-2007, 11:40 PM
Just put the variable between the textarea tags:



<textarea name="message"><?=$smessage?></textarea>


Ok! I've tried that in the same code I posted above and it's not working. I've also tried.


<textarea name="message"><?$smessage?></textarea>
...but that didn't work either. I'm clueless!

:confused:

alexjewell
06-24-2007, 01:34 AM
Hmmm...that's so weird :/

I'm clueless on that one. It should work...ha.

The one thing I see is the code you posted above is:



<textarea name="message"><?$smessage?></textarea>


It should be:



<textarea name="message"><?=$smessage?></textarea>


If that doesn't work, I'm not entirely sure...


The other thing, and thanks to Twey for pointing this out to me, is in the code you posted, you have:



//If the name and email are something other than nothing...
if($name != "" & $tel != "" & $email != "" & $message != "" ) {


You should use "&&", not "&":



//If the name and email are something other than nothing...
if($name != "" && $tel != "" && $email != "" && $message != "" ) {


That doesn't seem to be shooting back any errors...but I would make it right to just, well, have it right. :)