PHP for Beginners: Part 4 – PHP With Forms and Final Notes

Posted in Coding, Coding, PHP, Tutorials3 years ago • Written by 11 Comments

In the last part, I showed you how to use PHP to send e-mail messages. In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts more useful.

For those who missed the previous parts:

Part 1

Part 2

Part 3

Setting Up Your Form

Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in how to write your form but I will show you three of the main pieces of code you must know:

<input type="text" name="thebox" value="Your Name">

This will display a text input box with Your Name written in it as default. The value section of this code is optional. The information defined by name will be the name of this text box and should be unique.

<textarea name="message">
Your message goes here
</textarea>

Will display a large scrolling text box with the text ‘Please write your message here.’ as default. Again, the name is defined and should be unique.

<input type="submit" value="Submit">

This will create a submit button for your form. You can change what it says on the button by changing the button’s value.

All the elements for your form must be enclosed in the

tags. They are used as follows:
<form action="process_script.php" method="post">
Form elements and formatting etc.
</form>

The form’s action tells it what script to send its data to (in this case its process_script.php). This can also be a full URL (e.g. http://www.mysite.com/scripts/process_script.php). The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark e.g. http://www.mysite.com/process_script.php?name=nick

It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser’s address bar.

Getting The Form Information

The next step is to get the data the form has submitted into your script so that you can do something with it. There are basically two different methods of getting the data into PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The benefit of GET, though is that you can submit information to the script without a form, by simply editing the URL.

This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:

yourpage.php?user=nick

could show Nick’s page and:

yourpage.php?user=laura

could show Laura’s page, using the same script.

It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:

yourpage.php?user=nick&referrer=1stwebdesigner&area=6

These could all be accessed separately using the GET variables user, referrer and area.

To get a variable which has been sent to a script using the POST method you use the following code:

$variableName=$_POST['variable'];

which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variableName.

Similarly, if you are using the GET method you should use the following:

$variableName=$_GET['variable'];

This should be done for each variable you wish to use from your form (or URL).

Creating The Form To Mail Script

To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user’s comments to you.

Firstly, create this form for your HTML page:

<form action="mail.php" method="post">
Your Name: <input type="text" name="name" /><br />
E-mail: <input type="text" name = "email" /><br />
Comments:<br />
<textarea name="comments"></textarea><br />
<input type="submit" value="Submit" />
</form>

This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script:

<?php
function checkOK($field) {
if (eregi("\r",$field) || eregi("\n",$field)) {
die("Invalid Input!");
}
}

$name = $_POST['name'];
checkOK($name);
$email = $_POST['email'];
checkOK($email);
$comments = $_POST['comments'];
checkOK($comments);

$to = "[email protected]";
$message = "$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address: $email";
if(mail($to, "Comments From Your Site", $message, "From: $email\n")) {
echo "Thanks for your comments!";
} else {
echo "There was a problem sending the mail. Please check that you filled in the form correctly.";
}
?>

Remember to replace [email protected] with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your comments form.

The first part of that script may look a bit strange:

function checkOK($field) {
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}

You don’t really need to worry about what this is doing, but basically, it stops spammers from using your form to send their spam messages by checking special characters are not present in the input which can be used to trick the computer into sending messages to other addresses. It is a function which checks for these characters, and if they are found, stops running the script.

The lines like:

checkOK($name);
[etc..]

run this check on each input to ensure it is valid.

As you can see, using forms with PHP can be very effective. Now it’s time to share with you some final small things you should know about PHP (which as i think, should go in the very first part :) But i placed them where they are).

Comments

As with any programming language, it is quite important to comment in your script. If you are working on a script with someone else you must let them know what you code does and if you are distributing your script you will need to show people how to edit it. Even if you are the only one who will use your script it is useful to comment so that you can edit it at a later date.

In PHP there are two ways you can comment. One way is used for single line comments and the other is used mainly for comments that go over one line. A single line comment is written as follows:

// Your comment can go in here

