So you've finished up our tutorial, PHP 101, and now you want more of the meat and potatoes of making PHP work for you. One of the easiest and most effective ways to utilize PHP is my using forms. If you haven't read PHP 101, then please go back and do so, because you may run into some problems with this tutorial and the previous will give you some more insight than this tutorial,
Forms? Yeah, those nifty little things on web pages, which collect data from you, and either email it off to someone, or throw your information in a database for future reference, or something like that. Forms are one of the easiest ways to collect data from your visitors. Either by having them sign up for a mailing list, or collecting data for research or a poll, forms are what you will need to use.
Now, I'm going on the assumption that you don't know anything about forms. If you do, you may want to skip this section and move on to more of the PHP coding aspect of this tutorial.
To start off, we will need to create a new file on your system, which we will call "form.html". Open the file up and you will need to type in the following code:
<HTML>
<HEAD>
<TITLE>Form</TITLE>
</HEAD>
<BODY>
<FORM action="processform.php" method="POST" name="form" id="form">
What is your name? <INPUT type="text" name="name" id="name">
<BR><BR>
<INPUT type="submit" value="Submit" name="submit" id="submit">
<INPUT type="reset" value="Reset" name="reset" id="reset">
</FORM>
</BODY>
</HTML>
|
Nothing all that complicated, this will create a single text box, asking the user what his / her name is. Along with Submit and Reset buttons.
To start the in depth explanation of the code, let me just straight down to the opening FORM tag.
<FORM action="processform.php" method="POST" name="form" id="form">
The first part of the tag is action=, this is where you specify what file you are going to use to analyze the contents of the form. In this instance, we are going to be calling upon "processform.php" which we will be creating later.
The next thing to specify is the method. There are two methods which you can use, either POST or GET. In a nutshell, GET assigns the form data to the environment variable of QUERY_STRING, then submits it, while POST simply sends the data. POST is slightly more stealth, as the user will never see the data being passed to the script. GET is most commonly used when sending information between two different windows.
Following the method, there are two additional variables. name and id, which are used for identification purposes, especially with such languages as JavaScript. I usually set the two variables to equal the same thing, just for convenience purposes, and make them fairly descriptive, like this instance where we call it "form".
Now we have our FORM tag, we now have to build the components in the form, and then close it all out. After the prompt, "What is your name?", we have our first of 3 INPUT tags. The first one is the box that the user will type his / her name into. INPUT tags can represent many input types, including text boxes, buttons, radio buttons and check boxes. In this instance, it is going to be a text box, so we set the type variable to be "text". The last two fields are id and name, and hold the same purpose as before. We will set their values to "name" because that is what the text box will be holding the value of, the user's name.
After a couple of line breaks, we throw in the last 2 INPUT tags. The first of the two is going to be our submit button, the second will be a reset button. For submit buttons, we set the type to be "submit", and we will set the name and id to be the same, just to make things uniform. We are now going to set a new variable, value. value specifies what the button says when it is displayed on the screen. We have the value set to Submit, but you can call it whatever you want. The perk of the submit type, is that when the user clicks on it, it will perform the action specified in the FORM tag. Therefore, the submit button is what will execute the form.
The next button is the reset button. It will be the same as the previous button, but we will set all the variables (type, value, name and id) to be reset. reset, like our good friend submit has a special purpose as well. When the user clicks on this button, the contents of all the fields on the form will be reset back to their initial value, which in this case, the name text box will be reset back to being blank, because there is no value set for it.
Our form is now complete, so we will close it off with the closing FORM tag, and upload this bad boy to our host.
Now that we have "form.html" complete, and up on our server, let’s go ahead and pull it up in a web browser. It shouldn't be anything spectacular, just a basic form, with a single field, and 2 buttons. Type in your name and click on "Submit", you should get a page cannot be displayed error. If not, you must have a file called processform.php already in that directory. What happened is the form tried to send the information from the form, to a file that doesn't exist yet, hence the error.
On that note, I want you to create another file, and name it "processform.php". Immediately, I want you to upload it to the server, and try to submit your form again. Wow, a blank screen. Yeah, the file now exists, and doesn't give us an error. Only problem with that is that the script is not doing anything with the data being received, and our form is worthless.
Enough fun and games, lets get down to coding. Close out of your web browser, and open up the "processform.php" file for editing. What we're going to do is write a script that will take the user's name and give them a simple greeting, like "Hey [name], how are you doing?” Since I'm assuming you know a thing or two about PHP, why not give it a try, and then come back to the tutorial. I'll give you a hint, start your file with <? and end it with ?> ;).
Hopefully you figured it out on your own; if not, that's cool, that's why I'm writing this tutorial.
I would hope your file looks at least like this:
<?
?>
If not, may I suggest my PHP 101 tutorial? If you did get that far, let me say, good job, you're 66% of the way done. Within the delimiters, you will need to add the following line:
echo "Hey $name, what's shakin'?";
Or whatever lame greeting you want. To call the name of the person from the form, you just have to use the $name variable. The name of the variable came from the name of the field on the form. If the name of the field was blah, then the variable that holds the data for that field would be called $blah.
Congratulations, you just completed your first form and PHP script to process it.
Now for my next topic, form validation with PHP. Open up "processform.php" again, and insert a few line breaks after the first delimiter (after the echo statement). In that white space, we are going to add an if structure, to check to see if the user actually inputted a name.
if ($name=="") {
echo "I thought I said to type in your name?";
} else {
|
You can indent the second echo statement, and then add a } on the next line to complete the structure. Upload this new copy of the script, and pull up your form again. Try to submit the form without a name. Now you get the message "I thought I said to type in your name?" instead of "Hey , what's shakin'?" You could also check for certain values, like if the name is equal to your name, you could spit out "Hey, what's my name too!", or something like that. The possibilities are endless.
On a side note, you could use a simple JavaScript form validation routine to accomplish the same, but if the user's browser doesn't handle JavaScript, then you're pretty much SOL.
So we built are form, we are validating that the value isn't null, and now we're going to optimize what we have. Yep, optimize it. How? Well we're going to ditch the 2 files, and combine it into a single PHP file.
Let’s create a new file, and call it "allinone.php". Open it up, and input the following code:
<?
if ($name=="") {
?>
<HTML>
<HEAD>
<TITLE>Form</TITLE>
</HEAD>
<BODY>
<FORM action="allinone.php" method="POST" name="form" id="form">
What is your name? <INPUT type="text" name="name" id="name">
<BR><BR>
<INPUT type="submit" value="Submit" name="submit" id="submit">
<INPUT type="reset" value="Reset" name="reset" id="reset">
</FORM>
</BODY>
</HTML>
<?
} else {
echo "Hey $name, what's shakin'?";
}
?>
|
That code should look familiar for the most part. All we're doing is adding in a giant if structure. If the variable $name is null, then display the form, if not, analyze the data. The form will keep looping if the user doesn't enter in a name, but if they do, it will give them the greeting.
In case you have multiple fields on your form, this method won't be that efficient. In that situation, you will want to use a different if () { statement. The appropriate statement would be either if ($REQUEST_METHOD=="POST") { or if ($REQUEST_METHOD=="GET") { depending on if you use POST or GET for your form method. This will check the environment variable, REQUEST_METHOD, to see if the form is being sent via the POST or GET method.
Well, that's the first part of the tutorial; you should now have a basic understanding of HTML forms, and how to utilize PHP to analyze the data. Now it's time to learn how to do something a bit more functional than just redisplaying the form contents back to the user.
Have you ever seen a site that has a form that gives you the opportunity to contact the people who run the site? If not, please go here for an example. What these forms do, is link to a PHP script (or ASP, Perl...) and that script emails the data to who ever is set up as the recipient, usually webmaster@.
PHP has the perfect little function for such a thing, it's called mail(). If you want to check out PHP.net's manual page on mail() then by all means, check it out here. Their site will give you some in depth information about using mail() and some of the problems and pitfalls and what not.
The most simplistic use of mail() is like this:
mail ($to, $subject, $message);
Very basic, all you do is specify the recipient, the subject and the message. You can also add more complex things such as additional header information,
Cc:, Bcc:, and even who the email is from (good for spoofing messages against people who are too dumb to check the header information).
Well, let's try this idea out, and throw up our own contact form. First thing we need to do, as always, is create a new file. This time we will call it
"contactform.php" We will be using just a single file for this, as explained previously.
I am going to give you a basic overview of what you will need to do, and you can try it on your own. If you crash and burn, you can go further into the
tutorial, and use the code provided.
We are going to use an if structure like in the previous bit of code we did, but we will need to check the REQUEST_METHOD variable to see if it's value is
POST. Under the start of the if structure, we will place the code for our form. Our form should have the following fields: name, email address, subject,
message, and 2 buttons, send and reset. After we build our form, we will need throw an else into the structure, put in some code to send the email, and then
close it all off.
Did you get all that? Probably, not, but that's ok.
The first thing mentioned, was starting an if structure that checked the REQUEST_METHOD variable.
<?
if ($REQUEST_METHOD=="POST") {
?>
|
That should look familiar, if not, go back and start at the beginning of this tutorial again, and take notes!
Next up is our form, with 4 different boxes, and 2 buttons.
<HTML>
<HEAD>
<TITLE>Contact Form</TITLE>
</HEAD>
<BODY>
<FORM action="contactform.php" method="POST" name="form" id="form">
Your Name?<BR><INPUT type="text" name="name" id="name">
Your Email?<BR><INPUT type="text" name="email" id="email">
Subject?<BR><INPUT type="text" name="subject" id="subject">
Message?<BR><TEXTAREA name="message" id="message"></TEXTAREA>
<BR><BR>
<INPUT type="submit" value="Send Email" name="submit" id="submit">
<INPUT type="reset" value="Reset Form" name="reset" id="reset">
</FORM>
</BODY>
</HTML>
|
This script is a bit more complex than our original form, but not too far from being the same. The only new thing there is the use of the TEXTAREA tag.
TEXTAREA is basically a multi-lined input box. We use this for the message, so the user can more room to type and see what they are typing and all that good
stuff. The TEXTAREA tag makes use of a closing tag as well, in case you wanted to put text in the box, you would put it between the tags, instead of using
value=. Everything else is old information from earlier in the tutorial. Note, we used different name’s and id's for each component on the form, and we
changed the value= for the submit and reset buttons, so that they have different text when the form is viewed.
<?
} else {
$to = "your@email.address";
$from = "From: \"$name\" <$email>";
mail($to, $subject, $message, $from);
echo "Hey $name, thanks for emailing us, you should get a reply in 3-5 business days.";
}
?>
|
Here is the else portion of the structure. We assign two variables before we do anything. $to is where you put your email address in, so you receive the
emails being sent, $from contains the formatting for the additional header information. From: isn't a standard built into mail(), so you have to define it
in the extra header portion of the function.
The next line contains the mail() function, calling our 2 variables we just defined, as well as the $subject and $message information from the form. This line
will send the information to whatever email address you put in for $to.
The last line is a simple echo statement, to let the user know that their email was sent, and that it should be replied to shortly.
That's all there is to it! You can add additional if structures within the else portion to check to see if any fields were left blank, or to block people
from a certain email address from using the form, et cetera.
That pretty much wraps up using forms, and using the mail() function of PHP. What I'd like to do now, is take our last example, and give you a more complex
version of it. This new code will contain some error checking, as well as utilize HTML encoded email. The previous examples of using mail() sent plain text
messages, lame.
We are going to create one last file, and call it "contactform2.php", and input the following code:
<?
if ($REQUEST_METHOD=="POST") {
?>
<HTML>
<HEAD>
<TITLE>Contact Form, the Sequel</TITLE>
</HEAD>
<BODY>
<FORM action="contactform2.php" method="POST" name="form" id="form">
Your Name?<BR><INPUT type="text" name="name" id="name">
Your Email?<BR><INPUT type="text" name="email" id="email">
Subject?<BR><INPUT type="text" name="subject" id="subject">
Message?<BR><TEXTAREA name="message" id="message"></TEXTAREA>
<BR><BR>
<INPUT type="submit" value="Send Email" name="submit" id="submit">
<INPUT type="reset" value="Reset Form" name="reset" id="reset">
</FORM>
</BODY>
</HTML>
<?
} else {
if ($name=="" or $email=="" or $subject="" or $message="") {
echo "You have to fill out the entire form, go back and try again.";
} else {
$to = "your@email.address";
$from = "From: \"$name\" <$email>";
$subject = "[via form] " . $subject;
$additional = "$from\r\nReply-To: $email\r\nContent-Type: text/html; charset=iso-8859-1;
$message = " <HTML>
<HEAD>
<TITLE>$subject</TITLE>
</HEAD>
<BODY>
<P align=LEFT>$message</P>
</BODY>
</HTML>";
mail($to, $subject, $message, $additional);
echo "Hey $name, thanks for emailing us, you should get a reply in 3-5 business days.";
}
}
?>
|
Hopefully that wasn't too overwhelming. The initial form was not altered at all, so there is no need to discuss it. The first amendment is the new if
structure under the else statement. That particular if structure checks to see if any of the fields on the form were left blank, and if so, it advises the
user accordingly.
If all the fields are filled in, it then goes on to send the email. Our $to and $from variables are still the same, but I threw in a $subject variable.
$subject? Isn't that one of the fields on the form? Yep, it is, but, we aren't changing what the subject is, we're just appending "[via form]" to the front
of the subject line. Then, when the email hits your box, you can see who's using your form.
After appending the subject line, we define another new variable, $additional. This variable contains the additional header information in it, separated by
\r\n. We start the variable off with the $from variable, and then add Reply-To: and Content-Type:. Reply-To simply tells your email client to reply to a
certain address. It isn't truly necessary, but it's in good practice to use it. The last bit of header information is the most important. Content-type: is
used to tell an email client to read the message as HTML and not plain text.
The last variable is our $message. This time, the message won't be displayed as plain text, so we are going to utilize HTML. As you can see, $message is
now formatted like a web page, using $subject for the title, and the original $message in the BODY tag. You can put whatever HTML you want in here, change
the font, or make the background different, whatever floats your boat.
The next line is the mail() function. Nothing too special here, we simply changed the $from variable to the $additional variable to utilize the additional
header information we wanted to use. After that, we have the same echo line as before, just letting the user know what's going on.
That's it, after reading this, you should be able to form with forms, and the mail() function of PHP. If not, read it again. If so, then try using the
information to your advantage, and have fun with you. If you're really adventurous, you could start having emails sent to you when people visit a certain
page on your site, or if you're malicious, and have a site that gets a lot of traffic, you could set up a function that will email your victim every time
that page (or all your pages) is loaded. You could even generate random subject lines, senders, and messages to avoid a mass delete. Remember though kids,
the header information never lies, and even though your email says "From: JoMamma@FudgeYou.com", the header will still say it came from your server.
Hope you found this informative, and thanks for reading!
|