PHP Lessons 8: Server Constants and HTML Forms

by
Guest-GS

Hello there, it’s been a while, I’ve been very busy with work and some personal project, so i had to delay the PHP courses, but anyway, I’m back and today we’ll have a look at Server Constants.

Take a look at www.geekscribes.net, on the right side, we have a search form, when you type in a search keyword and press Enter, the page loads and it fetch every results according to what you typed. Ever wonder how it works? Don’t go any further, today I will show you bring a boring html form to life.

Before I start, if you missed the array tutorials, then please, go to the link below, and read the post, give it a try.. because you’ll need to understand how arrays work in order to understand this lesson fully.

Here’s the link:

http://www.geekscribes.net/blog/2009/08/11/php-lessons-arrays/

So let’s begin.. Server Constants are also called Predefined Variables, which are just arrays in fact. I will list some of them, but today, we’ll have a look at two of them..Below is a list:

$_SERVER:     This grabs almost all information about the server your website resides on.

$_GET:        The HTTP GET variables are in there

$_POST:       HTTP POST Variables (Very useful with forms)

$_FILES:      Used with forms also, but only for upload purposes. LIke uploading files to a server. Think Rapidshare.

$_REQUEST:    HTTP Request variables (We can say it is a mix of $_GET and $_POST.
              But don't rely on it too much. The only way to rely on it is to use the function array_map() ).
              Also, it's a bit unsecured to use this one, so avoid!

$_SESSION:    Session Variables
              (This is a handy built-in function use to store data. Like Username, Password, User Clicks.
              It can be useful, but can be hard to understand).

$_COOKIE:     HTTP Cookies.
              (This is use to store information on your computer. Like which preference you choosed for a website.
              Or if you checked Remember Me when logged in, a cookie is set on your computer.)

We’ll deal with $_SESSION and $_COOKIE in a later lesson, so no worries. :)

Today, we’ll have a look at $_GET and $_POST..and in order for you to understand, we will use an HTML Form to send a Request to the server.. Now, what is “send Request to the server”? Basically, you are making a request for a resource from the server, or are sending something to it. Whatever you put in a form is sent to the server in a special message (or request). The server can then use this to determine what you want and what to do.

There are two methods of sending requests, namely GET and POST. When you use GET, whatever data to be sent is passed in the URL (or action) if the form, in plain text. Using POST, the data is sent in the background making the transfer invisible to the user. Following logic, you won’t be sending login information via GET since the password would be visible in the address bar in plain text. For this, you’ll use POST. For other uses, such as getting an item’s price, GET is perfectly acceptable.

Note, if no value is specified for the action attribute, it means that the page refers to itself. If the page is “test.php”, it’s as if action was set to “test.php”. Also, if you don’t set a method, by default it’s “GET”. So beware if you’ll be using it to send passwords etc.

<form method="post" action="name.php">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

Ok, i won’t go through all this, you should at least have a fair knowlegde of HTML if you are studying PHP, but what I will point out is, the part where it says ” <form method=”post” action=”name.php”> ”

The “method” attribute in the form tag is set to post, which means we are going to use POST ( $_POST for php ) and the page to process the code is the same where our form lives, which is set in the “action” attribute of the form tag, so it’s set to nothing, which means, use the same page as our form, the PHP Code will be in the same page.

Ok, let’s make a test. Fire up your code editor or use the old notepad, and type that in a file, say “test.php”. It HAS to end in .php, not .html or .htm, even if it includes HTML codes. If it doesn’t end in .php, it won’t get pre-processed, and you’ll just see your PHP code in plain text.

<?php
  if(isset($_POST['submit']))
  {
     echo "<pre>";
     print_r($_POST);
     echo "</pre>";
  }
?>
<form method="post" action="">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

Type in your name in the input box, press enter and see the results.. My output was like this:

Array
(
   [name] => Kevin
   [submit] => Output my name
)

print_r is a function in PHP that allows you to display the contents of an array, in key-value pairs. Here, we are printing the $_POST array. I did say these are just arrays with form data stored in them. :)

The output therefore means:

Name: is the name of the field in our form. The text-box was called “name”
Submit: is the name of the submit button ( Note: We can get rid of it from our array)

Note that “Output my name” is given as the value for submit. The value attribute of a submit input type is what’s displayed on the button in HTML.

Now that we know what’s stored in our POST Array, we can easily output it. We can acess it through the $_POST array. Like below:

<?php
  if(isset($_POST['submit']))
  {
     echo "My name is ". $_POST['name'];
  }
?>
<form method="post" action="">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

So the code first check if the form has been submited:

if(isset ($_POST['submit']) )

If the array key named “submit” has a value (any value) set, then process the codes inside of the IF statement.

$_POST['name'], simply because, in our HTML FORM, the input where you typed your name, has the name attribute set to “name”. If you have another field, say, age. You would type $_POST['age'] to access it.

It’s all about arrays. You can also interact with it using a foreach loop. Most array operations in PHP could theoretically be performed on those $_GET, $_POST, … variables.

Now for the $_GET constant, unlike $_POST, the value is sent through the URL.

The form method is set to get instead of post! Try the code below, then look at your URL in the address bar

<?php

  if(isset($_GET['submit']))
  {
     echo "My name is ". $_GET['name'];
  }
?>
<form method="get" action="">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