Everything after the // will be ignored when the script is executed. You can even place these on the end of another line e.g.

print "Hello $name"; // Welcome to the user

Another way of commenting is by using multi-line comments:

/* The following piece of code will take the input
the user gave and will check that it is valid before
adding it to the database */

Anything between the /* and the */ will be ignored. It is important that you always close this type of comment as not doing so could make your script not work.

Print, Echo and HTML

As you may have noticed during this tutorial I have actually used 4 different ways of outputting information to the browser:

echo ("Text here");
echo "Text here";
print ("Text here");
print "Text here";

To clarify, all of these do the same thing and you can use any or all of them in a script. There is no reason to even use the same type all through a script. The only problem you may find is that all the ” in the HTML code must be replaced with \” which, if you have a lot of code, could take a very long time. This brings me to a very useful part of PHP. If, for example, you created the header of a page dynamically in PHP, then had the static page and finally a dynamic footer you can do the following:

<?php
Top PHP code in here
?>
HTML Code
<?php
Bottom PHP code in here
?>

This gets even better as the PHP code will just continue from where it was left off so you could do the following:

<?php
IF Statement {
?>
HTML For IF Being Correct
<?php
} else {
?>
HTML For IF Being Wrong
<?php
}
?>

You must always remember to close IF statements and loops, though, as it is very easy to forget.

One Line Prints

Being able to place HTML code into your PHP is very useful, but what happens if you want to put the value of a variable into the code. Unlike when using an echo or print statement, you can’t just put in the variable name as this section is not actually part of the PHP code. Instead you must just put in a little PHP.

For example, if you wanted to print someone’s name from a script with HTML formatting you would do the following:

<font face="Arial" size="7" color="red"><strong><?php echo($variableName); ?></strong></font>

* – As again, Never Do Inline Styling!

In the above code you have just added in the following PHP:

<?php echo($variableName); ?>

Which is exactly the same as the following PHP code:

<?php
echo($variableName);
?>

But all put onto one line.

Conclusion

This tutorial has given you some of the basics of PHP and should allow you to do most things you will want to. For a much more in depth look you should visit PHP.net, the official homepage of PHP. One major omission of this tutorial, you may have noticed, is using PHP with a database. Happily, 1stWebDesigner already have one tut on it: Getting Started With MySQL DB and PHP with PHPMyAdmin. You should know this, as this is one of the major reasons that people use PHP and because there are many options.

Hope I helped you in learning such wonderful and powerful language as PHP. What would you like to learn more about PHP? Next articles ideas… I’d love to hear your thoughts in the comments below!

