2/12/2010 1 Chapter 6: Web Programming with PHP Saminda Premaratne PHP • PHP is similar to JavaScript, only it’s a server-side language PHP code is embedded in HTML using tags when a page request arrives, the server recognizes PHP content via the file extension (.php or.phtml) the server executes the PHP code, substitutes output into the HTML page the resulting page is then downloaded to the client user never sees the PHP code, only the output in the page PHP is a loosely typed language. • developed in 1995 by Rasmus Lerdorf (membe r of the Apache Group) originally designed as a tool for tracking visitors at Lerdorf's Web site within 2 years, widely used in conjunction with the Apache serverdeveloped into full-featured, scripting language forserver-side programming free, open-source server plug-ins exist for various servers now fully integrated to work w ith mySQL databases • The acronym PHP means (in a slightly recursive definition) PHP: Hypertext PreprocessorWhat do You Need? • Server supports PHP –You don't need to do anything special! * –You don't need to compile anything or install any extra tools! –Create some .php files in your web directory - and the server wil l parse them for you. * Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point). • Most servers support PHP –Download PHP for free here: http://www.php.net/downloads.php –Download MySQL for free here: http://www .mysql.com/downlo ads/index.html –Download Apache for free here: http://httpd.apache.org/download.cgi Test PHP and Apache Test PHP and Apache •Test the Apache Server as • Create php folder in D:\SoftwareInstallation\ApacheGroup\Apache2\htdocs or where you have installed Apache •Create first.php in htdocs\php folder (D:\SoftwareInstallation\ApacheGroup\Apache2\htd cs\php) with the following lines: <?php phpinfo(); ?> •Open the browser and type the following link http://localhost:8088/php/first.php the port number 8088 may be different in your installation. You will be prompted the php information on the browser.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
• PHP is similar to JavaScript, only it’s a server-side language PHP code is embedded in HTML using tags when a page request arrives, the server recognizes PHP content via the file
extension (.php or .phtml)
the server executes the PHP code, substitutes output into the HTML page the resulting page is then downloaded to the client user never sees the PHP code, only the output in the page PHP is a loosely typed language.
• developed in 1995 by Rasmus Lerdorf (member of the Apache Group) originally designed as a tool for tracking visitors at Lerdorf's Web site within 2 years, widely used in conjunction with the Apache server developed into full-featured, scripting language for server-side programming free, open-source server plug-ins exist for various servers now fully integrated to work with mySQL databases
• The acronym PHP means (in a slightly recursive definition) PHP: Hypertext Preprocessor
What do You Need?
• Server supports PHP
– You don't need to do anything special! *
– You don't need to compile anything or install any extra tools!
– Create some .phpfiles in your web directory - and the server willparse them for you.
* Slightly different rules apply when dealing with an SQL database (as will be explained whenwe get to that point).
• Most servers support PHP
– Download PHP for free here: http://www.php.net/downloads.php
Variables• Variables in PHP are represented by a dollar sign followed by
the name of the variable. The variable name is case-sensitive.
• Variable names follow the same rules as other labels in PHP. Avalid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores,e.g.
Constantsmay be defined using the define( ) function, and retrieved by
its name or the constant( ) function
e.g.
White space
Any number of spaces, tabs and new lines are allowed between
•• Notice how echo ‘Notice how echo ‘55xx55=$foo’ outputs $foo rather than replacing it with=$foo’ outputs $foo rather than replacing it with 2525
•• Strings in single quotes (‘ ‘) are not interpreted or evaluated by PHPStrings in single quotes (‘ ‘) are not interpreted or evaluated by PHP
•• This is true for both variables and character e scapeThis is true for both variables and character e scape--sequences (such as “sequences (such as “\\n” orn” or““\\\\”)”)
The PHP $_GET and $_POST variablesare used to retrieve information from
forms, like user input.
The most important thing to notice when dealing with HTMLforms and PHP is that any form element in an HTML page willautomatically be available to your PHP scripts.
The example HTML page above contains two input fields anda submit button. When the user fills in this form and click onthe submit button, the form data is sent to the"welcome.php" file.
The $_GET variable is used to collectvalues from a form with
method="get".
The $_GET variable is an array of variable names and valuessent by the HTTP GET method.
The $_GET variable is used to collect values from a form withmethod="get". Information sent from a form with the GETmethod is visible to everyone (it will be displayed in thebrowser's address bar) and it has limits on the amount of
The "welcome.php" file can now use the $_GET variable to catch the form data (notice that thenames of the form fields will automatically be the ID keys in the $_GET array):
Note: When using the $_GET variable all variablenames and values are displayed in the URL. So thismethod should not be used when sendingpasswords or other sensitive information!However, because the variables are displayed inthe URL, it is possible to bookmark the page. Thiscan be useful in some cases.
Note: The HTTP GET method is not suitable on
large variable values; the value cannot exceed 100characters.
• The PHP $_REQUEST variable contains thecontents of both $_GET, $_POST, and$_COOKIE.
• The PHP $_REQUEST variable can be used toget the result from form data sent with boththe GET and POST methods.
Welcome<?php echo$_REQUEST["name"]; ?>.<br />You are <?php echo$_ REQUEST["age"]; ?> years old!
Example
The $_POST variable is used to collectvalues from a form with
method="post".
• The $_POST variable is an array of variablenames and values sent by the HTTP POSTmethod.
• The $_POST variable is used to collect values
from a form with method="post".Information sent from a form with the POSTmethod is invisible to others and has nolimits on the amount of information to send.<form action="welcome.php" method="post">Enter yourname: <input type="text" name="name" />Enter yourage: <input type="text" name="age" /><input type="submit" /></form>
When the user clicks the "Submit" button, the URL will not contain any form data, and willlook something like this:
Welcome <?php echo $_POST["name"]; ?>.<br />You are <?php echo $_POST["age"]; ?> years old!
http://www.onestepsoltuions.biz/welcome.php
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that thenames of the form fields will automatically be the ID keys in the $_POST array):
• Variables sent with HTTP POST are not
shown in the URL
• Variables have no length limit
• However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
• The PHP $_REQUEST variable contains thecontents of both $_GET, $_POST, and$_COOKIE.
• The PHP $_REQUEST variable can be used to
get the result from form data sent with boththe GET and POST methods.
Welcome<?php echo$_REQUEST["name"]; ?>.<br />You are<?php echo$_ REQUEST["age"]; ?> years old!
Example
Maintaining State
• Because each HTTP connection is terminatedafter a single GET or POST request, we say thatHTTP is a stateless protocol.
• Additionally, our programs normally handle asingle GET or POST request and thenterminate.
• Possobility that a user might manually disablecookies support and in turn, disable a Websites mechanism for state and sessionmanagement.
• it stored as plain-text in a specific directory,
everyone can view and modify them. Personalinformation is exposed.
A PHP session variable is used to store informationabout, or change settings for a user session. Sessionvariables hold information about one single user,
and are available to all pages in one application.
When you are working with an application, you open it, do somechanges and then you close it. This is much like a Session. Thecomputer knows who you are. It knows when you start theapplication and when you end. But on the internet there is oneproblem: the web server does not know who you are and what youdo because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store userinformation on the server for later use (i.e. username, shoppingitems, etc). However, session information is temporary and will bedeleted after theuser hasleft the website. If you need a permanentstorage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor andstore variables based on this UID. The UID is ei ther stored in acookie or is propagated in theURL.
• Before you can store user information in yourPHP session, you must first start up the session.
• Note: The session_start() function must appearBEFORE the <html> tag:
In the example below, we create a simple page-views counter. The isset() functionchecks if the "views" variable has already been set. If "views" has been set, we canincrement our counter. If "views" doesn't exist, we create a "views" variable, and set itto 1: