InMotion Hosting Support Center

PHP is a great scripting language that allows many dynamic functions in your site. You can create custom forms, form validation, and email responses using PHP. This article will explain the basics in creating an email form that validates the inputs, produces errors when inputs are typed incorrectly, and send an email to you when submitted.

This section of the code will validate the form inputs

Below is the code you will use to validate whether the inputs have valid data or not. This can be customized for different form field validations.

Note! You can paste the entire code directly in the body section of your webpage to get it working.

<?php 
if (isset($_REQUEST['submitted'])) {
// Initialize error array.
$errors = array();
// Check for a proper First name
if (!empty($_REQUEST['firstname'])) {
$firstname = $_REQUEST['firstname'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$firstname)){ $firstname = $_REQUEST['firstname'];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your First Name.';}

// Check for a proper Last name
if (!empty($_REQUEST['lastname'])) {
$lastname = $_REQUEST['lastname'];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$lastname)){ $lastname = $_REQUEST['lastname'];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your Last Name.';}

//Check for a valid phone number
if (!empty($_REQUEST['phone'])) {
$phone = $_REQUEST['phone'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$phone)){ $phone = $_REQUEST['phone'];}
else{ $errors[] = 'Your Phone number can only be numbers.';}
} else {$errors[] = 'You forgot to enter your Phone number.';}

if (!empty($_REQUEST['redmapleacer']) || !empty($_REQUEST['chinesepistache']) || !empty($_REQUEST['raywoodash'])) {
$check1 = $_REQUEST['redmapleacer'];
if (empty($check1)){$check1 = 'Unchecked';}else{$check1 = 'Checked';}
$check2 = $_REQUEST['chinesepistache'];
if (empty($check2)){$check2 = 'Unchecked';}else{$check2 = 'Checked';}
$check3 = $_REQUEST['raywoodash'];
if (empty($check3)){$check3 = 'Unchecked';}else{$check3 = 'Checked';}
} else {$errors[] = 'You forgot to enter your Phone number.';}
}
//End of validation

Sends the email if validation passes

The following code is what sends the email. The inputs must pass the previous validation in order for the email to send. You will need to replace the "to" email address with the email address you want to receive the email to.

if (isset($_REQUEST['submitted'])) {
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "your@email.com";
$subject = "Admin - Our Site! Comment from " . $name . "";

$message = "Message from " . $firstname . " " . $lastname . "
Phone: " . $phone . "
Red Maple Acer: " . $check1 ."
Chinese Pistache: " . $check2 ."
Raywood Ash: " . $check3 ."";
mail($to,$subject,$message,$from);
}
}
?>

Error Reporting Code

This code will print any errors that occurs such as an empty input.

<?php 
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3>The following occurred:</h3><ul>';
// Print each error.
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
else{echo '<hr /><h3 align="center">Your mail was sent. Thank you!</h3><hr /><p>Below is the message that you sent.</p>';
echo "Message from " . $firstname . " " . $lastname . " <br />Phone: ".$phone." <br />";
echo "<br />Red Maple Acer: " . $check3 . "";
echo "<br />Chinese Pistache: " . $check2 . "";
echo "<br />Raywood Ash: " . $check3 . "";
}
}
//End of errors array
?>

Prints the contact form

This is the form that will display for the visitor to fill out.

  <h2>Contact us</h2>
<p>Fill out the form below.</p>
<form action="" method="post">
<label>First Name: <br />
<input name="firstname" type="text" value="- Enter First Name -" /><br /></label>
<label>Last Name: <br />
<input name="lastname" type="text" value="- Enter Last Name -" /><br /></label>
<label>Phone Number: <br />
<input name="phone" type="text" value="- Enter Phone Number -" /><br /></label>
<label>Red Maple Acer:
<input name="redmapleacer" type="checkbox" value="Red Maple Acer" /><br /></label>
<label>Chinese Pistache:
<input name="chinesepistache" type="checkbox" value="Chinese Pistache" /><br /></label>
<label>Raywood Ash:
<input name="raywoodash" type="checkbox" value="Raywood Ash" /><br /></label>
<input name="" type="reset" value="Reset Form" /><input name="submitted" type="submit" value="Submit" />
</form>