If you enjoyed this article, get email updates (it's free).

Join over 77,235 Subscribers Today.

7 Written ArticlesWebsite

Hi there! My name is Nick Plekhanov. I'm a passionate web developer and user interface designer from Russia, experienced in PHP, and MySQL along with the beautiful XHTML and CSS under jQuery stuff. I've been doing web development for 3 years. Here, I'll be your PHP coder, sometimes designer, and SEO expert. My own web development blog is coming really soon. If you’d like to connect with me, follow me on Twitter.

11 Comments Best Comments First
  • ghazal parvati

    Tuesday, November 30th, 2010 10:25

    1

    Hi,
    I am far from being a PHP expert, but among the few things I know is that “eregi” is deprecated/not recommended after php 5 :
    http://www.php.net/manual/en/function.eregi.php
    preg_match being the alternative
    Anyhow, thks for your tuts

    0
    • AC

      Sunday, April 10th, 2011 12:40

      5

      I agree with ghazal parvati! eregi is deprecated.
      Anyway, some interesting things to read on this page! thx

      0
  • Mike

    Thursday, January 13th, 2011 19:07

    4

    Agreed. Awesome. I’ve had hell with a form I’m working on and this is exactly what I was looking for!

    0
  • Aleksej Tisionok

    Wednesday, December 1st, 2010 10:39

    3

    It would be usable if there were links to other parts

    0
  • Rahul

    Tuesday, November 30th, 2010 21:15

    2

    i was actually waiting for this 4th part , i haven’t missed a part , i read them all and i guess i improve here :))) thank you for this explanation , loved the post :)

    0
  • sant

    Sunday, July 3rd, 2011 10:16

    6

    pls send me the tuts of the bedinning parts…i am not able to find..can anyone let me know..plss

    0
    • Rean John Uehara

      Sunday, July 3rd, 2011 15:11

      7

      Hi, I’ve updated the article and linked to the previous parts. You should see the link just after the introduction. :)

      0
  • Dawid

    Monday, January 23rd, 2012 22:56

    11

    It’s working!

    0
  • Ned

    Tuesday, December 20th, 2011 13:41

    10

    I absolutely love your blog and find most of your post’s to be just what I’m looking for. can you offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on a lot of the subjects you write related to here. Again, awesome blog!

    0
  • Tarek

    Wednesday, September 28th, 2011 19:29

    9

    Hi there !

    Frankly i would like to learn the principles of Ortiented object programming , i tried many times to understand the concept of classes , encapsulation ,inherritence , and so on but they are still not obvious for me .

    Thank’s for all the things you share with us , it’s a great job that u do man

    0
  • daso

    Monday, July 4th, 2011 22:40

    8

    I’m very happy I stumbled across your site and these php tutorials, I am just starting teaching myself to code in PHP and these tutorials are very helpful. Would it be possible to cover search bars? or databases and adding data, getting data out of them and manipulating it? Keep up the great work.

    0
  • Dawid

    Monday, January 23rd, 2012 22:56

    11

    It’s working!

    0
  • Ned

    Tuesday, December 20th, 2011 13:41

    10

    I absolutely love your blog and find most of your post’s to be just what I’m looking for. can you offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on a lot of the subjects you write related to here. Again, awesome blog!

    0
  • Tarek

    Wednesday, September 28th, 2011 19:29

    9

    Hi there !

    Frankly i would like to learn the principles of Ortiented object programming , i tried many times to understand the concept of classes , encapsulation ,inherritence , and so on but they are still not obvious for me .

    Thank’s for all the things you share with us , it’s a great job that u do man

    0
  • daso

    Monday, July 4th, 2011 22:40

    8

    I’m very happy I stumbled across your site and these php tutorials, I am just starting teaching myself to code in PHP and these tutorials are very helpful. Would it be possible to cover search bars? or databases and adding data, getting data out of them and manipulating it? Keep up the great work.

    0
  • sant

    Sunday, July 3rd, 2011 10:16

    6

    pls send me the tuts of the bedinning parts…i am not able to find..can anyone let me know..plss

    0
    • Rean John Uehara

      Sunday, July 3rd, 2011 15:11

      7

      Hi, I’ve updated the article and linked to the previous parts. You should see the link just after the introduction. :)

      0
  • Mike

    Thursday, January 13th, 2011 19:07

    4

    Agreed. Awesome. I’ve had hell with a form I’m working on and this is exactly what I was looking for!

    0
  • Aleksej Tisionok

    Wednesday, December 1st, 2010 10:39

    3

    It would be usable if there were links to other parts

    0
  • Rahul

    Tuesday, November 30th, 2010 21:15

    2

    i was actually waiting for this 4th part , i haven’t missed a part , i read them all and i guess i improve here :))) thank you for this explanation , loved the post :)

    0
  • ghazal parvati

    Tuesday, November 30th, 2010 10:25

    1

    Hi,
    I am far from being a PHP expert, but among the few things I know is that “eregi” is deprecated/not recommended after php 5 :
    http://www.php.net/manual/en/function.eregi.php
    preg_match being the alternative
    Anyhow, thks for your tuts

    0
    • AC

      Sunday, April 10th, 2011 12:40

      5

      I agree with ghazal parvati! eregi is deprecated.
      Anyway, some interesting things to read on this page! thx

      0

Comments are closed.

54.243.14.193 - unknown - unknown - US