Click to See Complete Forum and Search --> : Creating a contact form with php
menre
Aug 24th, 2009, 08:02 AM
Hi Everyone,
I have a website that I need to design and create a 'contact' form for. Could someone point me to or help me with some php code for doing this please?
I am comfortable with html, so I would be happy if you can explain to me how to go about it please.
Thank you in advanced.
Menre
visualAd
Aug 25th, 2009, 08:41 AM
The first place to look is the PHP website:
http://uk.php.net/manual/en/language.variables.external.php
The good news, is at first you need not make any changes to the HTML page you wrote (or are about to write). You need to ensure you give all form inputs a name and choose weather to send the form via HTTP POST (in the body of the HTTP request) or HTTP GET (in the URL of the request). Set the action attribute of the form element to "process.php" or whatever you wish to call the script that handles the processing.
In your process.php page, for starters, to check that it is receiving the input just enter the following line:
print_r($_GET);
print_r($_POST);
When you have got that working I will show you how to validate the data and send the email.
menre
Aug 26th, 2009, 01:49 PM
Hello,
Thank you for your response to my previous post. I have done as you said or at least almost all that you said.
I went through an online tutorial somewhere and got it right. But there are still many issues with my work so far, and I do really need your help to correct them.
When I click the 'Send button' on my html page it goes (which is great), but opens the php processing page straight away. It processes the form correctly. However, I fear something there, because I see all the information I entered in form appearing in the address bar too. Don't you see this as a security risk?
Then other questions
1) I would like the form on my website to display a page with a message 'Your message has been submitted to us'. How do I create that?
2) If a field is left by the user, how do I do it so that is says for example 'you did not your email address'?
3) Where else can it be sent to? It just shows me the processing php page. Can I create a database with the form so that whenever people submit forms I should be able to see all, or they all get stored somewhere?
I have included both the php and html code of my work below for you to have a look at please.
A) This is the HTML page code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Your information</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="information.php" method="get">
Name: <input type="text" name="Name" /><br />
Password: <input type="password" name="Password" maxlength="10" /><br />
Location: <input type="text" name="Locat" /><br />
Email: <input type="text" name="Email" /><br />
Age range: <select name="AgeR">
<option value="Under 20">Under 20</option>
<option value="20-30" selected="selected">20-30</option>
<option value="31-40">31-40</option>
<option value="41-60">41-50</option>
<option value="51above">51 and above</option>
</select><br /><br />
Comments:<br /> <textarea name="Comm" rows="10" cols="70">Enter your comments
here</textarea><br /><br />
<input type="radio" name="FavSubject" value="Art"> Art</input>
<input type="radio" name="FavSubject" value="Biology"> Bilogy</input>
<input type="radio" name="FavSubject" value="Chemistry"> Chemistry</input>
<input type="radio" name="FavSubject" value="Design"> Design</input>
<br />
<input type="checkbox" name="Languages[]" value="PHP" checked="checked">
PHP</input>
<input type="checkbox" name="Languages[]" value="CSS"> CSS</input>
<input type="checkbox" name="Languages[]" value="CPP"> C++</input>
<input type="checkbox" name="Languages[]" value="Delphi"> Delphi</input>
<input type="checkbox" name="Languages[]" value="Java"> Java</input>
<input type="checkbox" name="Languages[]" value="JavaScript"> JavaScript</input>
<br /><input type="submit" />
</form>
</body>
</html>
B) This is the php code for processing it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Feedback</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-utf-8" />
</head>
<body>
<?php
$_GET['Languages'] = implode(', ', $_GET['Languages']);
$_GET['Comm'] = str_replace("\n", "<br />", $_GET['Comm']);
print "Your name: {$_GET['Name']}<br />";
print "Your password: {$_GET['Password']}<br />";
print "Location: {$_GET['Locat']}<br />";
print "Email: {$_GET['Email']}<br />";
print "Age range: {$_GET['AgeR']}<br /><br />";
print "Comments:<br />{$_GET['Comm']}<br /><br />";
print "Your favourite subject: {$_GET['FavSubject']}<br />";
print "Languages you code: {$_GET['Languages']}<br />";
?>
</body>
</html>
Once again, thanks.
Menre
kows
Aug 26th, 2009, 02:56 PM
if all you're doing is submitting a contact form, using GET (storing it in the URL) is fine -- but I'd generally suggest using POST for such things. just change the method of your <form> from "GET" to "POST," and then change any references to the global variable $_GET to $_POST in your "processing" page.
if you want proper form validation, then I suggest you combine your HTML form and processing script into the same file. then, you can do something like this:
<?php
//we should always show the form unless the data is incomplete
$showform = true;
//has this form been submitted?
if($_SERVER['REQUEST_METHOD'] == "POST"){
//it has. process the form
//initialize the error array
$errors = array();
//first, loop through $_POST and check if any values were empty
foreach($_POST as $key => $value){
if(strlen(trim($value)) == 0) $errors[] = "{$key} was empty";
}
//if the $errors array is empty, we can proceed
if(!count($errors)){
//the data was validated, we don't want to show the form now
$showform = false;
//this is where you would enter data into a database, send a mail, or do whatever else. I'll leave that to you.
//this will print the raw data submitted to the form
echo '<pre>'; print_r($_POST); echo '</pre>';
}
}
//--done processing form!
//do we show the form?
if($showform):
//yes! show the form.
//are there errors?
if(count($errors)):
?>
<blockquote>
<h3>There were errors with your submission:</h3>
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</blockquote>
<?php endif; ?>
<!-- your form goes here -->
<form method="post">
Name: <input type="text" name="name" value="<?php echo htmlentities($_POST['name']); ?>" /><br />
Email: <input type="text" name="email" value="<?php echo htmlentities($_POST['email']); ?>" /><br />
<input type="submit" value="Submit" />
</form>
<?php else: ?>
<!-- your "successful" message goes here -->
<h1>Success!</h1>
<p>Thank you for contacting us!</p>
<?php endif; ?>
I've only included two fields on my form, but you should get the idea. take note of the "value" attribute -- it will re-print old information when there is an error so that the user doesn't need to enter the entire form in again.
as always, ask questions if you don't understand something! I tried to be verbose with my comments!
visualAd
Aug 26th, 2009, 03:42 PM
I would first like to commend you for actually reading my post and having a go and making some progress yourself. This is something I don't see a lot of around here lately.
Below are the answers to your questions and some critical tips on the code you have written.
Hello,
When I click the 'Send button' on my html page it goes (which is great), but opens the php processing page straight away. It processes the form correctly. However, I fear something there, because I see all the information I entered in form appearing in the address bar too. Don't you see this as a security risk?
The variables are shown in the URL because the method attribute of the form is set to "get". This causes the browser to encode all the form variables within the URL query string (everything after the question mark).
This can be a security issue as any sensitive information can be easily passed on unintentionally (i.e. sending someone a link). The entire URL, including the query string may also be logged by a proxy server (especially in corporate environments).
It is generally only a good idea to use method=get when you are implementing a search feature or if the information being entered is to be used later for the generation of links. In your scenario, it is better to use method="post". This causes the encoded information to be sent within the body of the HTTP request and not the URL.
It is important to remember that the information is not invisible, if the connection is not encrypted. The data is still sent as plain text and can be intercepted.
1) I would like the form on my website to display a page with a message 'Your message has been submitted to us'. How do I create that?
Once you have processed the data successfully, you can redirect to another page by sending an HTTP location header:
header('Location: thank_you.html', True, 303); // 303 = see other
You can also make it a little more personalised by redirecting to a PHP page; e.g. you may want to say "Thank you [Name]" or give the user ticket number they can quote in later correspondence.
To transfer information between the pages, I would recommend a session. Opening a session causes PHP to set a cookie containing a session ID; this session ID is used to recall a file stored on the server (containing variables) for that user each time they make a request. To open a session just call session_start(); at the top of each page and add any variables you wish to be available in other pages to the $_SESSION array.
information.php
<?php
session_start(); // ensure this is statement is executed before any HTML / echo / print output
// notice that we are using the POST variable not get (you also need to change the HTML form method to post too)
$_SESSION['name'] = $_POST['Name'];
header('Location: thank_you.php', true, 303);
?>
thank_you.php
<?php
session_start();
?>
<html>
<body>
<p>Thank you for your message <?php each(htmlspecialchars($_SESSION['name'])) ?> </p>
</body>
</html>
Notice how any output that originally came from a form is escaped with the htmlspecialchars() function, this prevents any HTML entered in the form field (usually maliciously) from being interpreted by the browser.
Notice also how the PHP echo statement is embedded within the HTML and no HTML tags are generated using the echo statement. This improves readability and allows you to maintain the structure of the page; so I would recommend that you do this when mixing HTML and PHP in the same page.
More information on sessions can be found here: http://www.php.net/sessions
2) If a field is left by the user, how do I do it so that is says for example 'you did not your email address'?
You can check weather or not a field has been supplied by a user by using the isset() and doing a simple test for a blank string:
if (! isset($_POST['varname'])) {
// variable never sent, this is usually encountered with <select> fields
}
if (trim($_POST['varname']) == '') {
// variable was sent, but it was left blank
}
I also recommend strongly that you not only verify the form has been filled in correctly, you also validate the input. I.e. if you are expecting an integer, make sure you get one; if you are expecting one of several values, ensure that the values fall into this range.
Unfortunately unsecured forms are one of the most utilised attack vectors for websites that could cause the site, sever or the database to be compromise. This is why it is so important to validate the data sent.
When you determine that a value is entered incorrectly, you can redirect to an error page that shows an error message. This can include a "Go Back" link that asks the user to correct the form and submit again. Again, you can use the session to store information about the error and print this on the error page.
3) Where else can it be sent to? It just shows me the processing php page. Can I create a database with the form so that whenever people submit forms I should be able to see all, or they all get stored somewhere?
You could send an email to the webmaster with a summary of what was entered, you could save the data in a file or you could add a record to a database.
Would you be able to tell me the version of PHP you are using and weather or not it has mysql enabled? You can find out by calling the phpinfo() function.
A) This is the HTML page code.
I recommend that you indent your HTML code to make it more readable. I also recommend that you include a hidden element of the same name for all <select>, checkbox and radio fields. This will ensure that even if the user doesn't make a choice, a variable is still generated in PHP:
<input type="hidden" name="Languages" value = "">
<input type="checkbox" name="Languages[]" value="CSS"> CSS
<input type="checkbox" name="Languages[]" value="CPP"> C++
<input type="checkbox" name="Languages[]" value="Delphi"> Delphi
<input type="checkbox" name="Languages[]" value="Java"> Java
<input type="checkbox" name="Languages[]" value="JavaScript">
Also, If you are using HTML 4 you should not close the <input> tag and <br> tags should be written as <br> not <br /> (this is XHTML).
B) This is the php code for processing it.
As mentioned above, I strongly recommend that you fully validate all your form variables and escape any that you output using htmlspecialchars().
I also recommend that you output only the variables using echo / print and not any HTML.
E.g.:
print "Age range: {$_GET['AgeR']}<br /><br />";
Becomes:
<?php // nothing ?>
Age range: <?php print $_GET['AgeR'] ?> <br><br>
It is also good practice not to produce any output on your form processing script and redirect to another script when producing output. the is desirable because if the use clicks the refresh button on the processing page, it will cause the browse to prompt for the information to be resent. Users will normally just click "yes" without reading it.
menre
Aug 30th, 2009, 08:41 PM
Hello,
Thanks to everyone that responded to my posts. I have worked with your advice and my form is now partly working. I used the code you gave me and it worked well. However, I still have a little problem with the overall form. I have spent the last few days reading more online tutorials on how to send a form to a database and it has been worth the effort.
My problems now are:
1) When I combine the code you gave me in your response and the one I found from the tutorial nothing works. I think I am putting my code from the tutorial in the wrong place as I try to combine it with yours. I have two files and I use the two files to send the form to a table in my database and it works correctly (I am happy about that). But I still want the page to display other things your added to your code, such as if a field is left out by a user, the form displays this, and the tutorial did not cover that so, I had to add their code and yours together. But by doing so, I ran into trouble and nothing works again.
if you want proper form validation, then I suggest you combine your HTML form and processing script into the same file. then, you can do something like this:
I agree with you the above statement is a very good practice, but I tried it with this work and ran into trouble, so had to separate the files again to get it right. The code below are for the two files I created after reading the tutorials. the first one is the xhtml file, while the second one is the php processing file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Feedback </title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-utf-8" />
</head>
<body>
<?php
include("connect.inc.php");
$thisPage=$_SERVER['PHP_SELF'];
?>
<?
$name=$_POST['name'];
$email=$_POST['email'];
$comment=$_POST['comment'];
$number=$_POST['number'];
mysql_connect("localhost", "root", "") or
die(mysql_error());
mysql_select_db("student") or die (mysql_error());
mysql_query("INSERT INTO `feedback` VALUES ('$name', '$email', 'comment', '$number')");
Print "Your information has been succesfully added to the database. ";
?>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Feedback</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1 " />
</head>
<body>
<form action="process.php" method="post">
Your name: <input type="text" name="name"> <br />
E-mail: <input type="text" name = "email"> <br />
Comments : <input type="text" name = "comment"> <br />
Number: <input type="text" name="number"> <br />
<input type="submit" value="Submit">
</form>
</body>
</html>
//this is where you would enter data into a database, send a mail, or do whatever else. I'll leave that to you.
I saw and loved the above line of comment, but in my attempt to do that I ran into difficulty.
2) I hope I am not asking too much here. Could you explain to me how to put my database code there please?
Would you be able to tell me the version of PHP you are using and weather or not it has mysql enabled? You can find out by calling the phpinfo() function.
I have checked it and it is PHP version 5.1.4. It has mysql enabled and I have been able to create a database for the purpose of this feedback/contact us form.
Once again, thanks.
Menre
kows
Aug 31st, 2009, 10:25 AM
I took your code and put it together.
<?php
//this is a required file.
require_once("connect.inc.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Feedback</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1 " />
</head>
<body>
<!-- start form -->
<?php
//we should always show the form unless the data is incomplete
$showform = true;
//has this form been submitted?
if($_SERVER['REQUEST_METHOD'] == "POST"){
//it has. process the form
//initialize the error array
$errors = array();
//first, loop through $_POST and check if any values were empty
foreach($_POST as $key => $value){
if(strlen(trim($value)) == 0) $errors[] = "{$key} was empty";
}
//if the $errors array is empty, we can proceed
if(!count($errors)){
//the data was validated, we don't want to show the form now
$showform = false;
//this is where you would enter data into a database, send a mail, or do whatever else. I'll leave that to you.
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment = mysql_real_escape_string($_POST['comment']);
$number = mysql_real_escape_string($_POST['number']);
mysql_query("INSERT INTO `feedback` VALUES ('$name', '$email', '$comment', '$number')");
/* we don't need this anymore. you can remove this comment and 3 lines below it.
//this will print the raw data submitted to the form
echo '<pre>'; print_r($_POST); echo '</pre>';
*/
}
}
//--done processing form!
//do we show the form?
if($showform):
//yes! show the form.
//are there errors?
if(count($errors)):
?>
<blockquote>
<h3>There were errors with your submission:</h3>
<ul>
<?php foreach($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</blockquote>
<?php endif; ?>
<!-- your form goes here -->
<form method="post">
Your name: <input type="text" name="name" value="<?php echo htmlentities($_POST['name']); ?>"> <br />
E-mail: <input type="text" name="email" value="<?php echo htmlentities($_POST['email']); ?>"> <br />
Comments : <input type="text" name="comment" value="<?php echo htmlentities($_POST['comment']); ?>"> <br />
Number: <input type="text" name="number" value="<?php echo htmlentities($_POST['number']); ?>"><br />
<input type="submit" value="Submit">
</form>
<?php else: ?>
<!-- your "successful" message goes here -->
<h1>Success!</h1>
<p>Thank you for contacting us!</p>
<?php endif; ?>
<!-- resume your html -->
</body>
</html>
please note, I took out your calls to mysql_connect() and mysql_select_database(). I assumed that you stored these in connect.inc.php, and if you aren't -- you probably should. you can place the file outside of the "public_html" or "www" directory on your webserver and make it inaccessible from the web, but still usable by your web applications. connect.inc.php would just look like:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("student") or die (mysql_error());
?>
also, you should make sure you realize how I sanitized your form input using mysql_real_escape_string(). this will prevent things like SQL injection, but will also stop a user from accidentally breaking your form by typing in the wrong thing. in the code you gave me, if someone's "name" field had an apostrophe ( ' ), it would cause the mysql_query() to not execute; the syntax would have been broken. mysql_real_escape_string() will escape those characters to make sure that A) your queries aren't broken and B) the user isn't doing something malicious.
menre
Aug 31st, 2009, 03:53 PM
Hello,
Thank you very much for your help. Just one thing please. When I run the code that you helped me put together, I get the error message below.
Notice: Undefined variable: errors in /usr/local/apache2/htdocs/demo/corrected.php on line 56
I could not find the error on line 56.
Menre
kows
Sep 1st, 2009, 01:35 AM
move the following:
//initialize the error array
$errors = array();
to right below the definition of $showform (so, about 5-6 lines up)
or, you can make PHP not show notices by calling error_reporting() at the top of your script:
error_reporting(E_ALL ^ E_NOTICE);
basically, PHP is giving you a notice that $errors is not defined when the form is not submitted, and since I use $errors later on as an array, it isn't defined if the form hasn't been submitted. there are a few other ways you could get around this, too, like if the form hasn't been submitted then you don't bother checking if count($errors) is true. anyway, either of the above solutions should work fine.
visualAd
Sep 1st, 2009, 05:22 AM
It is better to leave error reporting set to E_ALL as it will help identify simple coding errors such as spelling mistakes in variable names a lot quicker; and ensure that you have initialised all variables by assigning them a value before attempting to read them.
menre
Sep 1st, 2009, 02:42 PM
Hello,
Thank you everyone. The form is now working and doing what I expected it to do. I appreciate all your time and effort in helping me to solve this problem.
Once again, thank you.
All Hail PHP, And Long Shall It Live!
Menre
menre
Sep 1st, 2009, 03:38 PM
Hi,
Sorry that I have to reopen this topic again due to some browser errors that I am getting with my form. When I open the form page in Internet Explorer, I get the error message below
<br /><b>Notice</b>: Undefined index: number in <b>/usr/local/apache2/htdocs/demo/corrected.php</b> on line <b>75</b><br />
and when I open it in Firefox, I get the error message '<br />' appearing inside the field after Your Name, E-mail, Comments and Number.
But when I delete the '<br />' from the textfields in Firefox and send the message it works fine.
Again, when I use one single quotation mark while sending my form but it appears with a double quotaion mark in my database. For example, if I say menre's page, it appears in my database table as menre""s page.
Could there be something I am doing wrong again somewhere?
Menre
visualAd
Sep 1st, 2009, 03:53 PM
The error is generated from this line:
Number: <input type="text" name="number" value="<?php echo htmlentities($_POST['number']); ?>"><br />
Again, if the variable has never been set, attempting to read it will throw out a notice. To suppress the error message on your form fields in the HTML you can use the error suppression operator "@", this will prevent the notice from being shown for that single statement:
Number: <input type="text" name="number" value="<?php echo htmlentities(@$_POST['number']); ?>"><br />
I would only recommend you use this when there is a reasonable expectation that the variable may not be set.
menre
Sep 2nd, 2009, 01:02 PM
Hello All,
Thank you so much for your help in solving this problem. I have added the '@' symbol to the place you suggested. Now, the form is working correctly, I am happy and sure the client will be happy too.
Once again, thank you. I will now be serious with learning PHP.
Menre
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.