You can paste the entire code directly in the body section of your webpage to get it working. We have more tutorials with other methods to send email from your website at the following links.

Using phpMailer to Send Mail through PHP

How to set up FormMail

Continued Education in Course 205: Using PHP to create dynamic pages
You are viewing Section 1: How to create a custom PHP contact form with validation
Section 2: Setting up a database to handle form data from a website
n/a Points
2014-08-16 2:25 am

very nice..just copy and paste  and it works :)

n/a Points
2014-09-10 3:31 am

i am using the above code for sending mail but getting error like this:

The following occurred:

    '; // Print each error. echo '

Your mail could not be sent due to input errors.

';} else{echo '

Your mail was sent. Thank you!

Below is the message that you sent.

'; echo "Message from " . $firstname . " " . $lastname . " Phone: ".$phone." "; echo "Red Maple Acer: " . $check3 . ""; echo "Chinese Pistache: " . $check2 . ""; echo "Raywood Ash: " . $check3 . ""; } } //End of errors array ?>

 

i don't know why this error come when we click on submit button..pls help me soon..

Staff
28,219 Points
2014-09-10 7:35 am
Hello Anandita,

Be sure to check your code for syntax errors, particularly the placement of the quotes. Did you cut and paste it as is? It seems to work fine for me when doing that. Did you make any changes?

Kindest Regards,
Scott M
n/a Points
2014-11-11 8:17 pm

I have the same issue as Anandita. I even cut and paste as is yet portions of the php script are getting printed to the page. Any idea what else could be causing this?

Thanks.

Staff
11,186 Points
2014-11-11 8:31 pm
It sounds like your code is not being correctly parsed as PHP. Does the file extension a .php file?
n/a Points
2015-01-31 2:44 pm

Hello Anandita,

Probably, you are writing the php code and the html code into the same xyz.html file.

If you are using this instruction with the php script and html code in one file:

<form action="" method="post">

Then it is must that you will get the error which you have reported.

I'll suggest you to make a seperate php file and name it "mail.php". And write the html code in seperate html file and use the following instruction:

<form action="mail.php" method="post">

Once you've done like this, you will not receive any errors. It is a tested method, as I experienced the same but when I added mail.php, everything becomes fine.

I hope this will help you. Though my reply for your comment is too late, but I tried to help you and many others who is facing same error.

Sincerely,

Malik

n/a Points
2015-05-07 3:54 pm

Hello, i copy the same code that mention above and created seperate php file  callled mail.php and in my html file i used <form action="mail.php" method="post">, but it goes to my mail.php page,  showing the code i have copied 

please help to resolve tis error.

Staff
16,896 Points
2015-05-07 5:50 pm
Hello sharath,

Thank you for contacting us today. We are happy to help, but will require some additional information since it is not clear what you are asking.

Can you provide a link to the form, so we can test the error?

Please include any additional information that will help us replicate the problem.

Thank you,
John-Paul
n/a Points
2014-09-15 3:24 am

Hi.. Ive problem for make a contact us page. im using such your web for 'post a comment'. its work and nothing error with that. but the comment cannot sent to the email. email cannot received the comment for page contact us. can help me to solve it?

Thanks.

Mira

Staff
28,219 Points
2014-09-15 8:58 am
Hello Mira,

If you are using just this article, then the email should send through fine. Are you one of our customers? Are you using additional SMTP settings to send your email through the server? If so, they will need to be correct in order to send out.

Kindest Regards,
Scott M
n/a Points
2014-09-16 7:13 am

Hi,

I am using this entire code but the only problem is that the form is being emailed on refreshing/reloading the page

Staff
28,219 Points
2014-09-16 10:16 am
Hello Sak,

Thank you for pointing that out. I found the error and corrected it. It has been tested and will not send an email if it is refreshed before the Submit button is pressed. A more updated version of this article should come out soon with a bit more polish.