You will notice that your URL is now :

http://localhost/test.php?name=Kevin&submit=Output+my+name
test.php:            This is the page we are using right now
test.php?name=kevin: This is the fun part. The ?name=<name>, is called a Query String, name is the $_GET Variable, and "kevin" is the value assigned to that variable.

The query strings are separated from the domain by a “?” and are separated by ampersands. Spaces are substituted with “+” symbols. Note, there is a maximum length on the URL length, and hence the amount of data that can be sent via GET. So if you have to send a ton of data, use POST.

Another advice is don’t use multi-word names separated by spaces for the “name” attribute of fields. You don’t want to see: “?my+name=John+smith” in the URL. Then in PHP, you’d do $_POST['my_name'] as the space became an underscore. A whole lot of headaches! So don’t do it! For the sake of fellow programmers.

test.php?name=kevin&submit=Output+my+name : the Submit is just the name of the submit button, you shouldn’t care about that too much

IMPORTANT Notice: When using the $_GET Method, NEVER, and I mean NEVER use password field with it. Use $_POST when you form contains password field. Unless of course you want the whole world to see your password is in fact “password” :p

One thing you can try is, use the $_SERVER variable to check what the Actual URL Query string is set to. Try the code below:

<?php
if(isset($_GET['submit']))
  {
     echo "My name is ". $_GET['name'];
     echo "<hr />"; //<hr /> just makes a horizontal rule (line) appear.
     echo "The URL Query String is ". $_SERVER['QUERY_STRING'];
     echo "<hr />";
  }
?>
<form method="get" action="">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

You will notice that the URL Query String is set to : name=<name you typed>&submit=Output+my+name. That is, whatever comes after the “?” mark.

If you don’t want the “submit” part to appear in the URL, simply do not set the “name” and “value” attributes. Note, this works for GET only. If you used POST, the form doesn’t work unless ” name=”submit” ” is set.

A bonus: add this just after the last HR tag, you will see what the default $_SERVER Array holds. Code below:

echo "<pre>";
print_r($_SERVER);
echo "</pre>";

You will get something like:

Array
(
   [HTTP_HOST] => localhost
   [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5
   [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
   [HTTP_ACCEPT_LANGUAGE] => en-gb,en;q=0.5
   [HTTP_ACCEPT_ENCODING] => gzip,deflate
   [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
   [HTTP_KEEP_ALIVE] => 300
   [HTTP_CONNECTION] => keep-alive
   [HTTP_REFERER] => http://localhost/test.php?name=Kevin&submit=Output+my+name

   ... and it continues with other stuff.
)

That ton of details is a lot of details about your server and its current configuration.

Then you can experiment through the Array like:

echo $_SERVER['HTTP_HOST'];

Which will return ‘localhost’, as shown in the $_SERVER Global Array.

Ok, this should get you started.. Now let’s have a look at how we can get rid of the submit name into our $_POST Array. In order to accomplish this, we will use a built-in function of PHP. This is fun. Code below:

<?php

   if(isset($_POST['submit']))
   {
     // we use the array_pop function to get rid of the last element
     // In our case the last element is the submit button
     //Actually, it returns the last element of the array.
     //Since we are not capturing it, it's discarded. The array is shortened by 1 element.

     array_pop($_POST);
     echo "<pre>";
     print_r($_POST);
     echo "</pre>";
     echo $_POST['name'];
   }
?>

<form method="post" action="">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

Try the code, and you will see that unlike the previous one, the line “[submit] => Output my name” is gone. That’s how we get rid of it (Note: It will remove the submit button IF it is the last element in the array, if not, use an IF statement with a foreach loop to pull it out). Like below:

<?php
   if(isset($_POST['submit'])){
     foreach($_POST as $key => $post)
     {
        if($key != "submit")
        {
          echo $post;
        }
     }
   }
?>
<form method="post" action="">
   <label for="name">Type your name</label>
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Output my name" />
</form>

If you do a print_r of $_POST, the submit will be there, because we didn’t use a function to pull it from it’s original array,but from every key and it’s value, we check if there is something which isn’t equal to “submit”, the IF statement will get rid of it, then when we echo the temporary variable $post, we get only our name.

Read this post again and again, until you understand how HTML Forms and PHP Works, next time there will be more from Complex Forms. Try fiddling with the $_GET and $_POST arrays and see the effects. You can also set values in $_GET and $_POST though it’s a bit useless. They are arrays after all. :D

This article was contributed by Tipa of Mu-Anime

[seriesposts title="PHP Lessons" titletag=h3 listtype=ul orderby=date name="PHP Lessons" ]

  • ramesh

    thanks for the update :)

  • http://www.geekscribes.net InF

    You’re welcome. :)

    We’ve been a bit busy with university work and the like. We have a dissertation to do. But we hope to be able to provide new posts again soon.

  • http://www.mu-anime.com Tipa

    Hmm one thing to point out.

    If you don’t define the method attribute in your html form, it is set to $_GET by default.

    So make sure you always define it, especially if your form contain fields like password! And again, don’t rely too much on $_REQUEST unless you badly need it…

    Next lesson will be about $_SESSION and $_COOKIES!

  • http://www.geekscribes.net InF

    I added the default GET part to the article. :)

  • http://www.downloadmessenger-now.com/ Download Messenger

    thanks for the lesson