Forms In PHP

Forms In PHPPHP was originally designed for use on the Internet, and although you can now use it for command line application and GUIs, its main purpose remains working on the web.

When it comes to the web, HTML has ruled unchallenged for some years as the de facto standard for displaying information, even more so now that WAP usage has evaporated.

This means that if you want to write a frontend for your PHP web application, you need to understand HTML.

DammnnBlockedUnblockFollowFollowingMar 19HTML is a very simple markup language that offers its users a great deal of flexibility.

While this might make it easy to learn and write in, it makes the job of web browsers such as Internet Explorer and Mozilla much harder, because they need to be able to cope with thousands of exceptions.

A movement was started to redefine how web pages are designed to that HTML would contain only content information, with a new language, CSS storing the style information.

There were also some recommending that XML was the way forward for data and that HTML could be eliminated altogether.

While the XML argument made sense, many realized that there were simply too many HTML based websites in existence to be able to just drop HTML, so the standard HTML was born — a modification of HTML that makes it XML-compliant.

The code you see in this article is all XHTML-compliant, and I recommend you keep to this in your work.

You may notice that all HTML attributes are surrounded by quotes, and all HTML tags used in this article are closed either by using </tag> or <tag/> — these are two of the rules of enforced in XHTML.

While teaching HTML and XHTML is outside the scope of this article, we are at least going to look at creating HTML forms, which are the primary means of sending data to PHP.

DESIGNING A FORMA “Form” on the web is considered to be zero or more form elements, plus a submit button.

These forms are designed to electronically replicate the forms we have all filled in hundreds of times before in real life — signing up for a bank account, a passport, etc.

You start your from using the <form> HTML tag, and you end with </form>.

By separating forms like this, you can have multiple forms on one page.

Given the above definition, here is the most basic form of HTML.

<form><input type = "submit"></form>That will simply show a button with “submit” written on it, which will not submit any data when clicked.

There are two attributes to the <form> tag that you should be aware of and use: action and method.

Action sets the location of the page that will handle the results of the form — the place where the variable should be sent, Method describes how the data should be submitted, and you have two options: GET and POST.

GET and POSTWhen defining the method, a web browser should use to send variables to the page specified by your action, you either use GET or POST.

Both send variables across to a page, but they do so in different ways.

GET sends its variable in the URL of your visitor’s web browser, which makes it easy to see what was sent.

However, it also makes it very easy for visitors to change what was sent, and, moreover, there is usually a low limit on the number of characters that can be sent in a URL — often fewer than 250.

As a result, if you send long variables using GET, you are likely to lose large amounts of them.

POST sends its variable behind the scenes, which means it is much harder to mimic, cannot be changed without some effort on your visitor’s behalf, and has a much higher limit on the amount of data that can be sent.

The downside to using POST is that browsers will not automatically resend post data if your user clicks the back button, leading to a message like “The data on this page needs to resent!”, which often confuse users.

This does not happen with GET, because browsers consider GET URLs the same as any other URL, and happily resend data as needed.

You can set how much data PHP should accept by editing the post_max_size entry in your php.

ini file — it is usually set to 8M by default, allowing your users to transfer up to 8 megabytes.

Given this newfound knowledge, here’s the same form again, this time using action and method.

It will still look the same as our previous effort, but this time it will use POST to send data to someform.

php:<form action = "someform.

php" method= "post"><input type = "submit" /></form>A WORKING FORMWe now have enough information to construct a working form, so here goes:That will submit three variables to someform.

php: Name, Password, and Age.

Form variables are given names using the name attribute — the name you use here will be used in the PHP script that receives the variable.

The default value of a filed can be set using the value attribute, which means that the Name text box will be set to sam by default.

The Age filed, which is presumably contain numbers like 18, 34 etc is the same type as the Name field, which is likely to contain strings like, Donald, Saurav, Sarah etc.

HTML does not have any way to say “restrict this field to number only,” which means users can enter their age as “Elephant,” if they wish.

Never trust input from users!.

And now a more complicated form, using various other types:<html> <body> <form action = "someform.

php" method = "post"> Name: <input type = "text" name = "Name" value = "sam" /> <br /> Password: <input type = "password" name = "password" maxlength = "10" /> <br /> Age range: <select name = "Age"> <option value = "Under 16"> Under 16 </option> <option value = "16-30" selected = "selected">16-30</option> <option value = "31-50"> 31-50 </option> <option value = "51-80"> 51-80 </option> </select> <br /> <br />Life story: <br /> <textarea name = "story" rows="10" cols="80"> Enter your life sorty here </textarea> <br/> <br /> <input type="radio" name="favesport" value="Tennis" /> Tennis <input type="radio" name="favesport" value="cricket" /> Cricket <input type="radio" name="favesport" value="Baseball" /> Baseball <input type="radio" name="favesport" value="Polo" /> Polo <br /><input type="checkbox" name="Languages[]" value="PHP" checked="checked" /> PHP<input type="checkbox" name="Languages[]" value="C++" /> C++ <input type="checkbox" name="Languages[]" value="Java" /> Java<br /> <input type="submit"> </form> </body></html>>There are several pieces of particular importance in there, so you should read through carefully:maxlength = “10” is one of the attributes for the password element — this can be used in normal text boxes too and acts to restrict the number of character that can be typed into the value of maxlength (10, in the example).