Kindest Regards,
Scott M
n/a Points
2014-09-18 4:13 am

hi

i will have to write this whole code in page or two page because it has three partition and php code is starting in partition one and ending in partition 2.

Staff
28,219 Points
2014-09-18 9:30 am
Hello Ravi,

You can put all three partitions in the same file. It was only split up on the article to show what purpose each partition serves.

Kindest Regards,
Scott M
n/a Points
2014-09-28 3:37 pm

What if you used radio buttons instead of checkboxes. How would the code look?

I get the html part but the radio validation not sending the value of radio button clicked.

Thanks

Staff
28,219 Points
2014-09-29 9:14 am
Hello Betty,

The checkbox is for when someone may select one or more of the options. Radio buttons force only one selection. Did you have code you wanted us to look at for errors? Replacing the checkboxes with radio buttons needs code modification not only on the form itself, but up where the validation is done.

Kindest Regards,
Scott M
n/a Points
2014-10-17 7:35 am

hello... can i create a home page using php, if yes then can i please get the know how

thanks

Staff
11,186 Points
2014-10-17 9:02 am
If you are not familiar with PHP, you may want to review some of the PHP articles on W3Schools which will teach you the basics of PHP to get you started.
n/a Points
2014-10-20 4:57 pm

This article is very interesting. Thanks!

I "inherited" the maintenance of some websites that use similar PHP functions for the contact forms, so this helps me understand what is going on. 

BUT, I'm having a big problem with browser compatibility. Any idea what I should check on?  This is driving me nuts!

Staff
28,219 Points
2014-10-20 5:04 pm
Hello Lou,

Since the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements in the page.

Kindest Regards,
Scott M
n/a Points
2014-10-21 8:32 am

Thanks for the reply Scott.

The websites and forms DISPLAY well in every browser,  But they seem to only actually send the message in Firefox and Chrome. Most messages in IE and some in Safari dont actually go through.  This is driving me nuts.

Staff
11,186 Points
2014-10-21 9:35 am
As Scott stated, with it being PHP, the functionality of the form itself should not be affected as all code is executed within the browser. Are you using this same contact form that we have provided within this article?
n/a Points
2014-11-04 9:36 am

 the php runs off the server, the functionality should not be affected. The browser incompatibility will likely come in display inconsistencies. These are normally found in the CSS files/statements. 

n/a Points
2014-12-25 1:09 pm

i want to design an email web page using php, how do i start?

Staff
3,669 Points
2014-12-26 10:37 am
Hello Hamman,

Can you provide some more information on what you are wanting to create? Generally a good place to start coding simple websites is W3 Schools.

Kindest Regards,
TJ Edens
n/a Points
2015-01-05 10:09 am

i want to make wesite  using php of my realtives they having a factory so which site i refer to get the knowlegde..i want like this only jst copy and paste so it is easy for me to create website.plz reply me soon plz

Staff
25,274 Points
2015-01-05 11:23 am
Hello Ash,

Thanks for the comment. Creating a website using only PHP will
    not
be a copy and paste process no matter what tool you use. There are many applications out there that make it easy to create a website that uses primarily PHP, but I would suggest using WordPress. Our WordPress Education Channel provides a lot of information on how to install and start using the application.

I hope this helps to answer your question, please let us know if you require any further assistance.

Regards,
Arnel C.
n/a Points
2015-01-30 2:47 pm

Hello,

I will appreciate the admin on sharing this useful php based code. It really helped me a lot in designing my php contact form. 

I have designed it and tested it successfully. Emails are coming to my email account but unfortunately in the SPAM folder with the tag (Unknown Sender).

I'll be grateful to you for your generous help to me.

Thanks and Sincerely,

Malik

Staff
25,274 Points
2015-01-30 4:25 pm
Hello Malik,

Sorry for the problem with the form. It looks like the issue is a result of the "FROM" setting for the form. I would recommend that you set it to an email address instead of a website. If you have any further questions or comments, please let us know.

Regards,
Arnel C.
n/a Points
2015-01-31 2:33 pm

Thank you Arnel C.

