Introduction to SQL
Structure Query Language(SQL) is a programming language used for storing and managing data in RDBMS. SQL was the first commercial language introduced for E.F Codd's Relational model. Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) uses SQL as the standard database language. SQL is used to perform all type of data operations in RDBMS.SQL Command
SQL defines following data languages to manipulate data of RDBMS.
DDL : Data Definition Language
All DDL commands are auto-committed. That means it saves all the changes permanently in the database.
Command Description
create to create new table
or database
alter for alteration
truncate delete data from
table
drop to drop a table
rename to rename a table
DML : Data Manipulation Language
DML commands are not auto-committed. It means changes are not permanent to database, they can be rolled back.
Command Description
insert to insert a new row
update to update existing
row
delete to delete a row
merge merging two rows or
two tables
TCL : Transaction Control Language
These commands are to keep a check on other commands and their affect on the database. These commands can annul changes made by other commands by rolling back to original state. It can also make changes permanent.
Command Description
commit to permanently save
rollback to undo change
savepoint to save temporarily
DCL : Data Control Language
Data control language provides command to grant and take back authority.
Command Description
grant grant permission of
right
revoke take back permission.
DQL : Data Query Language
Command Description
select retrieve records from
one or more table
1)Create command
create is a DDL command used to create a table or a database.
Creating a Database
To create a database in RDBMS, create command is uses. Following is the Syntax :
create database database-name;
Example for Creating Database
create database Test;
The above command will create a database named Test.
Creating a Table
create command is also used to create a table. We can specify names and datatypes of various columns along.Following is the Syntax,
create table table-name
{
column-name1 datatype1,
column-name2 datatype2,
column-name3 datatype3,
column-name4 datatype4
};
create table command will tell the database system to create a new table with given table name and column information.
Example for creating Table
create table Student(id int, name varchar, age int);
The above command will create a new table Student in database system with 3 columns, namely id, name and age.
2) alter command
alter command is used for alteration of table structures. There are various uses of alter command, such as,
to add a column to existing table
to rename any existing column
to change datatype of any column or to modify its size.
alter is also used to drop a column.
To Add Column to existing Table
Using alter command we can add a column to an existing table. Following is the Syntax,
alter table table-name add(column-name datatype);
Here is an Example for this,
alter table Student add(address char);
The above command will add a new column address to the Student table
To Add Multiple Column to existing Table
Using alter command we can even add multiple columns to an existing table. Following is the Syntax,
alter table table-name add(column-name1 datatype1, column-name2 datatype2, column-name3 datatype3);
Here is an Example for this,
alter table Student add(father-name varchar(60), mother-name varchar(60), dob date);
The above command will add three new columns to the Student table
To Add column with Default Value
alter command can add a new column to an existing table with default values. Following is the Syntax,
alter table table-name add(column-name1 datatype1 default data);
Here is an Example for this,
alter table Student add(dob date default '1-Jan-99');
The above command will add a new column with default value to the Student table
To Modify an existing Column
alter command is used to modify data type of an existing column . Following is the Syntax,
alter table table-name modify(column-name datatype);
Here is an Example for this,
alter table Student modify(address varchar(30));
The above command will modify address column of the Student table
To Rename a column
Using alter command you can rename an existing column. Following is the Syntax,
alter table table-name rename old-column-name to column-name;
Here is an Example for this,
alter table Student rename address to Location;
The above command will rename address column to Location.
To Drop a Column
alter command is also used to drop columns also. Following is the Syntax,
alter table table-name drop(column-name);
Here is an Example for this,
alter table Student drop(address);
The above command will drop address column from the Student table
Web Development Languages
Instead
of being bound to specific programming languages and the look and feel
of a particular operating system, you can put your killer application in
the browser and run it in the cloud, as a webapp. Welcome to the
wonderful world of web development.
HTML and CSS: The
first thing you need to know to build any web site is HTML (the page
markup that makes up web pages) and CSS (the style information that
makes that markup look pretty). HTML and CSS are not true programming
languages—they're just page structure and style information. However,
you should be able to author simple HTML and CSS by hand before you
begin building web applications, because a web page is the frontend to
every webapp. This HTML tutorial is a good place to start.
JavaScript: Now
that you can lay out a static web page with HTML and CSS, things get
fun—because it's time to learn JavaScript. JavaScript is the programming
language of the web browser, the magic that makes dynamic in-page
effects go. JavaScript is also the stuff of bookmarklets,Greasemonkey user scripts, and Ajax, so it's the key to making all sorts of web goodies. Start learning JavaScript here.
Server-side scripting: Once
you're good at making things happen inside a web page, you're going to
need to put some dynamic server action behind it—and for that, you'll
need to move into a server-side scripting language, like PHP, Python,
Perl, or Ruby. For example, to make a web-based contact form that sends
an email somewhere based on what a user entered, a server-side script is
required. Scripting languages like PHP can talk to a database on your
web server as well, so if you want to make a site where users can log in
and store information, that's the way to go. Excellent web development
site Webmonkey is full of tutorials for various web programming languages. See their PHP Tutorial for Beginners. When you're ready, check out how to use PHP to talk to a database in WebMonkey's PHP and MySQL tutorial. PHP's online documentation and function reference is the best on the web. Each entry (like this one on the strlen function)
includes user comments at the bottom which are often as helpful as the
documentation itself. (I happen to be partial to PHP, but there are
plenty of other server-side scripting languages you might decide to go
with instead.)
Web frameworks: Over
the years, web developers have had to solve and resolve the same
problems and rewrite similar code to build dynamic web sites. To avoid
making everyone reinvent the wheel for every new web development
project, some programmers have come up with development frameworks that
do some repetitive work for you. The popular Ruby on Railsframework,
for example, takes the Ruby programming language and offers a
web-specific structure for getting common web application tasks done. In
fact, Adam used Rails to build his first serious (and impressive!) web
application, MixTape.me. Here's his take on how to build a web site from scratch with no experience. Other popular web development frameworks include CakePHP (for PHP programmers), Django (for Python programmers), and jQuery (for JavaScript).
Introduction
PHP5 is the latest incarnation of PHP (PHP: Hypertext Preprocessor)—a programming language devised by Rasmus Lerdorf in 1994 for building dynamic, interactive Web sites. Since then, it's been evolving into a full-fledged language in its own right, thanks to the hard work of all the people who contribute to its development.
A sure sign that PHP is maturing as a technology is evidenced by its totally revamped and upgraded support for object-oriented programming (OOP) principles and improved support for XML. The Zend engine (the part that interprets and executes PHP code) now enables PHP5 developers to implement, among a host of other things, graceful application-wide error handling.
With all the new features and functionality that PHP5 provides, it's important for programmers to "upgrade" their understanding in order to best make use of this powerful Web scripting tool. And that's why it's important for you, the reader, to invest your time learning about the latest and greatest that the people developing PHP5 have to offer.
That's all well and good, but what exactly is PHP?
You know it's a language for writing computer programs, so the real question is "What sort of programs can you write with it?" In technical terms, PHP's main use is as a cross-platform, HTML-embedded, server-side Web scripting language. Let's take a moment to examine these terms:
1. Cross-platform: Most PHP code can be processed without alteration on computers running many different operating systems. For example, a PHP script that runs on Linux generally also runs well on Windows.
2. HTML-embedded: PHP code can be written in files containing a mixture of PHP instructions and HTML code.
3. Server-side: The PHP programs are run on a server—specifically a Web server.
4. Web-scripting language: PHP programs run via a Web browser.
This means you'll write programs that mix PHP code and HTML, run them on a Web server, and access them from a Web browser that displays the result of your PHP processing by showing you the HTML returned by the Web server. In other words, you can make your programs available for other people to access across the Web, simply by placing them on a public Web server.
You're probably already familiar with HTML (HyperText Markup Language)—it's the main language used to create Web pages, combining plain text with special tags that tell browsers how to treat that text. HTML is used to describe how different elements in a Web page should be displayed, how pages should be linked, where to put images, and so on.
Pure HTML documents, for all their versatility, are little more than static arrangements of text and pictures, albeit nicely presented ones. However, most of the sites you find on the Web aren't static but dynamic, even interactive. They can show you a list of articles containing a particular word in which you're interested, show you the latest news, even greet you by name when you log on. They enable you to interact, and present you with different information according to the choices you make.
You can't build a Web site like that using raw HTML, and that's where PHP comes in. What sort of things can you do with it? Well, you can program sites that
1. Present data from a wide variety of sources, such as databases, files, or even other Web pages.
2. Incorporate interactive elements, such as search facilities, message boards, and straw polls.
3. Enable the user to perform actions, such as sending e-mail or buying something.
In other words, PHP can be used to write the sort of sites that those who regularly use the Web are likely to encounter every day. From search engines to information portals to e-commerce sites, most major Web sites incorporate some or all of these sorts of programming. Among other things in the course of this book, you'll use PHP to build
1. A simple, online text editor
:
2. A Web-based e-mail application
3. An object-oriented contact manager application
4. An object-oriented logging agent
So, PHP5 can be used for a diverse range of applications, from simple utilities such as a text editor to powerful Web applications such as the logging agent case study. This book equips you with the knowledge necessary to build any kind of Web site you want using PHP5. You'll learn some useful techniques along the way and perhaps pick up some ideas that you can incorporate into your own Web sites and applications.
Web scripting is certainly the mainstay of PHP's success, but it's not the only way to use the language. Command line scripting—using CLI (Command Line Interface), which was introduced in PHP4—is one of many popular applications of PHP. (CLI is covered in an appendix at the end of this book). Client-side graphical user interface application development using GTK (Gnome ToolKit) is another.
Why PHP?
One of the best things about PHP is the large number of Internet service providers (ISPs) and Web hosting companies that support it. Today there are hundreds of thousands of developers using PHP, and it's not surprising that there are so many, considering that several million sites are reported to have PHP installed.
You already know that PHP is a cross-platform technology and that once you've written your Web page, it's easy to get it up and running on our Web server, but how does PHP compare with other technologies out there? Well, comparing PHP with Perl is a bit tricky because they were designed for different things. PHP was specifically designed to rapidly create dynamic Web content; Perl was not. As a result, Perl can sometimes be a complicated language that can become prohibitive for users who want to create Web pages. Comparing PHP with ASP is a more balanced comparison, but then you have to pay for ASP, and ASP doesn't work well on a variety of platforms—it needs to be used on other proprietary platforms for which you also must pay.
You may ask, "Is there a downside to PHP?" In the past, PHP has been criticized for the way it handled a number of things—for example, one of its main stumbling blocks was the way in which it implemented object support. However, PHP5 has taken stock of the downfalls of its predecessors and, where necessary, has completely rewritten the way in which it implements its functionality. Now more than ever, PHP is a serious contender for large-scale enterprise developments as well as having a large, consolidated base of small- to medium-sized applications.
Chapter 1: Getting up and Running
Overview
PHP, which stands for HyperText Preprocessor, is widely used for creating programmed features for Web sites because it is easy to learn and also because PHP syntax is drawn from other widely used languages, making it familiar to many programmers. In this chapter we present a very brief history of PHP, and then discuss the nature of PHP as it relates to the Web.
Before you can get into the nitty-gritty of programming with PHP5, you need a clear understanding of how PHP programs work across the Web, and that obviously implies knowledge of the Web protocol called HyperText Transfer Protocol (HTTP). HTTP is the language or format for communications from browser to Web server and back, and is therefore fundamental to many aspects of PHP. HTTP gets some coverage in this chapter, and quite a bit more in Chapter 3.
You'll see how to properly setup PHP on a Linux server, and on a Windows server as well. PHP programs run in conjunction with Web pages, which in turn run (or are distributed by) Web server software (such as Apache or IIS), which in turn run on top of an operating system (such as Linux or Windows). Although it's not strictly necessary to know everything about network operating systems to build good PHP programs, there are many aspects of PHP that are controlled or affected by the Web server. If you're unfamiliar with server computers, Web servers, and the like, don't worry. You'll soon see how they work, and look at the requirements and process of installing basic Web server software.
This chapter leads you through installing PHP on a Red Hat Linux machine running Apache, and through installing PHP on a Windows 2000 machine running IIS. Just pick the one that's right for you.
You'll also examine the contents of the PHP configuration file php.ini with you, and test your PHP installation.
Obviously there's a lot of work for you in this chapter, so let's get started.
The Roots of PHP
PHP is a programming language designed to work with HTML, but unlike HTML, PHP has data processing capabilities. If you are familiar with HTML, you know that it is not really a programming language, but more of a rendering language—that is, HTML enables you to write Web pages using code that creates a pleasing (hopefully) display of text, graphics, and links within a browser. Although there are a few helpful features of HTML (such as the capability to cause a form submission), for the most part HTML does nothing programmatically. For example, there are no HTML commands that enable you to add two numbers together, or access a database.
If you remember the Web back in the early '90s, you may recall that early Web pages were made from HTML code written as plain text source files. When you made a connection to a Web site with your browser, the Web server software sent these plain text HTML files to be processed and rendered into Web pages. Your browser actually did the rendering process (and still does, to be sure), but if you clicked View⇨Page Source, you'd see the raw HTML code.
Javascript (and a few other almost unknown programming languages) improved the situation for Web designers in that it provided for programmatic functionality within Web pages. However, it was limited to programmatic functionality on the user's computer, not on the back-end (on the Web server), where all the really cool data processing and database access takes place. Practical Extraction and Reporting Language (PERL) was one of the first widely used languages for programming on the back-end, but has limitations of its own, such as an inability to be mixed in with HTML for easy in-page programming.
So where does PHP fit in with HTML? PHP began as PHP/FI, developed in 1995 by Rasmus Lerdorf from some Perl scripts he had created for tracking accesses to his online resume. Eventually, Rasmus wrote an implementation in C, released the source code to the public, and by the beginning of 1998 version 3.0 of PHP was released (written by Rasmus Lerdorf, Andi Gutmans, and Zeev Suraski), the first version that is very similar to the current releases of PHP.
The main goal of PHP is to enable users to easily develop dynamic Web pages. The difference between dynamic Web pages and static Web pages is that the content and structure of dynamic Web pages may change each time they are accessed (that's what the back-end programming is for) whereas the content and structure of static Web pages is fixed and does not change unless the designer manually changes them.
Unlike many other languages, PHP can be embedded directly into HTML, making it quite easy for those familiar with HTML to grasp how to add back-end, programmatic functionality to their Web pages. This single capability is one of the most important factors in PHP's usefulness, and thereby its popularity. But have no doubt that PHP is growing into a much more full-features language going well beyond the initial intentions of its authors. PHP intends to be the primary language for a great variety of online and offline applications, and PHP5 is showing every sign of doing just that.
And you shouldn't forget how well PHP works with HTTP (HyperText Transfer Protocol), the communications protocol (pre-agreed format for data communications) for Web. Whenever you click a link or enter a Web address into your browser, a request in HTTP format is sent to the Web server, which responds by sending back the Web page. If the Web page isn't found, you'll probably get the "404 Not Found" error. Sending back the correct page or sending an error if the page is not found are HTTP functions. We discuss HTTP thoroughly in Chapter 2 because several important aspects of PHP applications depend on HTTP.
Installing, Configuring, and Running PHP
Before you can write a PHP application that works with your Web pages, you need to have PHP installed and configured.
System Requirements
To run the code in this book you will need at least the following software:
Server software (an operating system such as Windows 2000 or Linux)
1. A PHP-compatible Web server (such as Apache or Internet Information Server (IIS)
2. PHP5 (get the download from www.php.net)
3. A relational database system (starting at Chapter 9, we use SQLite or MySQL)
4. A Web browser (such as IE, Mozilla, and so on)
5. A text editor, such as Notepad, Emacs, vi, BBEdit, and so on.
You shouldn't have to worry about hard drive space or RAM, unless you are working on a very old system, or one that is overloaded. PHP doesn't take up much room, and runs very efficiently.
You can run all of the software listed here on the same computer, for development purposes. If you have access to several networked computers, you may want to install all of your server software on one (typically either a UNIX or Windows NT/2000 computer), and use another networked computer as your client machine. For the purposes of this book, we will generally assume you are running all of the software on a single computer. This is the configuration used by most Web developers.
You can run all of the software listed here on the same computer, for development purposes. If you have access to several networked computers, you may want to install all of your server software on one (typically either a UNIX or Windows NT/2000 computer), and use another networked computer as your client machine. For the purposes of this book, we will generally assume you are running all of the software on a single computer. This is the configuration used by most Web developers.
php.ini, the PHP Configuration File
There are two examples of PHP configuration files that come with PHP when you download it: php.ini-dist and php.ini-recommended. After you download and install PHP, there will be one file named php.ini strategically placed on your system, and each time PHP starts it will read this file and set itself up accordingly. The php.ini file can be written out by hand, but of course most of us just modify either the dist or recommended file to suit our needs, and then copy and rename it into the appropriate folder.
However, you should note the following lines in the top of the dist file:
; This is the default settings file for new PHP installations.
; By default, PHP installs itself with a configuration suitable for
; development purposes, and *NOT* for production purposes.
The settings in the dist file are used for nearly all of the examples in this book and we'll let you know whenever the configuration settings are changed. But you will want to use the recommended file when you complete your applications and copy them over to your production server, and you should be aware that you may need to rewrite your code a little bit to work properly with the recommended file's configuration settings. We'll discuss this more as we go along.
Setting up a Test Machine
In this chapter, we'll walk through setting up PHP5 on a Red Hat Linux machine running the Apache Web server, as well as on a Windows 2000 machine running Internet Information Server (IIS). You can run PHP5 with many other operating systems and Web servers, so see the PHP5 documentation for installation and configuration on other servers. And there are a variety of installation methods you can use. For example, there is an automatic installer for the Windows version, whereas you can install the Linux version using RPMs (for some versions of Linux), and you can also download and compile the Linux versions from the original source code if you like. None of the installations are all that difficult if you follow procedures correctly, and the examples we provide are a good starting point for many of the installations available.
There are some third-party installers (often open-source and free) out there, if you want to look for them. For instance, you might try PHPTriad or Foxserv in Google.
Network Connections
If you don't already know, a computer doesn't need to be attached to the Internet, or even to a network, to run Web server software. If you install a Web server on a computer, it's always possible to access that Web server from a Web browser running on the same machine, even if it doesn't have a network card or modem. Of course, to download and install the software you need, you have to have access to an Internet connection. But you don't need it to be active just because you're running your Web server.
Once you have a Web server installed and running, you'll install PHP5 alongside it. There's some configuration required to tell the Web server how to run PHP programs, and we'll walk through that process before we start PHP. There is an automatic installer to be found with most distributions of PHP; we'll use a primarily manual process to illustrate what's happening during installation.
Important
What if it goes wrong? The README and INSTALL files that are included in most PHP downloads, as well as the PHP manual at www.php.net/manual/, provide detailed information which may be more up-to-date than the information here, which covers the PHP5.0.2 release.
Where do You Start?
There are two main installation paths from which to choose, and each simply depends on which operating system you're using:
Installing PHP5 with the Apache Web Server on Linux (we use Red Hat Fedora Linux)
Installing PHP5 with Microsoft Internet Information Server on Windows (we use Windows 2000)
PHP5 can be installed on a great variety of Web server/operating system combinations, including under Apache on Windows. The two systems we're using are the easiest to get working. If neither of them suits you, of course you can install whatever other configuration you want—you should still be able to run all of the examples in the book. Refer to the PHP5 manual for more general installation instructions.
Running PHP5
One of the basic choices to make when installing PHP5 with your Web server is whether to run it as a CGI binary or as a separate static or dynamic module. CGI (Common Gateway Interface) is a very useful way to run interpreters such as PHP5. Because of security risks (see the "Running as a CGI" section later in this chapter for more information), compiling PHP5 as a static or dynamic module is recommended under most circumstances. Our installations (on Linux and on Windows) load PHP as a separate SAPI (Server Application Programming Interface) module. On Windows, the ISAPI filter was used to run PHP as a SAPI module.
Although it is most common to run PHP in conjunction with a Web server, so that Web pages with a file extension such as .php are processed through the PHP interpreter before the finished page is sent back to the browser, there is also a command line utility that enables you to run PHP code from the command line. It is present from any of the installation types we demonstrate. You can find plenty of documentation about it on the PHP site (www.php.net).
Creating and running PHP Web applications in a satisfactory way implies that you are running (or have access to) a Web server upon which PHP is (or can be) installed, and that the installation has been tested and runs properly. It also implies that PHP has been (or can be) configured to support the needs of your PHP programs. There are a couple scenarios under which these requirements can be achieved:
1. You are running a desktop or server machine, operating system, and Web server compatible with PHP, and PHP has been installed and configured.
2. You are running a desktop or server machine connected to the Internet, with access to a Web hosting account supported by a Web server with which PHP has been installed and configured.
The vast majority of desktop machines run Windows 98, NT, 2000, 2003, and XP. In many cases you can get a free copy of Personal Web Server (PWS) and install it on a machine running one of these operating systems. PHP is compatible with PWS, so you can install and configure PHP on desktop machines running basic operating systems such as Windows 98. Server operating systems such as Windows NT, 2000, and 200, come with Internet Information Server (IIS). PHP is compatible with IIS, and you can install and configure PHP on these machines. Our Windows 2000 installation of PHP5 uses IIS as a Web server.
The majority of Web-hosting computers run some version of Linux, such as Debian, RedHat, FreeBSD, and so on. The Web server of choice for these machines is Apache. PHP is compatible with Linux and Apache, and you can install and configure PHP on these systems, but if you are not in charge of the Web-hosting computer (and many times you won't be) you'll probably have little control over the installation and configuration. If you find yourself in this position (for example, if you've been hired to work on an existing Web site running on someone else's server), you can simply verify the operating system, Web server software, and PHP version so you can cope with whatever you've have to work with as you develop your PHP programs.
Installing PHP5 with Linux and Apache
At the time of this writing, the very first release candidate of PHP5 was available, and that's the one we're using. But you may want to check the PHP site for more recent versions, and any notes about changes.
The combination of Linux, Apache, MySQL, and PHP is probably the most common production environment for running PHP Web servers. This combination of open-source software has been referred to by the acronym LAMP. If you run the same combination of software, you can benefit from the experiences of the many other people who've used this setup.
The PHP developers work very closely with the Apache and MySQL teams to ensure that advances in the three server systems are fully supported by the other components. However, at the time of this writing PHP5 is being distributed with SQLite rather than MySQL, because there is some concern about whether MySQL is still open source. This may not be a concern when you read this and begin developing, but it's worth noting.
Choosing Your Installation Method
As with other open-source software, you have the option of downloading the PHP and Apache source code (which, in both cases, is written in the C programming language) and compiling the programs yourself. If that sounds daunting (it's not actually as scary as it sounds), you can obtain precompiled versions in one of two forms: binary downloads, which are precompiled versions of the software that typically come with installation scripts to put all the required pieces into the necessary parts of your file system, and binary packages, which are available for systems that have a software package management system, such as the Red Hat Package Manager (RPM) for Linux, and are the easiest to install.
An RPM Installation of PHP4
The version of Red Hat we're using is actually called Fedora, because Red Hat has split off development into two parts: Fedora and the enterprise version of Red Hat Linux. Currently, the Fedora site doesn't have an RPM for PHP5, so we'll provide the instructions for getting and installing the RPM for PHP4 here, and then show how to download and compile PHP5 for Fedora later. By the time you read this, in all likelihood there will be an RPM available for PHP5 for your Linux distribution, so the RPM installation presented here should provide good guidance for installing PHP5 via the RPM method.
A number of popular Linux distributions use the Red Hat Package Manager, including Red Hat, SuSE, Mandrake, Definite, TurboLinux, Caldera, and Yellow Dog. If your system uses an alternative package management system, such as Debian's deb packages, refer to your distribution's manual for installation instructions.
Obtaining RPMs
The best place to get RPMs is almost always the disks from which you installed your Linux system. Red Hat 7 and SuSE 7 both include PHP4 (although it isn't installed by default)—by the time you read this, the same should be true of most current Linux distribution versions.
If your distribution doesn't include PHP4, or it doesn't include all the required functionality or support RPMs, then the next place to check is your Linux distribution vendor's Web site, which should have a download area or FTP site from which you can obtain the latest RPMs.
Finally, www.rpmfind.net provides a comprehensive search service for RPMs. When you download RPMs, though, make certain that they are compatible with your Linux distribution and your computer hardware. Different distributions put important files in different places, and this can lead to RPMs from different vendors not working on other systems. Most RPMs are available compiled to run on the different hardware systems that Linux supports.
Which RPM Packages do You Need?
1. zlib
2. libpng
3. libjpeg
4. gd
5. gd-devel
6. apache
7. mod_php4
You can find out which of them are already installed on your system by typing the following at a command prompt, substituting in the name of each of these packages in turn:
> rpm -q zlib
zlib-1.1.3-6-i386
> rpm -q libng
Package libpng is not installed
Note which of the packages you already have, and which versions they are (the version number is more important than the release number).
Apache is at version 1.3.29 if you want to remain at the old versions of GD, or 2.0.48 if you want to be current with the latest version of GD. Of course, if you are installing PHP5, GD is now bundled with PHP and is up to version 2.0.17
Then locate suitably up-to-date versions of all the packages that you don't have already, or have old versions for. As suggested, try your install CDs, your distributor's Web site, and www.rpmfind.net.
Once you have current versions of all the packages you need, you can install them. The command for upgrading an existing installation or installing a package for the first time is exactly the same. Navigate your command prompt to the location of the files on the CD or the directory into which you downloaded the RPMs. As root, type:
> rpm -Uh libpng-1.0.5-3-i386.rpm
##################
For each package you need to upgrade or install, just substitute the name of the package file you downloaded. The line of # signs extends across the screen as each installation progresses.
If you install the packages in the order listed previously, you should find that all the prerequisite files are installed in the necessary order.
To know more about PHP5 read next Post.I hope you will like it.
If you remember back before 1994 (a million years ago in Web time), early Web pages consisted of text, images, and links. The backgrounds were gray; there were no tables (much less DHTML and style sheets) to help structure pages; and there was little user interaction. The introduction of HTML elements for forms and form fields opened the door to direct, form-based interaction between the user and the Web server. HTML forms are today one of the most used (and most useful) means for interacting with online applications.
You'll explore HTML forms, but you'll also learn what kinds of data are available in HTTP requests and responses, and how you can use PHP to capture that data and then use it in your programs.
You'll examine the specifics of talking to the Web server (using the GET and POST methods), the format of requests and responses sent between client and server (and all the great data you can extract from them), and the nature of applications running across the Internet. You'll look at the concept of state, the lack of state in HTTP Web communications, and several methods for working around that deficiency. You'll get a look at PHP sessions as well.
HTML Primer
If you're an HTML wizard and have an in-depth understanding of the structure of HTML, you can probably skip this section, but for those of you who've never dissected HTML code or the HTML specification, read on. You'll recall that PHP's "middle name" is hypertext and that alone tells you that PHP is intertwined with HTML (Hypertext Markup Language). Understanding how HTML—particularly the HTML <form> element—works is very important to proficiency with PHP.
HTML was created by Tim Berners-Lee and Robert Caillau in 1989. It is a subset of Standard Generalized Markup Language (SGML). SGML was defined by International Standards in 1986 as ISO 8879:1986. SGML is designed to provide a common format for markup languages. HTML is called an SGML application because it is a language, whereas XML is simply a subset of the SGML specification used to make your own markup languages.
Like most SGML applications, HTML includes a Document Type Definition (DTD) that specifies the syntax of markup elements. You'll see examples of the HTML DTD throughout this primer.
The World Wide Web Consortium (W3C) can be found at www.w3.org. This organization maintains the HTML specification (now the XHTML specification). Visit the site and look for the HTML 4.01 specification to see all the elements and attributes.
HTML is a markup language, not a programming language. The primary purpose of HTML is to display data or content (such as text and images) along with hypertext links. HTML tags (the "commands" in HTML) help the Web page designer arrange the display of text, graphics, and multimedia. The only elements that give something resembling programmatic functionality are used to make tables, links, forms, and frames.
HTML is written in plain text, and when a page is requested all the code is sent in plain text format. Here's a simple HTML Web page (without a body):
<html>
<head>
<title>The Title</title>
</head>
</html>
Although the convention for many years was to write HTML tags uppercase (as in <HTML>), the HTML specification actually has no preference, and you can write conforming HTML tags either way, or even a mixture of upper and lower case (as in <hTmL>). However, the latest standard for HTML is now XHTML, which adheres to the XML specification, so there is a difference between uppercase and lowercase tags. XHTML specifies lowercase for tag names, which is why nearly every HTML tag in this book is lowercase. Browsers won't care whether the tags are uppercase or lowercase, but using lowercase will make it a lot easier to change your HTML to conform to XHTML.
An HTML Web page is made up of HTML tags, and most (but not all) of these tags have both beginning (opening) and ending (closing) tags. HTML tags are delimited by the angle brackets (<>). An HTML tag is named for the element it represents. For example, the tags <html> and </html> are the opening and closing tags for the HTML element. These tags signify the beginning and ending of the entire HTML document. Within these tags are the tags for the <head> of the document and for the title of the document. Tags contained within other tags are said to be nested.
Some HTML elements have only a beginning tag, such as the IMG element. When writing an IMG element (the IMG element inserts an external image file into a Web page) all you write is <img>, without en ending </img>. However, to tell the browser where to find the external image file, you place what is called an attribute in the beginning tag. HTML attributes are like fields in a database, or properties in an object, or variables in a program. They have names (such as SRC), and are containers for values. In fact, you set the value of the SRC attribute in the <img> tag to the URL of the image file name (like this: <img SRC="http://www.example.com/images/example.gif">). When the user's browser receives the HTML of the Web page, the browser reads the HTML, finds the URL of the image file, requests that file as well, and then inserts the file into the rendered Web page at the appropriate spot .
The HTML Document Type Definition
A DTD declares what elements and attributes (and a few other things) that are allowed in an HTML document. Although an HTML document is made up of HTML tags, the HTML DTD uses a special format to specify what elements and attributes you can use. For example, because the HTML DTD specifies an IMG element, you can use the IMG element in a Web page.
But it's still up to the maker of your browser to properly recognize and display elements and attributes specified in the HTML DTD. In fact, deviations from the HTML specification are the primary reason a Web page may look (and work) fine in one browser and not in another.
Technically, HTML documents should start with a line indicating the DTD to be used, contained within the <!DOCTYPE> element. The DOCTYPE declaration indicates to the browser the proper DTD to use, but the inclusion of this line is not enforced by browsers. Many Web pages have no DOCTYPE declaration, but are still rendered correctly in browsers. Here's a DOCTYPE declaration inserted by Dreamweaver (a popular Web page design tool):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
The Form and Input Elements
One of the primary HTML elements you'll be working with is the <form> element. Take a look at how it's specified in the HTML DTD:
<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
<!ATTLIST FORM
%attrs; -- %coreattrs, %i18n, %events --
action %URI; #REQUIRED. -- server-side form handler --
method (GET|POST) GET -- HTTP method used to submit the form --
enctype %ContentType; "application/x-www-form-urlencoded"
accept %ContentTypes; #IMPLIED -- list of MIME types for file upload --
name CDATA #IMPLIED. -- name of form for scripting --
onsubmit %Script; #IMPLIED -- the form was submitted --
onreset %Script; #IMPLIED -- the form was reset --
accept-charset. %Charsets; #IMPLIED -- list of supported charsets --
>
The DTD for <form>begins with a line that names it as an element, and then specifies a list of attributes (ATTLIST). Notice the action attribute, which tells the browser where to send the contents of the form, and the method attribute, which tells the browser how to send the contents of the form.
The <input> element makes text fields, radio buttons, check boxes, and so on in a form. Here's its DTD:
The <input> element makes text fields, radio buttons, check boxes, and so on in a form. Here's its DTD:
<!ENTITY % InputType
"(TEXT | PASSWORD | CHECKBOX |
RADIO | SUBMIT | RESET |
FILE | HIDDEN | IMAGE | BUTTON)"
>
<!-- attribute name required for all but submit and reset -->
<!ELEMENT INPUT - o EMPTY -- form control -->
<!ATTLIST INPUT
%attrs; -- %coreattrs, %i18n, %events --
type %InputType; TEXT -- what kind of widget is needed --
name CDATA #IMPLIED -- submit as part of form --
value CDATA #IMPLIED -- Specify for radio buttons and
checkboxes
--
checked (checked) #IMPLIED -- for radio buttons and check boxes --
disabled (disabled) #IMPLIED -- unavailable in this context --
readonly (readonly) #IMPLIED -- for text and passwd --
size CDATA #IMPLIED -- specific to each type of field --
maxlength NUMBER #IMPLIED -- max chars for text fields --
src %URI; #IMPLIED -- for fields with images --
alt CDATA #IMPLIED -- short description --
usemap %URI; #IMPLIED -- use client-side image map --
ismap (ismap) #IMPLIED -- use server-side image map --
tabindex NUMBER #IMPLIED -- position in tabbing order --
accesskey %Character; #IMPLIED -- accessibility key character -
onfocus %Script; #IMPLIED -- the element got the focus --
onblur %Script; #IMPLIED -- the element lost the focus --
onselect %Script; #IMPLIED -- some text was selected --
onchange %Script; #IMPLIED -- the element value was changed --
accept %ContentTypes; #IMPLIED -- list of MIME types for file upload --
>
The type attribute of the element specifies the type of control that will appear on the screen in your browser (text makes a text field, radio makes a radio button, and so on).
To create a Web page with a form in it, you could write the following HTML code in plain text, upload it to a Web server (or even just open it directly in your browser), and it would display as a nicely formatted Web page:
<html>
<head>
<title>
</title>
</head>
<body bgcolor="white">
<form method="post" action="http://www.example.com">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
This code creates a simple form with two fields (username and password) and a submit button. When submitted, the form's contents are sent to www.example.com.
How can you make HTML forms and PHP work together to make Web pages that are dynamically generated (rather than simply copied to your browser by the Web server)? First, you create a Web page using plain text HTML tags, and include an HTML form within that page. Then, you write PHP code within the Web page, making sure the code is properly enclosed by the <?php and ?> delimiters.
When the Web page is requested by a browser, any PHP code in it is resolved or processed by the PHP scripting engine before the results are returned to the user, and the results of PHP processing are placed in exactly the same spot as the original PHP code. You also could write your code so that it is only processed when there is a form submission (you'll see how in the next few sections). It may even use some of the submitted form data in its processing.
The end result of the PHP processing is HTML compatible, but because the PHP scripting engine has a chance to perform some processing before the final version of the Web page is sent, some of the content of the page (any parts generated by the PHP code) may differ each time the page is requested. And if processing takes place in response to a form submission, there are a great variety of interactive features that can be created.
Accessing PHP and HTTP Data
You know how HTTP works and you basically understand clients and servers, so you're very cognizant of the interaction between your browser (a client application) and the Web server (a server application) when running PHP programs online. In this Post you explore HTML forms and examine how they facilitate user interactions with the Web server (and thereby your PHP programs). These topics deserve a lot of attention because HTTP, HTML, and PHP are tightly intertwined. A good understanding of what's going on between the browser and the server is essential for PHP programming because within the requests and responses flying back and forth from client to server is a wealth of data you can utilize.
Each time you click a link or submit a form, you send a great deal of data about your system and your browser to the Web server, and each time the Web server responds, it sends you a great deal of data about itself. PHP has the capability to capture the data that is submitted by a browser, and also provides a means of getting at data about PHP's installation on the server. For instance, if you go to your favorite PHP-driven Web site and log in, it's likely that a predefined variable named $_POST is filled (on the server) with your username and password, another predefined variable named $_SERVER contains information about the current Web server environment, and that both are available to the PHP application running the site. These aspects of PHP are discussed in depth in the next few sections, but it's really kind of surprising how much data is available (especially considering that most folks aren't even aware of it). Read on to learn how to access all this data.
Predefined Variables
PHP automatically makes quite a few variables (called predefined variables) available anywhere in your program. They are array variables, and you can access them by name, like any other variable. By default, PHP is configured not to populate these variables (in the php.ini file, the default register_globals=Off is in place), you must use their entire name to access their data. For example, if a form has a text field named username and this field is filled out and submitted (and assuming the form's submission method is POST), you can access the field's data by code such as this:
$my_new_username = $_POST[username];
Predefined variables are also called superglobal variables because they can be accessed without regard to scope. Predefined variables consist of most of the information contained in HTTP requests and responses, including server variables, query strings, form variables, and so on. You can use predefined variables for any purpose, just like ordinary variables, but some of them may or may not be present for any given installation of PHP because Web servers vary in the data provided via HTTP. In the next section you'll see how to retrieve the data in predefined variables.
In addition to predefined variables, you can use the built-in PHP function phpinfo() to get basic PHP installation and operating information. This function not only enables you to test whether PHP is installed and working but also enables you to find out many details about how PHP is installed on the server. For example, you can find out what version of PHP is running, what OS your server is running on, and so forth.
Perhaps an easier way to demonstrate what you get from the phpinfo() function is simply to run the test01.php file created in again. This time you're running it not just to see if the installation of PHP worked but to examine the various kinds of data it provides. When run from your Web server, phpinfo() creates a very nicely formatted and detailed page (including all the required HTML tags) describing the PHP version, operating system, version of the ZEND engine, settings in your php.ini file, additional modules, and predefined variables .
Variables in HTTP Request and Response
There's a surprising amount of data passed back and forth between the client and the Web server (and vice versa). For example, not only is the IP address of the client passed to the Web server with each request (not actually very surprising, as how else would the Web server know where to send the response) but also details about what version of browser is making the request, cookies, form data, Web server version, and so on. The data is contained in predefined variables structured as associative arrays, so that you can access them by name, just like you would access any other array. The contents of each and what you might want to use them for are presented after the following "Try It Out."
There is a setting in your configuration file (php.ini) called register_globals. The default is off (since PHP4.2), and it restricts how you can access some predefined variables. From a practical standpoint, this means you should use the full name of the array ($_SERVER['DOCUMENT-ROOT'] is the example given) to access data in predefined variables. There is the function (import_request_variables()) that will import GET, POST, and Cookie variables into the global scope, so you can access them directly by name, but the full array name is recommended and therefore used in this post.
Links
If you've ever done any Web page design or programming, you're undoubtedly familiar with the structure of a link in HTML. In technical terms, an HTML link uses the anchor element (whose starting and ending tags are <a> and </a>), and one of its main attributes, href, which has a URL as its value. Text or images placed inside the beginning and ending <a> tags make a link that, when clicked, goes to the URL in the href attribute, like this:
<a href="http://www.myplace.com">Click Here</a>
So clicking a link is one form of user interaction enabling you to communicate with the server. But it's pretty limited, because all you can do is make a request for the page that's already supplied by the site designer. For example, if I click a link to the About page, the only reason it goes to the right page is because the site designer has already hard-coded the link with the URL for that page.
Query Strings
Somewhat more flexible is the query string, which is attached to the end of the URL in a link. A query string can consist of as many name/value pairs as you (the developer) want to supply. The big difference is that PHP provides a means by which the user can supply values that can be embedded in the query string. Say, for example, that the user has entered a value of John as his first name, and your PHP program can make use of that value via its variable name ($first_name, for instance).
The term name/value pair is a generic way of referring to any situation in which you have a named container for a value. Name/value pairs include fields in a table in a database, variables, HTML and XML attributes, and so on.
You could write a PHP program that generates a query string attached to a URL using code such as this (assuming you had the $first_name and $last_name variables already set):
<a href="http://www.myplace.com?first_name=<?php echo $first_name; ?>">Click
Here</a>
When this code runs, it produces the following output:
<a href="http://www.myplace.com?first_name=John">Click Here</a>
Notice how a query string is constructed: a question mark followed by the name of the first name/value pair, an equals sign, and the value in the first name/value pair. If you had both a first name and a last name, you could have included both name/value pairs in the query string by connecting them with an ampersand (&), like so:
<a href="http://www.myplace.com?first_name=<?php echo $first_name;
?>&last_name=<?php echo $last_name; ?>">Click Here</a>
Putting both name/value pairs in the query string would result in the following (if you're a dead movie star):
<a href="http://www.myplace.com?first_name=John&last_name=Wayne">Click
Here</a>
Query strings are often useful (especially in preserving values between page requests, which are discussed that a bit more later in the post, but as you can see they are still quite limited. For one thing, to place a user-supplied value in a query string, you have to already have it. You could get it from a database, but if you needed to get it from the user before using it, you'd have to provide the user with some free form method of supplying it. And that brings us to a very powerful method for user interaction, the HTML form.
The Concept of State
You're familiar with how desktop applications such as Excel, Word, Dreamweaver, and so on work. You start them up, they appear on your screen, and you do your work via documents, menu choices, dialog boxes, controls, and form fields. It can easily appear that there is no separation between the application's data processing logic and the user interface, but in fact every time you choose something from a menu, click a button, or enter something in a form field, you are actually using the user interface, and the user interface is communicating what you just did to the programming logic inside the application. The application then responds by performing its processing and providing a response to the user interface. For some actions you take there may be no visible response, whereas for others it is plain that a great deal of processing has taken place behind the scenes.
The point of this discussion is that as you provide input to the application via the user interface, you change the overall state of the application. You can think of state as the exact condition, moment to moment, of all the data and variables in the application. And the application has an obligation to take note of state changes, because it might have to respond to these changes with an action of its own (which then further changes the state of the application).
There are many things besides user interaction that can change the state of an application. For example, suppose you're playing a game and you have 15 seconds to make your move. The application will monitor the system clock and may make an action entirely independent of anything you do (except make your move) based on how many seconds have elapsed (another case of state change). What does this have to do with you? Well....
As a programmer, you may not think much about state when programming desktop applications, because you're used to seamless communications between your user interface and your programming logic. But programming for the Web forces you to address the issue, because HTTP communications are stateless. HTTP is a stateless protocol because there is no built-in mechanism that tracks the state of every object in the user interface and informs the programming logic of it, or vice versa.
Instead, communications between browser and server take the form of clicks on links or form submissions. Not only is this driven by the user (instead of being automatic), but for folks with slower connections or intermittent connections it can be slow and time-consuming. So building an online application with PHP requires you to use other mechanisms for maintaining state, and you need to take measures to cope with the fact that the user interface is disconnected and may not respond at all in the way you would ordinarily expect.
State Maintenance
The most direct way in which you'll be involved with state in PHP programs is when trying to preserve variable values between page requests because each page is its own program, and once the program is done processing, all variables and values are lost—the program's done, and everything is erased out of memory. Unlike desktop applications, which maintain data in memory until you shut them down, a PHP program runs only when a page request activates it, and then only until processing is completed and/or HTML or text content is returned to the user.
PHP is able to bridge the gap between each request-response and the next, providing persistence of data—and, yes, prolonged interactivity. This process of continually updating the server with information, a major ingredient in most interactive sites, is necessary to maintain a session. Session maintenance is how you refer to a series of interactions, beginning with the user accessing or logging on to a site, and ending with the user logging out or being timed out for inactivity.
The key to this process is usually a cookie (a small piece of data stored on the client's computer) or some sort of a variable that the client and server pass back and forth, often called a session key. These cookies and keys are used to help the server know which client it is interacting with for any given request. Just as a username identifies a user to a system, a session key (or an appropriate cookie) identifies a client to a Web site.
Sessions also maintain state across page requests and you'll examine them in detail a little later. First, take a look at some other methods available to you, including the use of hidden form fields, query strings, databases, and cookies.
Hidden Form Fields
You've seen how hidden form fields work to send data (coded by the designer) back to the server when the form is submitted. If you want to maintain state using hidden form fields (for example, a unique value representing a product the user is working with, such as the product ID), you can simply place the current product ID value into a hidden form field. Of course, the idea is that you would have the user select the product from a drop-down box (the select element) and then submit the form, using something like this code:
<form action="myform.php" method="post"> Query strings can be used in exactly the same way as hidden form fields to maintain state values across page requests. However, as previously discussed, their name/value pairs are displayed for all to see in the address bar of the browser, along with the URL. This is a very insecure method of transmitting data, and as you've probably guessed, easy for malicious users to break, disable, or otherwise mess with.
<select name="selected_product_id">
<option value="121">Product 121</option>
<option value="122">Product 122</option>
</select>
<input type="submit" name="button" value="Select Product">
</form>
You could return a page to him using the following code:
<input type="hidden" name="chosen_product_id" value="<?php echo
$selected_product_id; ?>">
Before the page is returned, the user's input would be processed as follows (assuming he chose product 122):
<form action="myform.php" method="post">
<input type="hidden" name="chosen_product_id" value="122">
So the next time he submits this form, part of the data submitted would be chosen_product_id, which PHP would turn into $chosen_product_id, and which you could then use anytime you wanted to perform processing on the product he chose, no matter how many page requests ago he chose that product. Don't forget, though, you'll need to populate that same hidden form field value each time the user requests another page or you'll lose that value.
Query Strings
Query strings can be used in exactly the same way as hidden form fields to maintain state values across page requests. However, as previously discussed, their name/value pairs are displayed for all to see in the address bar of the browser, along with the URL. This is a very insecure method of transmitting data, and as you've probably guessed, easy for malicious users to break, disable, or otherwise mess with.
Databases
The mechanics of databases and database access haven't been discussed yet but you're certainly aware that databases are useful for storing structured information persistently (meaning that the data is retained even if the server is turned off), so you can understand why databases are useful for storing data across page requests. Basically, if you don't mind the extra overhead of making a query on the database each time a page request occurs, you can use a table in the database to store all pertinent data that must be preserved across page requests. The downside, of course, is the overhead involved in those database connections, and the extra effort building the database in the first place.
Cookies
So what are cookies? They're a quick (and some would say messy) method of storing, on the client's computer, small snippets of data that you want to persist between separate visits to a Web site. They aren't very powerful or reliable—you certainly wouldn't want to use them for permanent data storage, because the mere act of switching browsers completely obliterates all your old cookies. But they can be very handy for a wide variety of things. Some of the most common examples of cookie use include the following:
1. Storing a user's aesthetic preferences for a specific site.
2. Storing a user key (or keys) that can be used to link users with their personal data—as used in countless shopping basket features, for example.
3. Providing a semi-permanent session key, enabling a user to remain logged on to a site until he explicitly asks to leave it or the browser closes.
Cookies are best used for small, helpful but non-critical things. One of the best examples of cookie use is to store preferences describing how a user wants your site to appear. Although the capability to customize a site's color scheme is a nice perk for users, those who can't (or won't) use cookies won't be missing much.
Intended as innocuous "helpers" for Web developers, cookies have built up a bad reputation in recent years. They are often overused (for example, to store large quantities of data which is really best kept on the server end) and sometimes even abused (to gather information on consumers without their knowledge, for instance). If used sparingly and responsibly, though, cookies can be useful in a number of situations. They tend to be most useful:
1. In situations where you know for a fact that all the visitors to your site will have cookie support enabled—on corporate and educational intranets, for example.
2. To add bells and whistles to a site—features that add to a site's appeal but aren't required to make use of it.
Messing Around with Cookies
Exact details of how cookies are implemented vary from browser to browser, but certain important points apply across the board, and these are as follows:
1. A cookie is a short piece of data that can be used to store a variable's name and value, along with information on the site from which it came and an expiry time.
2. Cookies provide client-side storage, usually held in files on the client machine's hard drive.
3. Web sites can usually only modify their own cookies.
4. They can be accessed and (if the appropriate security criteria are met) altered at will by the Web server from which they were originally sent.
When a client accesses a Web site that uses cookies, the Web server tells the client (usually a Web browser) to store away a given piece of data for later use. The client is then responsible for storing that data away. Cookie-supporting browsers accomplish this by storing the data in a file named after the site the cookie belongs to, in a directory they keep reserved for this purpose. On subsequent requests to that site, the client sends back a copy of that data—the data persists on the client side until a specified period expires, causing it to be removed from the system. This specified period is set by the server when it tells the client to create the cookie, and is basically a number of seconds for which the client should keep the cookie. If the server tells the client to set an expiry period of zero seconds, the browser should keep the cookie only until the user quits the browser application.
Because cookies are kept on the client side, they're not under the control of the server once they've been created. Users can elect to delete cookies themselves, often simply by clicking a button in their browser, or by deleting the browser's cookie files. They could also edit the contents of the files if the urge took them. Just because you wrote what's in the cookie, doesn't mean you should always expect the right data to come back!
Essentially, cookies are the server telling the client "here's something to remember; remind me of it when you come back next time." Next time could be anything from when you click that link two seconds from now to when you come back next week. That's some serious persistence! It's a little like being at a conference where delegates can be identified by their name badges for as long as they care to wear them.
Web servers send clients cookies in HTTP headers, which are sent before any HTML text. Likewise, clients send back those cookies using HTTP headers. A client knows which cookies to share with a Web site, based on the server and path the client is currently accessing. So, if you're accessing www.php.net, the browser doesn't send any cookies it received from www.wrox.com.
When a cookie is set, a server name and path name can optionally be set—this limits access to the cookie to the specified server and/or path on that server. Clients use this information to determine whether they should send any given cookie. A cookie-enabled browser generally sends any and all cookies that it thinks applicable to a given site in the headers of any given access.
Set and Retrieve Cookies
PHP, as a modern Web scripting language, comes with full support, and setting cookie variables is as simple as making a call to setcookie(). As with header(), setcookie() must be called before any HTML is printed to the client's browser because cookies are set in the HTTP headers, which must be sent before any HTML.
The setcookie() function takes six parameters, of which the first three are by far the most important: These are, in order:
1. A string to be used as the name of the variable.
2. A string to be used as the value of the variable.
3. A UNIX timestamp denoting the time at which the cookie will expire.
A UNIX timestamp is simply a long integer that represents a time and date by counting seconds since midnight on 01/01/1970. You can get the current time in this form by using the function time(). If you want to set a cookie to expire an hour from now, simply specify time() + 3600 for the third parameter.
The last three parameters to setcookie() are less frequently used:
1. The path to whose files the cookie is relevant; the browser doesn't return cookies that are from inappropriate paths. For example, if you set this parameter to /my/path/number/one and accessed a page in /my/path/number/two, your browser wouldn't send the cookie. If you went back to a page in /my/path/number/one, the browser would send the cookie.
2. The domain to which the cookie applies; same rules apply as to the preceding parameter. This parameter may be useful if your Web server hosts multiple domains.
3. An integer called secure. Set it to 1 if you only want your cookie to be sent when requesting an SSL-encrypted page. (The cookie won't be stored in an encrypted form on the client's hard drive; this setting merely ensures that the cookie will be encrypted for transmission across the Internet.)
In the simplest possible situation, you could leave off these last three, so that a typical call to setcookie() might look like this:
setcookie("fontprefs", "", time()+3600);
Accessing cookies is even simpler—there's nothing to call at all! Just as it does with POST variables, PHP automatically puts cookie information in the global domain, so it's as simple to use cookie values as it is to use any other variables. For example, the value of a received cookie called fontprefs is automatically be available throughout the script as the global variable
$_COOKIES['fontprefs'].
There are several ways to delete a cookie. Of course, if the client knows where to look on his machine, he can always edit or delete the files in which cookies are stored. However, it's sometimes useful to be able to get the server to delete (or "eat") a cookie, and if this is the case, there are two main options:
1. Reset the cookie's expiry time to a time in the past: setcookie("num", "0", time() -9999);, for example.
2. Reset the cookie, specifying only its name: setcookie("fontprefs");, for example.
The last three parameters to setcookie() are less frequently used:
The path to whose files the cookie is relevant; the browser doesn't return cookies that are from inappropriate paths. For example, if you set this parameter to /my/path/number/one and accessed a page in /my/path/number/two, your browser wouldn't send the cookie. If you went back to a page in /my/path/number/one, the browser would send the cookie.
The domain to which the cookie applies; same rules apply as to the preceding parameter. This parameter may be useful if your Web server hosts multiple domains.
An integer called secure. Set it to 1 if you only want your cookie to be sent when requesting an SSL-encrypted page. (The cookie won't be stored in an encrypted form on the client's hard drive; this setting merely ensures that the cookie will be encrypted for transmission across the Internet.)
In the simplest possible situation, you could leave off these last three, so that a typical call to setcookie() might look like this:
setcookie("fontprefs", "", time()+3600);
Accessing cookies is even simpler—there's nothing to call at all! Just as it does with POST variables, PHP automatically puts cookie information in the global domain, so it's as simple to use cookie values as it is to use any other variables. For example, the value of a received cookie called fontprefs is automatically be available throughout the script as the global variable $_COOKIES['fontprefs'].
There are several ways to delete a cookie. Of course, if the client knows where to look on his machine, he can always edit or delete the files in which cookies are stored. However, it's sometimes useful to be able to get the server to delete (or "eat") a cookie, and if this is the case, there are two main options:
Reset the cookie's expiry time to a time in the past: setcookie("num", "0", time() -9999);, for example.
Reset the cookie, specifying only its name: setcookie("fontprefs");, for example.
Native Sessions in PHP
A session can be defined as a series of related interactions between a single client and the Web server, which take place over an extended period of time. This could be a series of transactions that a user makes while updating his stock portfolio, or the set of requests that are made to check an e-mail account through a browser-based e-mail service. The session may consist of multiple requests to the same script, or of requests to a variety of different resources on the same Web site.
Particularly when you want to work with sensitive (or bulky) information, it makes a lot of sense to submit it once and have it stored on the server. Rather than storing the actual data on the client machine, and have to pass it back and forth between the server and client each time, it's far more practical to keep the data on the server, but give the client a "key" to allow it to uniquely identify itself, and consequently any server-side data associated with it. This key is called a session identifier; it uniquely associates a client with a session, and therefore with its data. In PHP, the session identifier is known as the SID (Session ID). SID is a special variable that's specified as a reference number for any particular session.
You saw how to establish a session of sorts when you used cookies to make data persist on the client machine. As noted at the time, though, that isn't a terribly secure way to manage sessions. Fortunately, PHP comes with its own session management system built in, so you don't need to worry too much about the precise implementation details. PHP creates its SID whenever you use the session_start() function, and also by default if you use certain other session-related functions, such as session_register(). The value of the SID is kept in a global variable named PHPSESSID.
You can think of the SID as being like the reference number on an electric bill: you're given the number, the electric company files your details under that number, and presto! You no longer have to give the company all your details every time you call up to complain about its outrageous charges. The SID is automatically created and passed back and forth for you, each time the user clicks a link or submits form.
When you start a PHP session, the server assigns it a session ID, or SID. Any variables that you register as session variables (you'll see how to do this in a moment) are then stored on the server in a cookie-like file. The name of this file is generally the same as the value of the SID. All the client has to do to access this data is to include the SID in its request to the server. It can use a hidden form field, a query string, a cookie, anything at all, as long as the SID makes it into the HTTP request. The server looks up the appropriate session data and makes it available for use in whatever script it then executes.
If you have cookie support enabled, even this is taken care of, because the session manager automatically sends the client a cookie for the SID value. If you can't (or don't want to) use cookies, the simplest thing to do is to add the SID as a term in all query strings that point back to your Web site.
PHP sessions handle this all very neatly; they're an excellent way to learn how to build interactive sites quickly because they completely free you up from worrying about the nitty-gritty details of implementing persistence, and let you get on with the business of building your site. One particularly nice aspect is the knowledge that you have literally thousands of coders scrutinizing your persistence mechanism (because it's a part of PHP itself!) and ensuring that the underlying code works as well as possible. What's more, sessions are very well documented in the core PHP documentation, available at the official PHP Web site (www.php.net/). So, sessions are easy, reliable, and almost universally available; but how exactly do you use them?
In most cases, using PHP sessions is as simple as telling PHP, "I want variables X, Y, and Z to remain persistent," and letting PHP do the work. All that you, the coder, need to worry about is how to tell PHP to register a session variable—that is, make a given variable persistent—and then how to access those variables.
The function for registering a persistent variable for use with PHP sessions is session_register(). Given the name (without the dollar sign) of a variable, it makes that variable and its contents persist for the duration of the current session. If there isn't currently a session defined, a new one is created automatically. The length of the session (how long the session remains intact without the user having to use the site) is determined by the session timeout setting in the php.ini file. The default is 1,440 seconds (24 minutes).
If you wanted to maintain persistent variables called myvar1 and myvar2, for example, here's how you'd begin your PHP script:
<?php
session-register("myvar1");
session-register("myvar2");
?>
You must put this code at the top of the script. Behind the scenes, you're using cookies. Again, to not mess with HTTP headers, you must be sure to register all the session variables before any HTML headers are sent out. It's good practice to do so at the very top of a script, in a self-contained snippet of PHP, as shown.
Once you've registered a variable, retrieving its contents is ridiculously simple—just access the session variable as if it were any other global variable! If you used the preceding code to register variables $myvar1 and $myvar2, you can use them just like any other variables. The only difference is that they persist for as long as the session lasts, so that the next time the page is called within the session, by the same user, the variables will contain the same values they had when the page finished executing the last time.
To use PHP sessions with Windows, you may need to modify the variable session.save_path in your php.ini file so that it refers to a valid Windows directory (D:\WinNT\Temp, for example, where D is the letter for your hard drive).
Summary
This Post covered the many predefined variables available to your PHP program anytime a request and response occurs between the client and the Web server. The display and use of individual predefined variables such as $_SERVER, $_REQUEST, and so on also were discussed.
You learned the basics for making your PHP programs interactive: query strings in links (using the <a> element) and HTML forms (using the <input>, <textarea>, and <select> elements). You also learned the differences between the GET and POST methods, and examined the circumstances under which you might want to use one over the other.
Finally, you explored the concept of state, what it means that HTTP is stateless, and how to overcome HTTP's stateless limitations using hidden form fields, query strings, cookies, sessions, and even databases to store and transmit state information across page requests.
Thank you.I hope this post help you.
PHP 5
Introduction
PHP5 is the latest incarnation of PHP (PHP: Hypertext Preprocessor)—a programming language devised by Rasmus Lerdorf in 1994 for building dynamic, interactive Web sites. Since then, it's been evolving into a full-fledged language in its own right, thanks to the hard work of all the people who contribute to its development.
A sure sign that PHP is maturing as a technology is evidenced by its totally revamped and upgraded support for object-oriented programming (OOP) principles and improved support for XML. The Zend engine (the part that interprets and executes PHP code) now enables PHP5 developers to implement, among a host of other things, graceful application-wide error handling.
With all the new features and functionality that PHP5 provides, it's important for programmers to "upgrade" their understanding in order to best make use of this powerful Web scripting tool. And that's why it's important for you, the reader, to invest your time learning about the latest and greatest that the people developing PHP5 have to offer.
That's all well and good, but what exactly is PHP?
You know it's a language for writing computer programs, so the real question is "What sort of programs can you write with it?" In technical terms, PHP's main use is as a cross-platform, HTML-embedded, server-side Web scripting language. Let's take a moment to examine these terms:
1. Cross-platform: Most PHP code can be processed without alteration on computers running many different operating systems. For example, a PHP script that runs on Linux generally also runs well on Windows.
2. HTML-embedded: PHP code can be written in files containing a mixture of PHP instructions and HTML code.
3. Server-side: The PHP programs are run on a server—specifically a Web server.
4. Web-scripting language: PHP programs run via a Web browser.
This means you'll write programs that mix PHP code and HTML, run them on a Web server, and access them from a Web browser that displays the result of your PHP processing by showing you the HTML returned by the Web server. In other words, you can make your programs available for other people to access across the Web, simply by placing them on a public Web server.
You're probably already familiar with HTML (HyperText Markup Language)—it's the main language used to create Web pages, combining plain text with special tags that tell browsers how to treat that text. HTML is used to describe how different elements in a Web page should be displayed, how pages should be linked, where to put images, and so on.
Pure HTML documents, for all their versatility, are little more than static arrangements of text and pictures, albeit nicely presented ones. However, most of the sites you find on the Web aren't static but dynamic, even interactive. They can show you a list of articles containing a particular word in which you're interested, show you the latest news, even greet you by name when you log on. They enable you to interact, and present you with different information according to the choices you make.
You can't build a Web site like that using raw HTML, and that's where PHP comes in. What sort of things can you do with it? Well, you can program sites that
1. Present data from a wide variety of sources, such as databases, files, or even other Web pages.
2. Incorporate interactive elements, such as search facilities, message boards, and straw polls.
3. Enable the user to perform actions, such as sending e-mail or buying something.
In other words, PHP can be used to write the sort of sites that those who regularly use the Web are likely to encounter every day. From search engines to information portals to e-commerce sites, most major Web sites incorporate some or all of these sorts of programming. Among other things in the course of this book, you'll use PHP to build
1. A simple, online text editor
:
2. A Web-based e-mail application
3. An object-oriented contact manager application
4. An object-oriented logging agent
So, PHP5 can be used for a diverse range of applications, from simple utilities such as a text editor to powerful Web applications such as the logging agent case study. This book equips you with the knowledge necessary to build any kind of Web site you want using PHP5. You'll learn some useful techniques along the way and perhaps pick up some ideas that you can incorporate into your own Web sites and applications.
Web scripting is certainly the mainstay of PHP's success, but it's not the only way to use the language. Command line scripting—using CLI (Command Line Interface), which was introduced in PHP4—is one of many popular applications of PHP. (CLI is covered in an appendix at the end of this book). Client-side graphical user interface application development using GTK (Gnome ToolKit) is another.
Why PHP?
One of the best things about PHP is the large number of Internet service providers (ISPs) and Web hosting companies that support it. Today there are hundreds of thousands of developers using PHP, and it's not surprising that there are so many, considering that several million sites are reported to have PHP installed.
You already know that PHP is a cross-platform technology and that once you've written your Web page, it's easy to get it up and running on our Web server, but how does PHP compare with other technologies out there? Well, comparing PHP with Perl is a bit tricky because they were designed for different things. PHP was specifically designed to rapidly create dynamic Web content; Perl was not. As a result, Perl can sometimes be a complicated language that can become prohibitive for users who want to create Web pages. Comparing PHP with ASP is a more balanced comparison, but then you have to pay for ASP, and ASP doesn't work well on a variety of platforms—it needs to be used on other proprietary platforms for which you also must pay.
You may ask, "Is there a downside to PHP?" In the past, PHP has been criticized for the way it handled a number of things—for example, one of its main stumbling blocks was the way in which it implemented object support. However, PHP5 has taken stock of the downfalls of its predecessors and, where necessary, has completely rewritten the way in which it implements its functionality. Now more than ever, PHP is a serious contender for large-scale enterprise developments as well as having a large, consolidated base of small- to medium-sized applications.
Chapter 1: Getting up and Running
Overview
PHP, which stands for HyperText Preprocessor, is widely used for creating programmed features for Web sites because it is easy to learn and also because PHP syntax is drawn from other widely used languages, making it familiar to many programmers. In this chapter we present a very brief history of PHP, and then discuss the nature of PHP as it relates to the Web.
Before you can get into the nitty-gritty of programming with PHP5, you need a clear understanding of how PHP programs work across the Web, and that obviously implies knowledge of the Web protocol called HyperText Transfer Protocol (HTTP). HTTP is the language or format for communications from browser to Web server and back, and is therefore fundamental to many aspects of PHP. HTTP gets some coverage in this chapter, and quite a bit more in Chapter 3.
You'll see how to properly setup PHP on a Linux server, and on a Windows server as well. PHP programs run in conjunction with Web pages, which in turn run (or are distributed by) Web server software (such as Apache or IIS), which in turn run on top of an operating system (such as Linux or Windows). Although it's not strictly necessary to know everything about network operating systems to build good PHP programs, there are many aspects of PHP that are controlled or affected by the Web server. If you're unfamiliar with server computers, Web servers, and the like, don't worry. You'll soon see how they work, and look at the requirements and process of installing basic Web server software.
This chapter leads you through installing PHP on a Red Hat Linux machine running Apache, and through installing PHP on a Windows 2000 machine running IIS. Just pick the one that's right for you.
You'll also examine the contents of the PHP configuration file php.ini with you, and test your PHP installation.
Obviously there's a lot of work for you in this chapter, so let's get started.
The Roots of PHP
PHP is a programming language designed to work with HTML, but unlike HTML, PHP has data processing capabilities. If you are familiar with HTML, you know that it is not really a programming language, but more of a rendering language—that is, HTML enables you to write Web pages using code that creates a pleasing (hopefully) display of text, graphics, and links within a browser. Although there are a few helpful features of HTML (such as the capability to cause a form submission), for the most part HTML does nothing programmatically. For example, there are no HTML commands that enable you to add two numbers together, or access a database.
If you remember the Web back in the early '90s, you may recall that early Web pages were made from HTML code written as plain text source files. When you made a connection to a Web site with your browser, the Web server software sent these plain text HTML files to be processed and rendered into Web pages. Your browser actually did the rendering process (and still does, to be sure), but if you clicked View⇨Page Source, you'd see the raw HTML code.
Javascript (and a few other almost unknown programming languages) improved the situation for Web designers in that it provided for programmatic functionality within Web pages. However, it was limited to programmatic functionality on the user's computer, not on the back-end (on the Web server), where all the really cool data processing and database access takes place. Practical Extraction and Reporting Language (PERL) was one of the first widely used languages for programming on the back-end, but has limitations of its own, such as an inability to be mixed in with HTML for easy in-page programming.
So where does PHP fit in with HTML? PHP began as PHP/FI, developed in 1995 by Rasmus Lerdorf from some Perl scripts he had created for tracking accesses to his online resume. Eventually, Rasmus wrote an implementation in C, released the source code to the public, and by the beginning of 1998 version 3.0 of PHP was released (written by Rasmus Lerdorf, Andi Gutmans, and Zeev Suraski), the first version that is very similar to the current releases of PHP.
The main goal of PHP is to enable users to easily develop dynamic Web pages. The difference between dynamic Web pages and static Web pages is that the content and structure of dynamic Web pages may change each time they are accessed (that's what the back-end programming is for) whereas the content and structure of static Web pages is fixed and does not change unless the designer manually changes them.
Unlike many other languages, PHP can be embedded directly into HTML, making it quite easy for those familiar with HTML to grasp how to add back-end, programmatic functionality to their Web pages. This single capability is one of the most important factors in PHP's usefulness, and thereby its popularity. But have no doubt that PHP is growing into a much more full-features language going well beyond the initial intentions of its authors. PHP intends to be the primary language for a great variety of online and offline applications, and PHP5 is showing every sign of doing just that.
And you shouldn't forget how well PHP works with HTTP (HyperText Transfer Protocol), the communications protocol (pre-agreed format for data communications) for Web. Whenever you click a link or enter a Web address into your browser, a request in HTTP format is sent to the Web server, which responds by sending back the Web page. If the Web page isn't found, you'll probably get the "404 Not Found" error. Sending back the correct page or sending an error if the page is not found are HTTP functions. We discuss HTTP thoroughly in Chapter 2 because several important aspects of PHP applications depend on HTTP.
Installing, Configuring, and Running PHP
Before you can write a PHP application that works with your Web pages, you need to have PHP installed and configured.
System Requirements
To run the code in this book you will need at least the following software:
Server software (an operating system such as Windows 2000 or Linux)
1. A PHP-compatible Web server (such as Apache or Internet Information Server (IIS)
2. PHP5 (get the download from www.php.net)
3. A relational database system (starting at Chapter 9, we use SQLite or MySQL)
4. A Web browser (such as IE, Mozilla, and so on)
5. A text editor, such as Notepad, Emacs, vi, BBEdit, and so on.
You shouldn't have to worry about hard drive space or RAM, unless you are working on a very old system, or one that is overloaded. PHP doesn't take up much room, and runs very efficiently.
You can run all of the software listed here on the same computer, for development purposes. If you have access to several networked computers, you may want to install all of your server software on one (typically either a UNIX or Windows NT/2000 computer), and use another networked computer as your client machine. For the purposes of this book, we will generally assume you are running all of the software on a single computer. This is the configuration used by most Web developers.
You can run all of the software listed here on the same computer, for development purposes. If you have access to several networked computers, you may want to install all of your server software on one (typically either a UNIX or Windows NT/2000 computer), and use another networked computer as your client machine. For the purposes of this book, we will generally assume you are running all of the software on a single computer. This is the configuration used by most Web developers.
php.ini, the PHP Configuration File
There are two examples of PHP configuration files that come with PHP when you download it: php.ini-dist and php.ini-recommended. After you download and install PHP, there will be one file named php.ini strategically placed on your system, and each time PHP starts it will read this file and set itself up accordingly. The php.ini file can be written out by hand, but of course most of us just modify either the dist or recommended file to suit our needs, and then copy and rename it into the appropriate folder.
However, you should note the following lines in the top of the dist file:
; This is the default settings file for new PHP installations.
; By default, PHP installs itself with a configuration suitable for
; development purposes, and *NOT* for production purposes.
The settings in the dist file are used for nearly all of the examples in this book and we'll let you know whenever the configuration settings are changed. But you will want to use the recommended file when you complete your applications and copy them over to your production server, and you should be aware that you may need to rewrite your code a little bit to work properly with the recommended file's configuration settings. We'll discuss this more as we go along.
Setting up a Test Machine
In this chapter, we'll walk through setting up PHP5 on a Red Hat Linux machine running the Apache Web server, as well as on a Windows 2000 machine running Internet Information Server (IIS). You can run PHP5 with many other operating systems and Web servers, so see the PHP5 documentation for installation and configuration on other servers. And there are a variety of installation methods you can use. For example, there is an automatic installer for the Windows version, whereas you can install the Linux version using RPMs (for some versions of Linux), and you can also download and compile the Linux versions from the original source code if you like. None of the installations are all that difficult if you follow procedures correctly, and the examples we provide are a good starting point for many of the installations available.
There are some third-party installers (often open-source and free) out there, if you want to look for them. For instance, you might try PHPTriad or Foxserv in Google.
Network Connections
If you don't already know, a computer doesn't need to be attached to the Internet, or even to a network, to run Web server software. If you install a Web server on a computer, it's always possible to access that Web server from a Web browser running on the same machine, even if it doesn't have a network card or modem. Of course, to download and install the software you need, you have to have access to an Internet connection. But you don't need it to be active just because you're running your Web server.
Once you have a Web server installed and running, you'll install PHP5 alongside it. There's some configuration required to tell the Web server how to run PHP programs, and we'll walk through that process before we start PHP. There is an automatic installer to be found with most distributions of PHP; we'll use a primarily manual process to illustrate what's happening during installation.
Important
What if it goes wrong? The README and INSTALL files that are included in most PHP downloads, as well as the PHP manual at www.php.net/manual/, provide detailed information which may be more up-to-date than the information here, which covers the PHP5.0.2 release.
Where do You Start?
There are two main installation paths from which to choose, and each simply depends on which operating system you're using:
Installing PHP5 with the Apache Web Server on Linux (we use Red Hat Fedora Linux)
Installing PHP5 with Microsoft Internet Information Server on Windows (we use Windows 2000)
PHP5 can be installed on a great variety of Web server/operating system combinations, including under Apache on Windows. The two systems we're using are the easiest to get working. If neither of them suits you, of course you can install whatever other configuration you want—you should still be able to run all of the examples in the book. Refer to the PHP5 manual for more general installation instructions.
Running PHP5
One of the basic choices to make when installing PHP5 with your Web server is whether to run it as a CGI binary or as a separate static or dynamic module. CGI (Common Gateway Interface) is a very useful way to run interpreters such as PHP5. Because of security risks (see the "Running as a CGI" section later in this chapter for more information), compiling PHP5 as a static or dynamic module is recommended under most circumstances. Our installations (on Linux and on Windows) load PHP as a separate SAPI (Server Application Programming Interface) module. On Windows, the ISAPI filter was used to run PHP as a SAPI module.
Although it is most common to run PHP in conjunction with a Web server, so that Web pages with a file extension such as .php are processed through the PHP interpreter before the finished page is sent back to the browser, there is also a command line utility that enables you to run PHP code from the command line. It is present from any of the installation types we demonstrate. You can find plenty of documentation about it on the PHP site (www.php.net).
Creating and running PHP Web applications in a satisfactory way implies that you are running (or have access to) a Web server upon which PHP is (or can be) installed, and that the installation has been tested and runs properly. It also implies that PHP has been (or can be) configured to support the needs of your PHP programs. There are a couple scenarios under which these requirements can be achieved:
1. You are running a desktop or server machine, operating system, and Web server compatible with PHP, and PHP has been installed and configured.
2. You are running a desktop or server machine connected to the Internet, with access to a Web hosting account supported by a Web server with which PHP has been installed and configured.
The vast majority of desktop machines run Windows 98, NT, 2000, 2003, and XP. In many cases you can get a free copy of Personal Web Server (PWS) and install it on a machine running one of these operating systems. PHP is compatible with PWS, so you can install and configure PHP on desktop machines running basic operating systems such as Windows 98. Server operating systems such as Windows NT, 2000, and 200, come with Internet Information Server (IIS). PHP is compatible with IIS, and you can install and configure PHP on these machines. Our Windows 2000 installation of PHP5 uses IIS as a Web server.
The majority of Web-hosting computers run some version of Linux, such as Debian, RedHat, FreeBSD, and so on. The Web server of choice for these machines is Apache. PHP is compatible with Linux and Apache, and you can install and configure PHP on these systems, but if you are not in charge of the Web-hosting computer (and many times you won't be) you'll probably have little control over the installation and configuration. If you find yourself in this position (for example, if you've been hired to work on an existing Web site running on someone else's server), you can simply verify the operating system, Web server software, and PHP version so you can cope with whatever you've have to work with as you develop your PHP programs.
Installing PHP5 with Linux and Apache
At the time of this writing, the very first release candidate of PHP5 was available, and that's the one we're using. But you may want to check the PHP site for more recent versions, and any notes about changes.
The combination of Linux, Apache, MySQL, and PHP is probably the most common production environment for running PHP Web servers. This combination of open-source software has been referred to by the acronym LAMP. If you run the same combination of software, you can benefit from the experiences of the many other people who've used this setup.
The PHP developers work very closely with the Apache and MySQL teams to ensure that advances in the three server systems are fully supported by the other components. However, at the time of this writing PHP5 is being distributed with SQLite rather than MySQL, because there is some concern about whether MySQL is still open source. This may not be a concern when you read this and begin developing, but it's worth noting.
Choosing Your Installation Method
As with other open-source software, you have the option of downloading the PHP and Apache source code (which, in both cases, is written in the C programming language) and compiling the programs yourself. If that sounds daunting (it's not actually as scary as it sounds), you can obtain precompiled versions in one of two forms: binary downloads, which are precompiled versions of the software that typically come with installation scripts to put all the required pieces into the necessary parts of your file system, and binary packages, which are available for systems that have a software package management system, such as the Red Hat Package Manager (RPM) for Linux, and are the easiest to install.
An RPM Installation of PHP4
The version of Red Hat we're using is actually called Fedora, because Red Hat has split off development into two parts: Fedora and the enterprise version of Red Hat Linux. Currently, the Fedora site doesn't have an RPM for PHP5, so we'll provide the instructions for getting and installing the RPM for PHP4 here, and then show how to download and compile PHP5 for Fedora later. By the time you read this, in all likelihood there will be an RPM available for PHP5 for your Linux distribution, so the RPM installation presented here should provide good guidance for installing PHP5 via the RPM method.
A number of popular Linux distributions use the Red Hat Package Manager, including Red Hat, SuSE, Mandrake, Definite, TurboLinux, Caldera, and Yellow Dog. If your system uses an alternative package management system, such as Debian's deb packages, refer to your distribution's manual for installation instructions.
Obtaining RPMs
The best place to get RPMs is almost always the disks from which you installed your Linux system. Red Hat 7 and SuSE 7 both include PHP4 (although it isn't installed by default)—by the time you read this, the same should be true of most current Linux distribution versions.
If your distribution doesn't include PHP4, or it doesn't include all the required functionality or support RPMs, then the next place to check is your Linux distribution vendor's Web site, which should have a download area or FTP site from which you can obtain the latest RPMs.
Finally, www.rpmfind.net provides a comprehensive search service for RPMs. When you download RPMs, though, make certain that they are compatible with your Linux distribution and your computer hardware. Different distributions put important files in different places, and this can lead to RPMs from different vendors not working on other systems. Most RPMs are available compiled to run on the different hardware systems that Linux supports.
Which RPM Packages do You Need?
1. zlib
2. libpng
3. libjpeg
4. gd
5. gd-devel
6. apache
7. mod_php4
You can find out which of them are already installed on your system by typing the following at a command prompt, substituting in the name of each of these packages in turn:
> rpm -q zlib
zlib-1.1.3-6-i386
> rpm -q libng
Package libpng is not installed
Note which of the packages you already have, and which versions they are (the version number is more important than the release number).
Apache is at version 1.3.29 if you want to remain at the old versions of GD, or 2.0.48 if you want to be current with the latest version of GD. Of course, if you are installing PHP5, GD is now bundled with PHP and is up to version 2.0.17
Then locate suitably up-to-date versions of all the packages that you don't have already, or have old versions for. As suggested, try your install CDs, your distributor's Web site, and www.rpmfind.net.
Once you have current versions of all the packages you need, you can install them. The command for upgrading an existing installation or installing a package for the first time is exactly the same. Navigate your command prompt to the location of the files on the CD or the directory into which you downloaded the RPMs. As root, type:
> rpm -Uh libpng-1.0.5-3-i386.rpm
##################
For each package you need to upgrade or install, just substitute the name of the package file you downloaded. The line of # signs extends across the screen as each installation progresses.
If you install the packages in the order listed previously, you should find that all the prerequisite files are installed in the necessary order.
To know more about PHP5 read next Post.I hope you will like it.
PHP, HTML, and State
Here we laern About PHP,HTML,and State. now you're familiar with HTTP, simple PHP programs, variables, and some of the PHP built-in functions, and although you can do a lot with what you've already learned, there's a key ingredient missing: user interaction! That's what this Post is all about, at least as far as Web-based applications are concerned.If you remember back before 1994 (a million years ago in Web time), early Web pages consisted of text, images, and links. The backgrounds were gray; there were no tables (much less DHTML and style sheets) to help structure pages; and there was little user interaction. The introduction of HTML elements for forms and form fields opened the door to direct, form-based interaction between the user and the Web server. HTML forms are today one of the most used (and most useful) means for interacting with online applications.
You'll explore HTML forms, but you'll also learn what kinds of data are available in HTTP requests and responses, and how you can use PHP to capture that data and then use it in your programs.
You'll examine the specifics of talking to the Web server (using the GET and POST methods), the format of requests and responses sent between client and server (and all the great data you can extract from them), and the nature of applications running across the Internet. You'll look at the concept of state, the lack of state in HTTP Web communications, and several methods for working around that deficiency. You'll get a look at PHP sessions as well.
HTML Primer
If you're an HTML wizard and have an in-depth understanding of the structure of HTML, you can probably skip this section, but for those of you who've never dissected HTML code or the HTML specification, read on. You'll recall that PHP's "middle name" is hypertext and that alone tells you that PHP is intertwined with HTML (Hypertext Markup Language). Understanding how HTML—particularly the HTML <form> element—works is very important to proficiency with PHP.
HTML was created by Tim Berners-Lee and Robert Caillau in 1989. It is a subset of Standard Generalized Markup Language (SGML). SGML was defined by International Standards in 1986 as ISO 8879:1986. SGML is designed to provide a common format for markup languages. HTML is called an SGML application because it is a language, whereas XML is simply a subset of the SGML specification used to make your own markup languages.
Like most SGML applications, HTML includes a Document Type Definition (DTD) that specifies the syntax of markup elements. You'll see examples of the HTML DTD throughout this primer.
The World Wide Web Consortium (W3C) can be found at www.w3.org. This organization maintains the HTML specification (now the XHTML specification). Visit the site and look for the HTML 4.01 specification to see all the elements and attributes.
HTML is a markup language, not a programming language. The primary purpose of HTML is to display data or content (such as text and images) along with hypertext links. HTML tags (the "commands" in HTML) help the Web page designer arrange the display of text, graphics, and multimedia. The only elements that give something resembling programmatic functionality are used to make tables, links, forms, and frames.
HTML is written in plain text, and when a page is requested all the code is sent in plain text format. Here's a simple HTML Web page (without a body):
<html>
<head>
<title>The Title</title>
</head>
</html>
Although the convention for many years was to write HTML tags uppercase (as in <HTML>), the HTML specification actually has no preference, and you can write conforming HTML tags either way, or even a mixture of upper and lower case (as in <hTmL>). However, the latest standard for HTML is now XHTML, which adheres to the XML specification, so there is a difference between uppercase and lowercase tags. XHTML specifies lowercase for tag names, which is why nearly every HTML tag in this book is lowercase. Browsers won't care whether the tags are uppercase or lowercase, but using lowercase will make it a lot easier to change your HTML to conform to XHTML.
An HTML Web page is made up of HTML tags, and most (but not all) of these tags have both beginning (opening) and ending (closing) tags. HTML tags are delimited by the angle brackets (<>). An HTML tag is named for the element it represents. For example, the tags <html> and </html> are the opening and closing tags for the HTML element. These tags signify the beginning and ending of the entire HTML document. Within these tags are the tags for the <head> of the document and for the title of the document. Tags contained within other tags are said to be nested.
Some HTML elements have only a beginning tag, such as the IMG element. When writing an IMG element (the IMG element inserts an external image file into a Web page) all you write is <img>, without en ending </img>. However, to tell the browser where to find the external image file, you place what is called an attribute in the beginning tag. HTML attributes are like fields in a database, or properties in an object, or variables in a program. They have names (such as SRC), and are containers for values. In fact, you set the value of the SRC attribute in the <img> tag to the URL of the image file name (like this: <img SRC="http://www.example.com/images/example.gif">). When the user's browser receives the HTML of the Web page, the browser reads the HTML, finds the URL of the image file, requests that file as well, and then inserts the file into the rendered Web page at the appropriate spot .
The HTML Document Type Definition
A DTD declares what elements and attributes (and a few other things) that are allowed in an HTML document. Although an HTML document is made up of HTML tags, the HTML DTD uses a special format to specify what elements and attributes you can use. For example, because the HTML DTD specifies an IMG element, you can use the IMG element in a Web page.
But it's still up to the maker of your browser to properly recognize and display elements and attributes specified in the HTML DTD. In fact, deviations from the HTML specification are the primary reason a Web page may look (and work) fine in one browser and not in another.
Technically, HTML documents should start with a line indicating the DTD to be used, contained within the <!DOCTYPE> element. The DOCTYPE declaration indicates to the browser the proper DTD to use, but the inclusion of this line is not enforced by browsers. Many Web pages have no DOCTYPE declaration, but are still rendered correctly in browsers. Here's a DOCTYPE declaration inserted by Dreamweaver (a popular Web page design tool):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
The Form and Input Elements
One of the primary HTML elements you'll be working with is the <form> element. Take a look at how it's specified in the HTML DTD:
<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
<!ATTLIST FORM
%attrs; -- %coreattrs, %i18n, %events --
action %URI; #REQUIRED. -- server-side form handler --
method (GET|POST) GET -- HTTP method used to submit the form --
enctype %ContentType; "application/x-www-form-urlencoded"
accept %ContentTypes; #IMPLIED -- list of MIME types for file upload --
name CDATA #IMPLIED. -- name of form for scripting --
onsubmit %Script; #IMPLIED -- the form was submitted --
onreset %Script; #IMPLIED -- the form was reset --
accept-charset. %Charsets; #IMPLIED -- list of supported charsets --
>
The DTD for <form>begins with a line that names it as an element, and then specifies a list of attributes (ATTLIST). Notice the action attribute, which tells the browser where to send the contents of the form, and the method attribute, which tells the browser how to send the contents of the form.
The <input> element makes text fields, radio buttons, check boxes, and so on in a form. Here's its DTD:
The <input> element makes text fields, radio buttons, check boxes, and so on in a form. Here's its DTD:
<!ENTITY % InputType
"(TEXT | PASSWORD | CHECKBOX |
RADIO | SUBMIT | RESET |
FILE | HIDDEN | IMAGE | BUTTON)"
>
<!-- attribute name required for all but submit and reset -->
<!ELEMENT INPUT - o EMPTY -- form control -->
<!ATTLIST INPUT
%attrs; -- %coreattrs, %i18n, %events --
type %InputType; TEXT -- what kind of widget is needed --
name CDATA #IMPLIED -- submit as part of form --
value CDATA #IMPLIED -- Specify for radio buttons and
checkboxes
--
checked (checked) #IMPLIED -- for radio buttons and check boxes --
disabled (disabled) #IMPLIED -- unavailable in this context --
readonly (readonly) #IMPLIED -- for text and passwd --
size CDATA #IMPLIED -- specific to each type of field --
maxlength NUMBER #IMPLIED -- max chars for text fields --
src %URI; #IMPLIED -- for fields with images --
alt CDATA #IMPLIED -- short description --
usemap %URI; #IMPLIED -- use client-side image map --
ismap (ismap) #IMPLIED -- use server-side image map --
tabindex NUMBER #IMPLIED -- position in tabbing order --
accesskey %Character; #IMPLIED -- accessibility key character -
onfocus %Script; #IMPLIED -- the element got the focus --
onblur %Script; #IMPLIED -- the element lost the focus --
onselect %Script; #IMPLIED -- some text was selected --
onchange %Script; #IMPLIED -- the element value was changed --
accept %ContentTypes; #IMPLIED -- list of MIME types for file upload --
>
The type attribute of the element specifies the type of control that will appear on the screen in your browser (text makes a text field, radio makes a radio button, and so on).
To create a Web page with a form in it, you could write the following HTML code in plain text, upload it to a Web server (or even just open it directly in your browser), and it would display as a nicely formatted Web page:
<html>
<head>
<title>
</title>
</head>
<body bgcolor="white">
<form method="post" action="http://www.example.com">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
This code creates a simple form with two fields (username and password) and a submit button. When submitted, the form's contents are sent to www.example.com.
How can you make HTML forms and PHP work together to make Web pages that are dynamically generated (rather than simply copied to your browser by the Web server)? First, you create a Web page using plain text HTML tags, and include an HTML form within that page. Then, you write PHP code within the Web page, making sure the code is properly enclosed by the <?php and ?> delimiters.
When the Web page is requested by a browser, any PHP code in it is resolved or processed by the PHP scripting engine before the results are returned to the user, and the results of PHP processing are placed in exactly the same spot as the original PHP code. You also could write your code so that it is only processed when there is a form submission (you'll see how in the next few sections). It may even use some of the submitted form data in its processing.
The end result of the PHP processing is HTML compatible, but because the PHP scripting engine has a chance to perform some processing before the final version of the Web page is sent, some of the content of the page (any parts generated by the PHP code) may differ each time the page is requested. And if processing takes place in response to a form submission, there are a great variety of interactive features that can be created.
Accessing PHP and HTTP Data
You know how HTTP works and you basically understand clients and servers, so you're very cognizant of the interaction between your browser (a client application) and the Web server (a server application) when running PHP programs online. In this Post you explore HTML forms and examine how they facilitate user interactions with the Web server (and thereby your PHP programs). These topics deserve a lot of attention because HTTP, HTML, and PHP are tightly intertwined. A good understanding of what's going on between the browser and the server is essential for PHP programming because within the requests and responses flying back and forth from client to server is a wealth of data you can utilize.
Each time you click a link or submit a form, you send a great deal of data about your system and your browser to the Web server, and each time the Web server responds, it sends you a great deal of data about itself. PHP has the capability to capture the data that is submitted by a browser, and also provides a means of getting at data about PHP's installation on the server. For instance, if you go to your favorite PHP-driven Web site and log in, it's likely that a predefined variable named $_POST is filled (on the server) with your username and password, another predefined variable named $_SERVER contains information about the current Web server environment, and that both are available to the PHP application running the site. These aspects of PHP are discussed in depth in the next few sections, but it's really kind of surprising how much data is available (especially considering that most folks aren't even aware of it). Read on to learn how to access all this data.
Predefined Variables
PHP automatically makes quite a few variables (called predefined variables) available anywhere in your program. They are array variables, and you can access them by name, like any other variable. By default, PHP is configured not to populate these variables (in the php.ini file, the default register_globals=Off is in place), you must use their entire name to access their data. For example, if a form has a text field named username and this field is filled out and submitted (and assuming the form's submission method is POST), you can access the field's data by code such as this:
$my_new_username = $_POST[username];
Predefined variables are also called superglobal variables because they can be accessed without regard to scope. Predefined variables consist of most of the information contained in HTTP requests and responses, including server variables, query strings, form variables, and so on. You can use predefined variables for any purpose, just like ordinary variables, but some of them may or may not be present for any given installation of PHP because Web servers vary in the data provided via HTTP. In the next section you'll see how to retrieve the data in predefined variables.
In addition to predefined variables, you can use the built-in PHP function phpinfo() to get basic PHP installation and operating information. This function not only enables you to test whether PHP is installed and working but also enables you to find out many details about how PHP is installed on the server. For example, you can find out what version of PHP is running, what OS your server is running on, and so forth.
Perhaps an easier way to demonstrate what you get from the phpinfo() function is simply to run the test01.php file created in again. This time you're running it not just to see if the installation of PHP worked but to examine the various kinds of data it provides. When run from your Web server, phpinfo() creates a very nicely formatted and detailed page (including all the required HTML tags) describing the PHP version, operating system, version of the ZEND engine, settings in your php.ini file, additional modules, and predefined variables .
Variables in HTTP Request and Response
There's a surprising amount of data passed back and forth between the client and the Web server (and vice versa). For example, not only is the IP address of the client passed to the Web server with each request (not actually very surprising, as how else would the Web server know where to send the response) but also details about what version of browser is making the request, cookies, form data, Web server version, and so on. The data is contained in predefined variables structured as associative arrays, so that you can access them by name, just like you would access any other array. The contents of each and what you might want to use them for are presented after the following "Try It Out."
There is a setting in your configuration file (php.ini) called register_globals. The default is off (since PHP4.2), and it restricts how you can access some predefined variables. From a practical standpoint, this means you should use the full name of the array ($_SERVER['DOCUMENT-ROOT'] is the example given) to access data in predefined variables. There is the function (import_request_variables()) that will import GET, POST, and Cookie variables into the global scope, so you can access them directly by name, but the full array name is recommended and therefore used in this post.
Links
If you've ever done any Web page design or programming, you're undoubtedly familiar with the structure of a link in HTML. In technical terms, an HTML link uses the anchor element (whose starting and ending tags are <a> and </a>), and one of its main attributes, href, which has a URL as its value. Text or images placed inside the beginning and ending <a> tags make a link that, when clicked, goes to the URL in the href attribute, like this:
<a href="http://www.myplace.com">Click Here</a>
So clicking a link is one form of user interaction enabling you to communicate with the server. But it's pretty limited, because all you can do is make a request for the page that's already supplied by the site designer. For example, if I click a link to the About page, the only reason it goes to the right page is because the site designer has already hard-coded the link with the URL for that page.
Query Strings
Somewhat more flexible is the query string, which is attached to the end of the URL in a link. A query string can consist of as many name/value pairs as you (the developer) want to supply. The big difference is that PHP provides a means by which the user can supply values that can be embedded in the query string. Say, for example, that the user has entered a value of John as his first name, and your PHP program can make use of that value via its variable name ($first_name, for instance).
The term name/value pair is a generic way of referring to any situation in which you have a named container for a value. Name/value pairs include fields in a table in a database, variables, HTML and XML attributes, and so on.
You could write a PHP program that generates a query string attached to a URL using code such as this (assuming you had the $first_name and $last_name variables already set):
<a href="http://www.myplace.com?first_name=<?php echo $first_name; ?>">Click
Here</a>
When this code runs, it produces the following output:
<a href="http://www.myplace.com?first_name=John">Click Here</a>
Notice how a query string is constructed: a question mark followed by the name of the first name/value pair, an equals sign, and the value in the first name/value pair. If you had both a first name and a last name, you could have included both name/value pairs in the query string by connecting them with an ampersand (&), like so:
<a href="http://www.myplace.com?first_name=<?php echo $first_name;
?>&last_name=<?php echo $last_name; ?>">Click Here</a>
Putting both name/value pairs in the query string would result in the following (if you're a dead movie star):
<a href="http://www.myplace.com?first_name=John&last_name=Wayne">Click
Here</a>
Query strings are often useful (especially in preserving values between page requests, which are discussed that a bit more later in the post, but as you can see they are still quite limited. For one thing, to place a user-supplied value in a query string, you have to already have it. You could get it from a database, but if you needed to get it from the user before using it, you'd have to provide the user with some free form method of supplying it. And that brings us to a very powerful method for user interaction, the HTML form.
The Concept of State
You're familiar with how desktop applications such as Excel, Word, Dreamweaver, and so on work. You start them up, they appear on your screen, and you do your work via documents, menu choices, dialog boxes, controls, and form fields. It can easily appear that there is no separation between the application's data processing logic and the user interface, but in fact every time you choose something from a menu, click a button, or enter something in a form field, you are actually using the user interface, and the user interface is communicating what you just did to the programming logic inside the application. The application then responds by performing its processing and providing a response to the user interface. For some actions you take there may be no visible response, whereas for others it is plain that a great deal of processing has taken place behind the scenes.
The point of this discussion is that as you provide input to the application via the user interface, you change the overall state of the application. You can think of state as the exact condition, moment to moment, of all the data and variables in the application. And the application has an obligation to take note of state changes, because it might have to respond to these changes with an action of its own (which then further changes the state of the application).
There are many things besides user interaction that can change the state of an application. For example, suppose you're playing a game and you have 15 seconds to make your move. The application will monitor the system clock and may make an action entirely independent of anything you do (except make your move) based on how many seconds have elapsed (another case of state change). What does this have to do with you? Well....
As a programmer, you may not think much about state when programming desktop applications, because you're used to seamless communications between your user interface and your programming logic. But programming for the Web forces you to address the issue, because HTTP communications are stateless. HTTP is a stateless protocol because there is no built-in mechanism that tracks the state of every object in the user interface and informs the programming logic of it, or vice versa.
Instead, communications between browser and server take the form of clicks on links or form submissions. Not only is this driven by the user (instead of being automatic), but for folks with slower connections or intermittent connections it can be slow and time-consuming. So building an online application with PHP requires you to use other mechanisms for maintaining state, and you need to take measures to cope with the fact that the user interface is disconnected and may not respond at all in the way you would ordinarily expect.
State Maintenance
The most direct way in which you'll be involved with state in PHP programs is when trying to preserve variable values between page requests because each page is its own program, and once the program is done processing, all variables and values are lost—the program's done, and everything is erased out of memory. Unlike desktop applications, which maintain data in memory until you shut them down, a PHP program runs only when a page request activates it, and then only until processing is completed and/or HTML or text content is returned to the user.
PHP is able to bridge the gap between each request-response and the next, providing persistence of data—and, yes, prolonged interactivity. This process of continually updating the server with information, a major ingredient in most interactive sites, is necessary to maintain a session. Session maintenance is how you refer to a series of interactions, beginning with the user accessing or logging on to a site, and ending with the user logging out or being timed out for inactivity.
The key to this process is usually a cookie (a small piece of data stored on the client's computer) or some sort of a variable that the client and server pass back and forth, often called a session key. These cookies and keys are used to help the server know which client it is interacting with for any given request. Just as a username identifies a user to a system, a session key (or an appropriate cookie) identifies a client to a Web site.
Sessions also maintain state across page requests and you'll examine them in detail a little later. First, take a look at some other methods available to you, including the use of hidden form fields, query strings, databases, and cookies.
Hidden Form Fields
You've seen how hidden form fields work to send data (coded by the designer) back to the server when the form is submitted. If you want to maintain state using hidden form fields (for example, a unique value representing a product the user is working with, such as the product ID), you can simply place the current product ID value into a hidden form field. Of course, the idea is that you would have the user select the product from a drop-down box (the select element) and then submit the form, using something like this code:
<form action="myform.php" method="post"> Query strings can be used in exactly the same way as hidden form fields to maintain state values across page requests. However, as previously discussed, their name/value pairs are displayed for all to see in the address bar of the browser, along with the URL. This is a very insecure method of transmitting data, and as you've probably guessed, easy for malicious users to break, disable, or otherwise mess with.
<select name="selected_product_id">
<option value="121">Product 121</option>
<option value="122">Product 122</option>
</select>
<input type="submit" name="button" value="Select Product">
</form>
You could return a page to him using the following code:
<input type="hidden" name="chosen_product_id" value="<?php echo
$selected_product_id; ?>">
Before the page is returned, the user's input would be processed as follows (assuming he chose product 122):
<form action="myform.php" method="post">
<input type="hidden" name="chosen_product_id" value="122">
So the next time he submits this form, part of the data submitted would be chosen_product_id, which PHP would turn into $chosen_product_id, and which you could then use anytime you wanted to perform processing on the product he chose, no matter how many page requests ago he chose that product. Don't forget, though, you'll need to populate that same hidden form field value each time the user requests another page or you'll lose that value.
Query Strings
Query strings can be used in exactly the same way as hidden form fields to maintain state values across page requests. However, as previously discussed, their name/value pairs are displayed for all to see in the address bar of the browser, along with the URL. This is a very insecure method of transmitting data, and as you've probably guessed, easy for malicious users to break, disable, or otherwise mess with.
Databases
The mechanics of databases and database access haven't been discussed yet but you're certainly aware that databases are useful for storing structured information persistently (meaning that the data is retained even if the server is turned off), so you can understand why databases are useful for storing data across page requests. Basically, if you don't mind the extra overhead of making a query on the database each time a page request occurs, you can use a table in the database to store all pertinent data that must be preserved across page requests. The downside, of course, is the overhead involved in those database connections, and the extra effort building the database in the first place.
Cookies
So what are cookies? They're a quick (and some would say messy) method of storing, on the client's computer, small snippets of data that you want to persist between separate visits to a Web site. They aren't very powerful or reliable—you certainly wouldn't want to use them for permanent data storage, because the mere act of switching browsers completely obliterates all your old cookies. But they can be very handy for a wide variety of things. Some of the most common examples of cookie use include the following:
1. Storing a user's aesthetic preferences for a specific site.
2. Storing a user key (or keys) that can be used to link users with their personal data—as used in countless shopping basket features, for example.
3. Providing a semi-permanent session key, enabling a user to remain logged on to a site until he explicitly asks to leave it or the browser closes.
Cookies are best used for small, helpful but non-critical things. One of the best examples of cookie use is to store preferences describing how a user wants your site to appear. Although the capability to customize a site's color scheme is a nice perk for users, those who can't (or won't) use cookies won't be missing much.
Intended as innocuous "helpers" for Web developers, cookies have built up a bad reputation in recent years. They are often overused (for example, to store large quantities of data which is really best kept on the server end) and sometimes even abused (to gather information on consumers without their knowledge, for instance). If used sparingly and responsibly, though, cookies can be useful in a number of situations. They tend to be most useful:
1. In situations where you know for a fact that all the visitors to your site will have cookie support enabled—on corporate and educational intranets, for example.
2. To add bells and whistles to a site—features that add to a site's appeal but aren't required to make use of it.
Messing Around with Cookies
Exact details of how cookies are implemented vary from browser to browser, but certain important points apply across the board, and these are as follows:
1. A cookie is a short piece of data that can be used to store a variable's name and value, along with information on the site from which it came and an expiry time.
2. Cookies provide client-side storage, usually held in files on the client machine's hard drive.
3. Web sites can usually only modify their own cookies.
4. They can be accessed and (if the appropriate security criteria are met) altered at will by the Web server from which they were originally sent.
When a client accesses a Web site that uses cookies, the Web server tells the client (usually a Web browser) to store away a given piece of data for later use. The client is then responsible for storing that data away. Cookie-supporting browsers accomplish this by storing the data in a file named after the site the cookie belongs to, in a directory they keep reserved for this purpose. On subsequent requests to that site, the client sends back a copy of that data—the data persists on the client side until a specified period expires, causing it to be removed from the system. This specified period is set by the server when it tells the client to create the cookie, and is basically a number of seconds for which the client should keep the cookie. If the server tells the client to set an expiry period of zero seconds, the browser should keep the cookie only until the user quits the browser application.
Because cookies are kept on the client side, they're not under the control of the server once they've been created. Users can elect to delete cookies themselves, often simply by clicking a button in their browser, or by deleting the browser's cookie files. They could also edit the contents of the files if the urge took them. Just because you wrote what's in the cookie, doesn't mean you should always expect the right data to come back!
Essentially, cookies are the server telling the client "here's something to remember; remind me of it when you come back next time." Next time could be anything from when you click that link two seconds from now to when you come back next week. That's some serious persistence! It's a little like being at a conference where delegates can be identified by their name badges for as long as they care to wear them.
Web servers send clients cookies in HTTP headers, which are sent before any HTML text. Likewise, clients send back those cookies using HTTP headers. A client knows which cookies to share with a Web site, based on the server and path the client is currently accessing. So, if you're accessing www.php.net, the browser doesn't send any cookies it received from www.wrox.com.
When a cookie is set, a server name and path name can optionally be set—this limits access to the cookie to the specified server and/or path on that server. Clients use this information to determine whether they should send any given cookie. A cookie-enabled browser generally sends any and all cookies that it thinks applicable to a given site in the headers of any given access.
Set and Retrieve Cookies
PHP, as a modern Web scripting language, comes with full support, and setting cookie variables is as simple as making a call to setcookie(). As with header(), setcookie() must be called before any HTML is printed to the client's browser because cookies are set in the HTTP headers, which must be sent before any HTML.
The setcookie() function takes six parameters, of which the first three are by far the most important: These are, in order:
1. A string to be used as the name of the variable.
2. A string to be used as the value of the variable.
3. A UNIX timestamp denoting the time at which the cookie will expire.
A UNIX timestamp is simply a long integer that represents a time and date by counting seconds since midnight on 01/01/1970. You can get the current time in this form by using the function time(). If you want to set a cookie to expire an hour from now, simply specify time() + 3600 for the third parameter.
The last three parameters to setcookie() are less frequently used:
1. The path to whose files the cookie is relevant; the browser doesn't return cookies that are from inappropriate paths. For example, if you set this parameter to /my/path/number/one and accessed a page in /my/path/number/two, your browser wouldn't send the cookie. If you went back to a page in /my/path/number/one, the browser would send the cookie.
2. The domain to which the cookie applies; same rules apply as to the preceding parameter. This parameter may be useful if your Web server hosts multiple domains.
3. An integer called secure. Set it to 1 if you only want your cookie to be sent when requesting an SSL-encrypted page. (The cookie won't be stored in an encrypted form on the client's hard drive; this setting merely ensures that the cookie will be encrypted for transmission across the Internet.)
In the simplest possible situation, you could leave off these last three, so that a typical call to setcookie() might look like this:
setcookie("fontprefs", "", time()+3600);
Accessing cookies is even simpler—there's nothing to call at all! Just as it does with POST variables, PHP automatically puts cookie information in the global domain, so it's as simple to use cookie values as it is to use any other variables. For example, the value of a received cookie called fontprefs is automatically be available throughout the script as the global variable
$_COOKIES['fontprefs'].
There are several ways to delete a cookie. Of course, if the client knows where to look on his machine, he can always edit or delete the files in which cookies are stored. However, it's sometimes useful to be able to get the server to delete (or "eat") a cookie, and if this is the case, there are two main options:
1. Reset the cookie's expiry time to a time in the past: setcookie("num", "0", time() -9999);, for example.
2. Reset the cookie, specifying only its name: setcookie("fontprefs");, for example.
The last three parameters to setcookie() are less frequently used:
The path to whose files the cookie is relevant; the browser doesn't return cookies that are from inappropriate paths. For example, if you set this parameter to /my/path/number/one and accessed a page in /my/path/number/two, your browser wouldn't send the cookie. If you went back to a page in /my/path/number/one, the browser would send the cookie.
The domain to which the cookie applies; same rules apply as to the preceding parameter. This parameter may be useful if your Web server hosts multiple domains.
An integer called secure. Set it to 1 if you only want your cookie to be sent when requesting an SSL-encrypted page. (The cookie won't be stored in an encrypted form on the client's hard drive; this setting merely ensures that the cookie will be encrypted for transmission across the Internet.)
In the simplest possible situation, you could leave off these last three, so that a typical call to setcookie() might look like this:
setcookie("fontprefs", "", time()+3600);
Accessing cookies is even simpler—there's nothing to call at all! Just as it does with POST variables, PHP automatically puts cookie information in the global domain, so it's as simple to use cookie values as it is to use any other variables. For example, the value of a received cookie called fontprefs is automatically be available throughout the script as the global variable $_COOKIES['fontprefs'].
There are several ways to delete a cookie. Of course, if the client knows where to look on his machine, he can always edit or delete the files in which cookies are stored. However, it's sometimes useful to be able to get the server to delete (or "eat") a cookie, and if this is the case, there are two main options:
Reset the cookie's expiry time to a time in the past: setcookie("num", "0", time() -9999);, for example.
Reset the cookie, specifying only its name: setcookie("fontprefs");, for example.
Native Sessions in PHP
A session can be defined as a series of related interactions between a single client and the Web server, which take place over an extended period of time. This could be a series of transactions that a user makes while updating his stock portfolio, or the set of requests that are made to check an e-mail account through a browser-based e-mail service. The session may consist of multiple requests to the same script, or of requests to a variety of different resources on the same Web site.
Particularly when you want to work with sensitive (or bulky) information, it makes a lot of sense to submit it once and have it stored on the server. Rather than storing the actual data on the client machine, and have to pass it back and forth between the server and client each time, it's far more practical to keep the data on the server, but give the client a "key" to allow it to uniquely identify itself, and consequently any server-side data associated with it. This key is called a session identifier; it uniquely associates a client with a session, and therefore with its data. In PHP, the session identifier is known as the SID (Session ID). SID is a special variable that's specified as a reference number for any particular session.
You saw how to establish a session of sorts when you used cookies to make data persist on the client machine. As noted at the time, though, that isn't a terribly secure way to manage sessions. Fortunately, PHP comes with its own session management system built in, so you don't need to worry too much about the precise implementation details. PHP creates its SID whenever you use the session_start() function, and also by default if you use certain other session-related functions, such as session_register(). The value of the SID is kept in a global variable named PHPSESSID.
You can think of the SID as being like the reference number on an electric bill: you're given the number, the electric company files your details under that number, and presto! You no longer have to give the company all your details every time you call up to complain about its outrageous charges. The SID is automatically created and passed back and forth for you, each time the user clicks a link or submits form.
When you start a PHP session, the server assigns it a session ID, or SID. Any variables that you register as session variables (you'll see how to do this in a moment) are then stored on the server in a cookie-like file. The name of this file is generally the same as the value of the SID. All the client has to do to access this data is to include the SID in its request to the server. It can use a hidden form field, a query string, a cookie, anything at all, as long as the SID makes it into the HTTP request. The server looks up the appropriate session data and makes it available for use in whatever script it then executes.
If you have cookie support enabled, even this is taken care of, because the session manager automatically sends the client a cookie for the SID value. If you can't (or don't want to) use cookies, the simplest thing to do is to add the SID as a term in all query strings that point back to your Web site.
PHP sessions handle this all very neatly; they're an excellent way to learn how to build interactive sites quickly because they completely free you up from worrying about the nitty-gritty details of implementing persistence, and let you get on with the business of building your site. One particularly nice aspect is the knowledge that you have literally thousands of coders scrutinizing your persistence mechanism (because it's a part of PHP itself!) and ensuring that the underlying code works as well as possible. What's more, sessions are very well documented in the core PHP documentation, available at the official PHP Web site (www.php.net/). So, sessions are easy, reliable, and almost universally available; but how exactly do you use them?
In most cases, using PHP sessions is as simple as telling PHP, "I want variables X, Y, and Z to remain persistent," and letting PHP do the work. All that you, the coder, need to worry about is how to tell PHP to register a session variable—that is, make a given variable persistent—and then how to access those variables.
The function for registering a persistent variable for use with PHP sessions is session_register(). Given the name (without the dollar sign) of a variable, it makes that variable and its contents persist for the duration of the current session. If there isn't currently a session defined, a new one is created automatically. The length of the session (how long the session remains intact without the user having to use the site) is determined by the session timeout setting in the php.ini file. The default is 1,440 seconds (24 minutes).
If you wanted to maintain persistent variables called myvar1 and myvar2, for example, here's how you'd begin your PHP script:
<?php
session-register("myvar1");
session-register("myvar2");
?>
You must put this code at the top of the script. Behind the scenes, you're using cookies. Again, to not mess with HTTP headers, you must be sure to register all the session variables before any HTML headers are sent out. It's good practice to do so at the very top of a script, in a self-contained snippet of PHP, as shown.
Once you've registered a variable, retrieving its contents is ridiculously simple—just access the session variable as if it were any other global variable! If you used the preceding code to register variables $myvar1 and $myvar2, you can use them just like any other variables. The only difference is that they persist for as long as the session lasts, so that the next time the page is called within the session, by the same user, the variables will contain the same values they had when the page finished executing the last time.
To use PHP sessions with Windows, you may need to modify the variable session.save_path in your php.ini file so that it refers to a valid Windows directory (D:\WinNT\Temp, for example, where D is the letter for your hard drive).
Summary
This Post covered the many predefined variables available to your PHP program anytime a request and response occurs between the client and the Web server. The display and use of individual predefined variables such as $_SERVER, $_REQUEST, and so on also were discussed.
You learned the basics for making your PHP programs interactive: query strings in links (using the <a> element) and HTML forms (using the <input>, <textarea>, and <select> elements). You also learned the differences between the GET and POST methods, and examined the circumstances under which you might want to use one over the other.
Finally, you explored the concept of state, what it means that HTTP is stateless, and how to overcome HTTP's stateless limitations using hidden form fields, query strings, cookies, sessions, and even databases to store and transmit state information across page requests.
Thank you.I hope this post help you.
Thanks for providing great informatic and looking beautiful blog, really nice required information & the things I never imagined, and I would request, wright more blog and blog post like that for us. Thank you once again
ReplyDeleteby Cloudi5
Web Design Company in Coimbatore
Thanks for your valuable feedback...!!
Delete