Age is now a drop-down list box — note how the name attributes is placed inside the select element, but each individual option element has its own value.

The text inside the value attribute is what is submitted to the form handler specified in the form’s action attribute.

The text after each option and before the next option is the text the user will see.

Selected is specified as an attribute of one of the option elements, which means that the option will be the default selection of the parent select list.

Life story is a textarea element.

Note that it has attributes rows and cols to specify the size of the text are in characters.

All members of a radio element group need to have the same name attribute.

The name attribute is used to inform the browser which group each radio element is part of so that users can select only one at a time.

All members of a checkbox group need to have the same name attribute, and that name attribute needs square brackets [] at the end.

The reason for the square brackets is that it informs PHP that the value may be an array of information — user can select multiple values, and PHP will place them all into an array of the value of the name attribute.

checked is specified as an attribute of one of the checkbox, which means it will be checked by default.

GET is the method attribute for the form, meaning that the information sent through to the handler page which is someform.

php, it will be sent in the location bar of the browser as a normal URL.

This will allow you to see how easy it is to change variables in the location bar and, by entering lost of text into the story textarea element, how easy it is to have too much data for GET to handle.

HANDLING DATAHandling data coming in form HTML pages is by far the most common task in PHP.

Let’s look at a few of them.

register_globalsPrior to PHP 4.

1, variables submitted from external sources — such as session variables, cookies, form filed etc — were automatically converted to variables inside PHP, as long as register_globals was enabled in the php.

ini file, which it was by default.

These variables were also accessible through the arrays $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_SESSION_VARS, etc.

Imagine the following situation: you have a secure site, where the member are identified by logon names, such as “Administrator,” “joe”, and “Peter”.

The pages on this site track the username by way of the variable UserID, which is stored in a cookie on the computer when the user authenticates to the site.

With register_globals enabled, $UserID is available as a variable to all scripts on your site, which, while helpful, is a security hole.

Here is a URL that demonstrates the problem: http://www.




When register_globals is enabled, all variables sent by GET and POST are also converted to variables and are indistinguishable from variables from other sources.

The result of this is that a hacker could, by using the URL above, impersonate someone else-like root!working around register_globalsIn order to provide a middle ground for users who did not want to use the super-globals but also did not want to enable register_globals, the function import_request_variable() was introduced.

This copies variables from the superglobal arrays into variables in their own right and takes two parameters: a special string of which types of variables to convert, and prefix that should be added to them.

The special string can contain “g” for GET variables, “p” for POST, “c” for cookies, or any combination of them.

The prefix works in almost the same way as the prefix to extract() does, except that it does not add an underscore, which means that scripts relying on older functionality can use import_request_variables() to get back to the old manner of working.

As with the prefix used in extract(), the string is appended to the beginning of the names of each variable created to ensure there is no naming clash with existing data.

Here are some of the examples:import_request_variables("p", "post");import_request_variables("gp", "gp");import_request_variables("cg", "cg");Note that the order of the letters in the first parameter matters — in gp, for example, any POST variables that have the same names as GET variables will overwrite the GET variable.

In other words, the GET variables are imported first, then the POST variable.

If we had used pg, it would have been POST and then GET, so the ordering is crucial.

Once import_request_variables() is used, you can use the new variable immediately, like this:print $_GET['name'];import_request_variables("g", "var");print $varName;If you don’t specify a prefix, or if the prefix is empty, you will get a notice to warn you of the security issue.

HANDLING OUR FORMYou now know enough to be able to program a script to handle the advanced form presented previously.

Our variables will be coming in using the GET method.

In the real world, you would use POST because it is possible that users will submit large quantities of data in the “Life story” filed; however, using GET here lets you see how it all works.

Because we are using GET method, we should be reading our variable from $_GET.

The first two fields sent are Name and Password, which will both contain string data.

Rember that the password HTML from element transmits its data as plain text, which means that both Name and Password can be handled the same way.

As tehy are coming in via GET, the values entered by our visitors will be in $GET[‘Name’] and $_GET[‘Password’] — note that the cases have been preserved from the form exactly and that, as per usual, PHP considers $_GET[‘name’] to be different from $_GET[‘Name’].

The next input is the select list box Age, which will return a string value — either “Under 16”, “16–30”, “31–50” or “51–80”.

From the PHP point of view, this is no different from handling input from a text box other than that we can, to a certain extent, have an idea about what the values will be.

That is, under normal circumstances, we will always know what the values will be, as our users have to pick one option from a list we present.