I really appreciate your prompt reply. I followed your suggestion and now all the emails are coming to inbox folder instead going to spam. BINGO..!! Thank you.

I'd really like to share the part of php code which I changed.

The original php code has:

$from = "From: Our Site!"; //Site name

Now, just change "From: Our Site!" with a valid email address like below:

$from = "name@xyz.com"; //Valid email address

By doing this, email will come to inbox with a valid reference email address and this will prevent email going into spam folder.

Just thought to share, so that some one might get help by this. Any way brilliant work from admins.

Thanks and Sincerely,

Malik

n/a Points
2015-02-12 1:26 pm

Hi,

Advance thanks for your code. every think work fine. but I couldn't receive the information to my email. I used one php file for entire code. If you could help Would be appriciaated.

Kumar

Staff
16,896 Points
2015-02-12 1:58 pm
Hello Kumar,

Thank you for your question. We are happy to help, but will need some additional information. Have you confirmed the email settings you entered are correct?

Have you followed the above guide? Are you having any problems with a step?

Have you reviewed the email logs to confirm if your script is communicating with the email server. (Live support can help you with that if you are on a shared server).

Thank you,
John-Paul
n/a Points
2015-02-13 3:22 pm

I am running this script on a localhost but the email is not being delivered even though the message says mail has been sent. Do I need to make changes to php.ini?

Staff
16,896 Points
2015-02-13 7:41 pm
Hello Bob,

Thank you for your comment. PHP errors can be enabled to display and log errors using your local php.ini file.

This can provide more details into what is happening.

Also, be sure to check your spam box/email filter for the test emails.

If you have any further questions, feel free to post them below.

Thank you,
John-Paul
n/a Points
2015-02-24 3:28 pm

Hello all,

I really need help. I don't know where to put my email, so when someone fills in the contact form, they click on the send button and it appears in my mailbox. So my question is; where in this script do I have to add something to receive messages in my mailbox? This script I use is also linked on a jquery. So I have a php form and a jquery. Please help me intelligent people! :D         

In my html I have add this:

<form id="form" action="#">

            <div class="success_wrapper">

              <div class="success">Contact form submitted!<br>

                <strong>We will be in touch soon.</strong> </div>

            </div>

            <fieldset>

              <label class="name">

                <input type="text" value="Name:">

                <br class="clear">

                <span class="error error-empty">*This is not a valid name.</span><span class="empty error-empty">*This field is required.</span> </label>

              <label class="phone">

                <input type="tel" value="Telephone:">

                <br class="clear">

                <span class="error error-empty">*This is not a valid phone number.</span><span class="empty error-empty">*This field is required.</span> </label>

              <label class="email">

                <input type="text" value="E-mail:">

                <br class="clear">

                <span class="error error-empty">*This is not a valid email address.</span><span class="empty error-empty">*This field is required.</span> </label>

              <label class="message">

                <textarea>Message:</textarea>

                <br class="clear">

                <span class="error">*The message is too short.</span> <span class="empty">*This field is required.</span> </label>

              <div class="clear"></div>

              <div class="btns"> <a data-type="reset" class="btn">clear</a><a data-type="submit" class="btn">send</a>

                <div class="clear"></div>

              </div>

            </fieldset>

          </form>

 

The linked Jquery code is this:

//forms

;(function($){

$.fn.forms=function(o){

return this.each(function(){

var th=$(this)

,_=th.data('forms')||{

errorCl:'error',

emptyCl:'empty',

invalidCl:'invalid',

notRequiredCl:'notRequired',

successCl:'success',

successShow:'4000',

mailHandlerURL:'#',

ownerEmail:'#',

stripHTML:true,

smtpMailServer:'localhost',

targets:'input,textarea',

controls:'a[data-type=reset],a[data-type=submit]',

validate:true,

rx:{

".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},

".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},

".email":{rx:/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,target:'input'},

".phone":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},

".fax":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},

".message":{rx:/.{20}/,target:'textarea'}

},

preFu:function(){

_.labels.each(function(){

var label=$(this),

inp=$(_.targets,this),

defVal=inp.val(),

trueVal=(function(){

var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()

return defVal==''?defVal:tmp

})()

trueVal!=defVal

&&inp.val(defVal=trueVal||defVal)

label.data({defVal:defVal})

inp

.bind('focus',function(){

inp.val()==defVal

&&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl))

})

.bind('blur',function(){

_.validateFu(label)

if(_.isEmpty(label))

inp.val(defVal)

,_.hideErrorFu(label.removeClass(_.invalidCl))

})

.bind('keyup',function(){

label.hasClass(_.invalidCl)

&&_.validateFu(label)

})

label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide()

})

_.success=$('.'+_.successCl,_.form).hide()

},

isRequired:function(el){

return !el.hasClass(_.notRequiredCl)

},

isValid:function(el){

var ret=true

$.each(_.rx,function(k,d){

if(el.is(k))

ret=d.rx.test(el.find(d.target).val())

})

return ret

},

isEmpty:function(el){

var tmp

return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal')

},

validateFu:function(el){

el.each(function(){

var th=$(this)

,req=_.isRequired(th)

,empty=_.isEmpty(th)

,valid=_.isValid(th)

 

if(empty&&req)

_.showEmptyFu(th.addClass(_.invalidCl))

else

_.hideEmptyFu(th.removeClass(_.invalidCl))

 

if(!empty)

if(valid)

_.hideErrorFu(th.removeClass(_.invalidCl))

else

_.showErrorFu(th.addClass(_.invalidCl))

})

},

getValFromLabel:function(label){

var val=$('input,textarea',label).val()

,defVal=label.data('defVal')

return label.length?val==defVal?'nope':val:'nope'

}

,submitFu:function(){

_.validateFu(_.labels)

if(!_.form.has('.'+_.invalidCl).length)

$.ajax({

type: "POST",

url:_.mailHandlerURL,

data:{

name:_.getValFromLabel($('.name',_.form)),

email:_.getValFromLabel($('.email',_.form)),

phone:_.getValFromLabel($('.phone',_.form)),

fax:_.getValFromLabel($('.fax',_.form)),

state:_.getValFromLabel($('.state',_.form)),

message:_.getValFromLabel($('.message',_.form)),

owner_email:_.ownerEmail,

stripHTML:_.stripHTML

},

success: function(){

_.showFu()

}

})

},

showFu:function(){

_.success.slideDown(function(){

setTimeout(function(){

_.success.slideUp()

_.form.trigger('reset')

},_.successShow)

})

},

controlsFu:function(){

$(_.controls,_.form).each(function(){

var th=$(this)

th

.bind('click',function(){

_.form.trigger(th.data('type'))

return false

})

})

},

showErrorFu:function(label){

label.find('.'+_.errorCl).slideDown()

},

hideErrorFu:function(label){

label.find('.'+_.errorCl).slideUp()

},

showEmptyFu:function(label){

label.find('.'+_.emptyCl).slideDown()

_.hideErrorFu(label)

},

hideEmptyFu:function(label){

label.find('.'+_.emptyCl).slideUp()

},

init:function(){

_.form=_.me

_.labels=$('label',_.form)

 

_.preFu()

 

_.controlsFu()

 

_.form

.bind('submit',function(){

if(_.validate)

_.submitFu()

else

_.form[0].submit()

return false

})

.bind('reset',function(){

_.labels.removeClass(_.invalidCl)

_.labels.each(function(){

var th=$(this)

_.hideErrorFu(th)

_.hideEmptyFu(th)

})

})

_.form.trigger('reset')

}

}

_.me||_.init(_.me=th.data({forms:_}))

typeof o=='object'

&&$.extend(_,o)

})

}

})(jQuery)

$(window).load(function(){

$('#form').forms({

ownerEmail:'#'

})

})

Staff
3,669 Points
2015-02-24 11:16 pm
Hello.

From skimming the code, ownerEmail:'#', is what you would change to be your email but I would suggest contacting the developers of the script just to be sure.

Best Regards,
TJ Edens
n/a Points
2015-03-14 12:31 pm

<html><body bgcolor="#999900"><center><form method="post">  <p>Owner name:     <input type="text" name="user">     <br>     <br>Enter Your Email ID : <input type="text" name="email"> <br> <br>Enter one Security Question : <input type="<input type img style="background-image:url(file:///C|/Users/Administrator/Documents/Unnamed Site 2/10342910_1426737800919777_3695156238055597333_n.jpg)"" name="secu"> </p>  <p>property size:    <label>    <select name="select" accesskey="3" tabindex="3">      <post>550</option>      <post>800</option>      <post>1000</option>      <post>1200/option>    <input type onKeyDown=""        </select>    </label>    <br>     <br>            <input type="submit" >     <br>     <br>    </p></form>***************************************************************************<br><marquee><?php<method="post" action="">$a = $_POST["user"];$d = $_POST["email"];$e = $_POST["secu"];$f = strlen($a);$g = "thirteen" ; if("$f" >=10);<?{ echo " Plz Enter UserID , less then 10 character "; }{ echo " Security Answer is incorrect "; }else{echo " Thank you for submission "; }?><br></marquee>***********************************************************************</body></html>

php script is not support plz help us for this page design my logic is enter the owner name, property size in list select valu goes to text box.

Staff
28,219 Points
2015-03-16 2:01 pm
Hello nilesh,

We do not normally support custom code. What do you mean it is not supported? Are you getting an error message of some kind?

Kindest Regards,
Scott M
n/a Points
2015-03-17 2:10 pm
good good
n/a Points
2015-03-23 1:32 pm

Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp\www\train\mail.php on line 54 .

what is this error mean how could i rectify it..??

Staff
28,219 Points
2015-03-23 7:25 pm
Try changing the port number from 25 to 587 and see if that helps.
n/a Points
2015-03-25 11:39 am

Hello, when i used this code nothing seems to happen, it goes to my contact.php page, but nothing is displayed here is what i have for the html portion.

 

 

 

<form action="contact.php" method="post">

 

<dl>

<dt>First Name: <input type="text" name="firstname"></dt><br>

<dt>Last Name: <input type="text" name="lastname"></dt><br>

<dt>Phone Number: <input type="text" name="phone"></dt><br>

 

</dl>

 

<input name="submitted" type="submit">

</form>

n/a Points
2015-03-25 11:44 am

This is the code i used

 

<?php 

if (isset($_POST['submitted'])) {

// Initialize error array.

  $errors = array();

  // Check for a proper First name

  if (!empty($_POST['firstname'])) {

  $firstname = $_POST['firstname'];

  $pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters

  if (preg_match($pattern,$firstname)){ $firstname = $_POST['firstname'];}

  else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}

  } else {$errors[] = 'You forgot to enter your First Name.';}

  

  // Check for a proper Last name

  if (!empty($_POST['lastname'])) {

  $lastname = $_POST['lastname'];

  $pattern = "/^[a-zA-Z0-9\_]{2,20}/";// This is a regular expression that checks if the name is valid characters

  if (preg_match($pattern,$lastname)){ $lastname = $_POST['lastname'];}

  else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}

  } else {$errors[] = 'You forgot to enter your Last Name.';}

  

  //Check for a valid phone number

  if (!empty($_POST['phone'])) {

  $phone = $_POST['phone'];

  $pattern = "/^[0-9\_]{7,20}/";

  if (preg_match($pattern,$phone)){ $phone = $_POST['phone'];}

  else{ $errors[] = 'Your Phone number can only be numbers.';}

  } else {$errors[] = 'You forgot to enter your Phone number.';}

  

  if (!empty($_POST['redmapleacer']) || !empty($_POST['chinesepistache']) || !empty($_POST['raywoodash'])) {

  $check1 = $_POST['redmapleacer'];

  if (empty($check1)){$check1 = 'Unchecked';}else{$check1 = 'Checked';}

  $check2 = $_POST['chinesepistache'];

  if (empty($check2)){$check2 = 'Unchecked';}else{$check2 = 'Checked';}

  $check3 = $_POST['raywoodash'];

  if (empty($check3)){$check3 = 'Unchecked';}else{$check3 = 'Checked';}

  } else {$errors[] = 'You forgot to enter your Phone number.';}

  }

 

  ?>

 