However, it takes only a little knowledge to “hack” the page so that users can input what they like — just remember the golden rule: “Never trust users input.

”The story text is element submits data in the same way as a normal text box does, with the difference that it can contain newline characters?..

The chances are that you want to HTML line breaks (the <br /> tag) as well as the?.line breaks, so you should use nl2br(), like this:$_GET['story'] = nl2br($_GET['Story']);Next, we get to our radio buttons, Favesport.

As radio buttons can only submit one value, this one value will be available as a normal variable in $_GET[‘FaveSport’].

This is in contact to the checkbox from elements that follow — they have the name language[], which will make PHP covert them into a single array of values, available in $_GET[‘Languages’].

We can put the whole script together using the above information.

This script parses the form properly:The entire script to handle the HTML form we created is just eight lines long, of which six are just print statements reading from the $_GET array.

The first two lines aren’t anything special either: line one converts the language array created from the checkboxes into one string using implode(), and lie two converts the new line characters in the story text are into HTML line break.

However, the script above contains a bug.

What happens if our users don’t check any boxes for languages.The answer is that browser will not send any languages information, which means that $_GET[‘languages’] will not be set, which in turn means that the first line in the script will cause an error.

The solution is simple: use if (isset($_GET[‘languages’])) to check whether there is a value set.

If there is, use implode() to make it a string, and if not, put a dummy text string in there like, “You didn’t select any languages!”SPLITTING FORMS ACROSS PAGESVery often it is necessary to split up one long form into several smaller forms, placed across several pages.

When this is the case, you can pass data from page to page by using the hidden from the element, storing the answer in session value, or storing the answer in a database.

Of the three, you are most likely to find using hidden form element the easiest to program and the easiest to debug.

As long as you are using POST, data size will not be a problem, and the advantage is that you can view that HTML source code at any time to see if things are working as planned.

Of course, that also means that hackers can view the source code, so you should really only resort to the hidden field if you can’t use sessions for some reason.

If our existing form was part one of a larger set of forms, we would need to append the following HTML to the bottom of part of the forms so that the values are carried over to part three:<input type="hidden" name="name" value="<?php print $_GET['Name'];?>" /><input type="hidden" name="Password" value="<?php print $_GET['Password'];?>" />You would need to have all the other there also, but it works in the same way, so there is no point repeating them all here.

VALIDATING INPUTAny sensible site should include server-side validation of variables, because they are much harder to hack, and they will work no matter what browsers your visitors are using.

Basic input validation in PHP is done using the functions is_strin(), is_numeric(), is_float(), is_array(), and is_object().

Each of these functions takes just one parameter, a variable of their namesake, and return true if that variable is of the appropriate type.

For example, is_numeric() will return true if the variable passed to it is a number, and is_object() will return true if its variable is an object.

There is one other function of this type that works the same way but is useless for validation, and that is is_resoure() — it’s mentioned here for the sake of completeness.

The three basic validation checks you should conduct on input are whether you have each of your required variables, whether they have a value assigned, and whether they are of the type you were expecting.

From there, you can conduct more complicated checks, such as whether the integer values are in the range you would expect, whether the string value has enough characters, whether the arrays have enough elements, etc.

Here are some examples:<?php<!DOCTYPE html><html><body> // is the $Age variable set with a numeric value between 18 and 30.if (isset($Age)) { if (is_numeric($Age)) { if (($Age > 18) && ($Age < 30)) { // input is valid } else { print "sorry, you are not right age!"; }} else { //empty or non-numeric print "Age is incorrect!" } } else { print "please provide a value for age;" }// is $SpouseAge either unset, blank, or between 18 and 120?if (isset($SpouseAge) && $SpouseAge != "") { if (is_numeric($SpouseAge)) { if (($SpouseAge >= 18) && ($SpouseAge < 120)) { //input is valid } else { print "spouse is not the right age!"; } } else { print "spouse age is incorrect!"; } } else { // input is valid, no spouse; print "You have no spouse.

"; }// is $Income non-negaitve?if (isset($Income)) { if (is_numeric($Income)) { if ($Income >= 0) { //input is valid } else { print "Your income is negative!"; } } else { print "please provide a numeric value for income"; } } else { print "please valid a value for income.

"; }</body></html>?>For more specific parsing of character type in a variable, the CTYPE library is available.

There are eleven CTYPE functions in total, all of which work in the same way as is_numeric(): you pass a variable in and get either true or false back.

The matches are absolute, which means that ctype_digit() will return false for the value “123456789a” because of the “a” at the end, as the script shows:$var = "123456789a";print (int)ctype_digit($var);Similarly, “123 ” will fail the ctype_digit() test because it has space after the number.

There is no match for floating point number available, as ctype_digit() matches 0–9 without also matching the decimal point.

As a result, it will return false for 123.


For this purpose, you need to use is_float().


. More details

Leave a Reply