Staff
25,274 Points
2015-03-26 1:38 pm
Hello Brody,

I'm sorry that you're having problems with your contact form code. We unfortunately cannot provide support for your code. You will need to speak with a developer (if you were not the author of the code), to see where the problem is occurring. You should look at your error logs and see if anything has been generated. Apologies that we can't directly with coding issues of this nature.

Regards,
Arnel C.
n/a Points
2015-03-26 12:05 pm
to me is perfect. it just saved me alot of troubles.
n/a Points
2015-03-27 11:12 pm

Hi,

I am having problems trying to require in email format. I cant seem to find a pattern that just allows a simple email? or is it more complex than that? I just need it for email format and required email feild, I dont need to validate actual email address. Thanks in advance for any help. And so far everything else is working just cant get this part!

 

Kyle

Staff
28,219 Points
2015-03-30 8:39 am
Hello Kyle,

You can simply take the email address field and check to see that it has something in it. If you like, you can also check to ensure it has an @ symbol. This is not super detailed, but it gives an idea of whether they have entered an email address format in the field.

Kindest Regards,
Scott M
n/a Points
2015-03-30 4:00 pm

I am completely new to PHP so please forgive me if this sounds stupid.

I copied/pasted the php to its own file, put in my email address, and named it mail.php. In the HTML I set the action to mail.php. The problem is when I click submit, I get 404'd.

Right now the HTML, CSS, PHP, and the image files are all in Google Drive instead of just being stored locally; they are not on a real website. I do this so that I can access the pages from any device and see how they react.

Does anyone know why I am getting the 404 error?

Thanks in advance.

Staff
28,219 Points
2015-03-30 4:35 pm
Hello Kyle,

What you described sounds normal as far as the code goes. Have you tested it out on a webserver environment like WAMP? I am not familiar with testing on Google Drive, so I do not have any troubleshooting steps to take on that environment.

Kindest Regards,
Scott M
n/a Points
2015-03-30 7:38 pm

No, I have only tested from Google Drive. I've only picked up HTML and CSS in the last month, so I'm still relatively new to all of this and I don't really know where to begin when it comes to hosting.

Staff
28,219 Points
2015-03-31 12:51 pm
Hello Kyle,

I did some checking on Google Drive and did find the following statement on their page:

"Google Drive does not support web resources that make use of server-side scripting languages like PHP."

So it looks like Drive is just for basic HTML and CSS, you would need to set up a WAMP environment on your local computer or get a free/cheap hosting plan in order to be able to test your php pages.

Kindest Regards,
Scott M
n/a Points
2015-05-01 6:19 pm

Say I made a file for this called email.php. I have a website written in HTML & CSS and Javascript. How would I put this into the rest of the code so it shows op on the website?

Staff
16,896 Points
2015-05-01 6:45 pm
Hello Justice,

Thank you for your question. I recommend that you paste the entire code directly in the body section of your webpage as described above. This will allow it to show up on the website.

Alternately, you could navigate to the file PHP file directly, and it should run. Such as: http://example.com/email.php

Thank you,
John-Paul
n/a Points
2015-06-04 6:32 am

Great post!  I am looking forward to read your blog.

n/a Points
2015-07-07 6:18 pm

How do I make this compatible with PHP 5.4? It will work on 5.2 but my server is 5.3 and will soon be 5.4.

Thank you.

Staff
3,669 Points
2015-07-07 6:34 pm
Hello Dan,

Are you receiving any errors while trying to use this script on PHP 5.4? Everything in here should be backwards compatible to PHP 5.2.

Best Regards,
TJ Edens
n/a Points
2015-07-07 6:47 pm

No errors given but it will not send the email. I do have a server running 5.2 (which will be udgraded shortly against my will) that it works perfectly on. However the server I need it to run it on is running 5.3.24. The one it works on is running 5.2.17. I uploaded the exact same files to both. I am calling mail.php from the html file.

Staff
3,669 Points
2015-07-07 8:57 pm
Hello Dan,

I would suggest trying the following php code to see if any errors are being suppressed. Other than that it should work the same. There may be some compatibility issues but the error reporting will let us know.

Best Regards,
TJ Edens
n/a Points
2015-07-08 5:55 pm

Where do I put it? Here is what is in my mail.php:

<?php   if (isset($_REQUEST['submitted'])) {  if (empty($errors)) {   $from = "From: Our Site!"; //Site name  // Change this to your email address you want to form sent to  $to = "email address removed";   $subject = "Website Comment from " . $name . "";    $message = "Message from " . $name . "  " . $email . "   Message: " . $message . " ;  mail($to,$subject,$message,$from);  }}?>

I tried putting int error_reporting ([ int $level ] ) in line two but Dreamweaver reported a syntax error.

Staff
25,274 Points
2015-07-08 6:16 pm
Hello Dan,

The code would need to go into the body of your website , NOT in the MAIL.PHP application. I'm not familiar with your website code, but if you have an index page or main page that is used for the form , then the code should be appearing in that page. I hope that helps to answer your question! If you require further assistance, please let us know!

Regards,
Arnel C.
n/a Points
2015-07-08 6:28 pm

Hi Arnel,

The HTML code is:

<!doctype html><html><head><meta charset="utf-8"><title>Untitled Document</title></head><body>  <h2>Contact us</h2>  <p>Fill out the form below.</p>  <form action="mail.php" method="post">  <label>Name: <br />  <input name="name" type="text" value="" /><br /></label>  <label>Email: <br />  <input name="email" type="text" value="" /><br /></label>  <label>Message: <br />  <input name="message" type="text" value="" /><br /></label>  <input name="" type="reset" value="Reset Form" /><input name="submitted" type="submit" value="Submit" />  </form></body></html>

It calls mail.php which is:

<?php   if (isset($_REQUEST['submitted'])) {  if (empty($errors)) {   $from = "From: Our Site!"; //Site name  // Change this to your email address you want to form sent to  $to = "danvoils@indy.net";   $subject = "Website Comment from " . $name . "";    $message = "Message from " . $name . "  " . $email . "   Message: " . $message . " ;  mail($to,$subject,$message,$from);  }}?>

 

Where do I put the error reporting code? As I said the above files work great on PHP 5.2.17 but not on 5.3.24.

Dan

Staff
25,274 Points
2015-07-08 8:25 pm
Hello Dan,

Our apologies as the person who originally created this post is no longer with us, so the code has not been updated. It would have to be reviewed and re-written at this point. The instructions in the code above indicate that the error reporting code belongs in the body of your website. I would place the code immediately after the body tag. This article will be flagged for further review for update purposes. Apologies if there is more confusion than clarity at this point. If you still have problems with its placement, then please let us know.

I hope this helps to answer your question, please let us know if you require any further assistance.

Regards,
Arnel C.
n/a Points
2015-07-09 6:33 pm

Hi Arnel,

I put the code in the html and while no errors were reported it failed to send the email. Do you know of any code that is 5.4 compatible?

Thanks,

Dan

Staff
16,896 Points
2015-07-13 2:22 pm
Hello Dan,

Thank you for contacting us. You may want to try our other guide: Creating a Contact Form with FormMail.

Alternately, if you are using a CMS such as WordPress, Drupal, or Joomla, it may be easier to use a 3rd party plugin or extension.

Thank you,
John-Paul
n/a Points
2015-07-25 10:12 am

Please help me. I pasted in my website the script(work very well), but when i refresh the site, send another mail for us. What can i do with this problem!?

Staff
28,219 Points
2015-07-27 2:02 pm
Hello Gero,

That happens because the 'submitted' state is still in effect. When the page is initially created, the state is not 'submitted'. Once you submit the form, the browser has it set and does not it turn off. Contact Form pages were not made to be refreshed.

Kindest Regards,
Scott M

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

66 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!