Anything 2 Share All - Tips Make money online-Phim-video clip-wallpage-software-picture!

Share for all tip, tut, free picture, film, video clip, wallpage, software, etc...

Core PHP Programming - Part I: Programming with PHP!

The first part of this book is a thorough discussion of PHP as a programming language. You will be introduced to common concepts of computer science and how they are implemented in PHP. No prior programming experience beyond the use of simple mark-up languages is necessary. That is, you must be familiar with HTML. These chapters focus on building a foundation of understanding rather than on how to solve specific problems. If you have experience programming in a similar language, such as C or Perl, you may choose to read Chapter 1 and skim the rest, saving it as a reference. In most situations, PHP treats syntax much as these two languages do.
Chapter 1 is an introduction to PHP—how it began and what it looks like. It may be sufficient for experienced programmers, since it moves quickly through PHP's key features. If you are less experienced, I encourage you to treat this chapter as a first look. Don't worry too much about exactly how the examples work. I explain the concepts in depth in later chapters.
Chapter 2 introduces the concepts of variables, operators, and expressions. These are the building blocks of a PHP script. Essentially, a computer stores and manipulates data. Variables let you name values; operators and expressions let you manipulate them.
Chapter 3 examines the ways PHP allows you to control program execution. This includes conditional branches and loops.
Chapter 4 deals with functions, how they are called and how to define them. Functions are packages of code that you can call upon repeatedly.
Chapter 5 is about arrays—collections of values that are identified by either numbers or names. Arrays are a very powerful way to store information and retrieve it efficiently.
Chapter 6 is about classes, presenting an object-oriented approach to grouping functions and data. Although not strictly an object-oriented language, PHP supports many features found in OO languages such as Java.
Chapter 7 deals with how PHP sends and receives data. Files, network connections, and other means of communication are covered.

1.1 The Origins of PHP

Wonderful things come from singular inspiration. PHP began life as a simple way to track visitors to Rasmus Lerdorf's resume. It also could embed SQL queries in Web pages. But as often happens on the Web, admirers quickly asked for their own copies. As a proponent of the Internet's ethic of sharing, and as a generally agreeable person, Rasmus unleashed upon an unsuspecting Web his Personal Home Page Tools version 1.0.
"Unleashed upon himself" may be more accurate. PHP became very popular. A consequence was a flood of suggestions. PHP 1.0 filtered input, replacing simple commands for HTML. As its popularity grew, people wondered if it couldn't do more. Loops, conditionals, rich data structures—all the conveniences of modern structured programming seemed like a next logical step. Rasmus studied language parsers, read about YACC and GNU Bison, and created PHP 2, otherwise known as PHP/FI.
PHP/FI allowed developers to embed structured code inside HTML tags. PHP scripts could parse data submitted by HTML forms, communicate with databases, and make complex calculations on the fly. And it was very fast because the freely available source code compiled into the Apache Web server. A PHP script executed as part of the Web server process and required no forking, often a criticism of Common Gateway Interface (CGI) scripts.
PHP was a legitimate development solution and began to be used for commercial Web sites. In 1996, Clear Ink created the SuperCuts site (www.supercuts.com) and used PHP to create a custom experience for the Web surfer. The PHP Web site tracks the popularity of PHP by measuring how many different Web sites use the PHP module. When writing the second edition of this text, it seemed really exciting that PHP had grown from 100,000 sites to 350,000 sites during 1999. The most recent data show more than 10 million domains using PHP!
In 1997, a pair of Israeli students named Andi Gutmans and Zeev Suraski attempted to use it for building an online shopping cart, considered cutting-edge enough to be a university project. Shortly after they started, they stumbled upon various bugs in PHP that made them look under the hood at the source code. To their surprise, they noticed that PHP's implementation broke most of the principles of language design, which made it prone to unexpected behavior and bugs. Always looking for good excuses not to study for exams, they started creating a new implementation. In part, the task was a test of their programming abilities, in part a recreation. A few months later, they had rewritten PHP from scratch, making it a real, consistent, and robust language for the first time. Having spent so much time on the project, they asked the course teacher, Dr. Michael Rodeh, for academic credit in an attempt to avoid unnecessary exams. Being the manager of the IBM Research Lab in Haifa and well aware of the overwhelming number of different languages to choose from, he agreed—with the stipulation that they cooperate with the existing developers of PHP/FI instead of starting their own language.
When Andi and Zeev emailed Rasmus with the news about their rewrite, they wondered if he would accept this new work, as it essentially meant discarding his implementation. Rasmus did accept it, and a new body was formed—the PHP Core Team, known today as the PHP Group. Along with Andi, Rasmus, and Zeev, three other developers—Stig Bakken, Shane Caraveo, and Jim Winstead—were accepted to the Core Team. A community of developers started growing around PHP.
After seven months of development, alpha and beta testing, PHP version 3.0 was officially released on June 6, 1998, and started bending the curve of PHP's growth to unprecedented angles. PHP's functionality was growing on a daily basis, and PHP applications were popping up everywhere. Following the release, Open Source projects written in PHP flourished. Projects like Phorum tackled long-time Internet tasks such as hosting online discussion. The PHPLib project provided a framework for handling user sessions that inspired new code in PHP. FreeTrade, a project I led, offered a toolkit for building e-commerce sites.
Writing about PHP increased as well. More than 20 articles appeared on high-traffic sites such as webmonkey.com and techweb.com. Sites dedicated to supporting PHP developers were launched. The first two books about PHP were published in May 1999. Egon Schmid, Christian Cartus, and Richard Blume wrote a book in German called PHP: Dynamische Webauftritte professionell realisieren. Prentice Hall published the first edition of my book, Core PHP Programming. Since then, countless books about PHP fill bookstore shelves.
Given this background, there were no reasons not to be happy with the way PHP was back then. Perhaps the internal knowledge of what was going on under the hood and the feeling familiar to every developer—"I could have done it much better"—were the reasons that Andi and Zeev were some of the very few people who felt unhappy with PHP 3. As if out of habit, they withdrew from the PHP community and attempted to design a new approach towards executing PHP scripts.
A few months later, on January 4, 1999, Zeev and Andi announced a new framework that promised to increase dramatically the performance of PHP scripts. They dubbed the new framework the Zend Engine. Early tests showed script execution times dropping by a factor of 100. In addition, new features for compiling scripts into binary, debugging, optimization, and profiling were planned. This announcement officially ended the PHP 3.1 project, which was supposed to bring better Windows support to PHP 3 but failed to gain momentum, and officially started the planning of PHP 4.
Work on the Zend Engine and PHP 4 continued in parallel with bug fixes and enhancements to PHP 3. During 1999, eight incremental versions were released, and on December 29, 1999, PHP version 3.0.13 was announced. A PHP beta based on the Zend Engine became publicly available in July 19, 1999, and was followed by an intense development period of various components, some of which were brand new, such as built-in session handling, output buffering, and a Web server abstraction layer. The release of PHP 4 on May 22, 2000, marked another important milestone on PHP's journey to becoming the most popular Web development platform on earth. The number of people working on various levels of PHP has grown immensely, and new projects, most notably PEAR, gained momentum and started pushing PHP to new heights of popularity.
The PHP community drives the development of new features. Many programmers find inspiration in object-oriented programming. PHP 3 introduced objects as syntactic sugar. That is, while the syntax used for objects was different, the underlying implementation varied little from arrays. It attracted many object-oriented advocates, but the limited implementation left them desiring more. PHP 5 addresses these needs with a strong, rebuilt object system.

PHP is not a shrink-wrapped product made by faceless drones or wizards in an ivory tower. PHP started as a simple tool brought into the bazaar described by Eric Raymond in his essay The Cathedral and the Bazaar. Once it appeared, anyone could make improvements, and many did. Their aim seems to be to achieve solutions of direct, personal interest. If a client comes along who requires a project to use a database not supported by PHP, you simply write an extension. Then you give it to the PHP project. Soon, other people are fixing your bugs.
Yet, the vast majority of PHP users never write an extension. They happily find everything they need in the contributed works of others. Those who've contributed thousands of lines of code to PHP perhaps never consider themselves heroes. They don't trumpet their accomplishments. But because each part of PHP came from a real person, I would like to point them out. When appropriate, I'll note who added a particular extension.

1.2 PHP Is Better Than Its Alternatives

In previous years, skeptics may have asked, Why should I learn PHP? Today, PHP's popularity is enough to generate interest in learning it. PHP is a standard feature offered by most Web hosting companies. However, it is interesting to understand why so many people choose PHP over alternatives.
Perl adapted well to being a CGI solution. Microsoft provides its Active Server Pages with Internet Information Server. Middleware, like Macromedia's Cold Fusion, is yet another solution. ServerWatch.com lists hundreds of Web technologies, some costing tens of thousands of dollars. Why should you choose PHP over any of these alternatives?
The short answer is that PHP is better. It is faster to code and faster to execute. The same PHP code runs unaltered on different Web servers and different operating systems. Additionally, functionality that is standard with PHP is an add-on in other environments. A more detailed argument follows.
PHP is free. Anyone may visit the PHP Web site <http://www.php.net/> and download the complete source code, licensed under a BSD-style license <http://www.php.net/license/>. Binaries are also available for Windows. The result is easy entry into the experience. There is very little risk in trying PHP, and its license allows the code to be used to develop works with no royalties. This is unlike products such as Allaire's Cold Fusion, which costs thousands of dollars for the software to interpret and serve scripts. Even commercial giants like Netscape and IBM now recognize the advantages of making source code available.
PHP runs on UNIX, Windows, and Macintosh OS X. PHP is designed to integrate with the Apache Web server. Apache, another free technology, is the most popular Web server on the Internet and comes with source code for UNIX and Windows. PHP works with other Web servers, including Microsoft's Internet Information Server. Scripts may be moved between server platforms without alteration. PHP supports ISAPI to allow for the performance benefits of tight coupling with Microsoft Web servers.
PHP is modifiable. PHP is designed to allow for future extension of functionality. PHP is coded in C and provides a well-defined application programming interface (API). Capable programmers may add new functionality easily. The rich set of functions available in PHP is evidence that they often do. Even if you aren't interested in changing the source code, it's comforting to know you can inspect it. Doing so may give you greater confidence in PHP's robustness.
PHP was written for Web page creation. Perl, C, and Java are very good general languages and are certainly capable of driving Web applications. The unfortunate sacrifice these alternatives make is the ease of communication with the Web experience. PHP applications may be rapidly and easily developed because the code is encapsulated in the Web pages themselves.
Support for PHP is free and readily available. Queries to the PHP mailing lists are often answered within minutes. A custom bug-tracking system on the PHP site shows each problem along with its resolution. Numerous sites, such as phpbuilder.com and zend.com, offer original content to PHP developers.
PHP is popular. Internet service providers find PHP to be an attractive way to allow their customers to code Web applications without the risks exposed by CGIs. Developers worldwide offer PHP programming. Sites coded in PHP will have the option of moving from one host to another as well as a choice of developers to add functionality.
Programming skills developed in other structured languages can be applied to PHP. PHP takes inspiration from both Perl and C. Experienced Perl and C programmers learn PHP very quickly. Likewise, programmers who learn PHP as a first language may apply their knowledge toward not only Perl and C, but other C-like languages such as Java.

1.3 Interfaces to External Systems

Originally, PHP was famous for interfacing with many different database systems, but it also has support for other external systems. Support comes in the form of modules called extensions. They either compile directly into PHP or are loaded dynamically. New extensions are added to the PHP project regularly. The extensions expose groups of functions for using these external systems. As mentioned, some of these are databases. PHP offers functions for talking natively with most popular database systems, and it provides access to ODBC drivers. Other extensions give you the ability to send messages using a particular network protocol, such as LDAP or IMAP. These functions are described in detail in Part II. Because PHP developers are enthusiastic and industrious, you will undoubtedly find more extensions have been added since I wrote this.
Pspell is a system for checking spelling. An extension provides support for numbers of arbitrary precision. There is an extension for dealing with various calendar systems. An extension provides support for DBM-style databases. You can use the SNMP, IMAP, and LDAP protocols. The Interbase and Informix databases are supported natively, as are mSQL, MySQL, MS SQL, Sybase, Oracle, and PostgreSQL. You can also parse XML or create WDDX packets. You can even extract meta information about your digital pictures using the EXIF extension. At the time of writing, automated coffee making is not yet supported.

1.4 How PHP Works with the Web Server

The normal process a Web server goes through to deliver a page to a browser is as follows. It all begins when a browser makes a request for a Web page. Based on the URL, the browser resolves the address of the Web server, identifies the page it would like, and gives any other information the Web server may need. Some of this information is about the browser itself, like its name (Mozilla), its version (4.08), or the operating system (Linux). Other information given the Web server could include text the user typed into form fields.
If the request is for an HTML file, the Web server will simply find the file, tell the browser to expect some HTML text, and then send the contents of the file. The browser gets the contents and begins rendering the page based on the HTML code. If you have been programming HTML for any length of time, this will be clear to you.
Hopefully, you have also had some experience with CGI scripts. When a Web server gets a request for a CGI, it can't just send the contents of the file. It must execute the script first. The script will generate some HTML code, which then gets sent to the browser. As far as the browser is concerned, it's just getting HTML.
When a PHP page is requested, it is processed exactly like a CGI, at least to the extent that the script is not simply sent to the browser. It is first passed through the PHP engine, which gives the Web server HTML text.

1.5 Hardware and Software Requirements

One great advantage of Open Source software is that it provides the opportunity for adaptation to new environments. This is true of PHP. Although originally intended as a module for the Apache Web server, PHP has since abstracted its Web server interface. The new abstraction layer allowed an ISAPI module to be written, which allows it to work equally well with Microsoft's Internet Information Server. With regard to hardware requirements, I have personally witnessed PHP running on 100-MHz Pentium machines running Slackware Linux and Windows NT respectively. Performance was fine for use as a personal development environment. That the engines for PHP 3 and 4 were developed on Intel 486 CPUs must have helped. A site expected to receive thousands of requests a day would need faster hardware, of course. Although more resources are needed when comparing a PHP-powered site to a flat HTML site, the requirements are not dramatically different. Despite my example, you are not limited to Intel hardware. PHP works equally well on PowerPC, Sparc, and other 32-bit or better CPUs.
When choosing an operating system, you have the general choice between Windows and a UNIX-like OS. PHP will run on older Windows operating systems, although these operating systems aren't suited for high-traffic Web servers. It will also run on Windows 2000 and Windows XP. For UNIX operating systems, PHP works well with Linux and Solaris as well as others. If you have chosen a PPC-based system, such as a Macintosh, you may choose LinuxPPC, a version of Linux. Chad Cunningham contributed patches for compiling PHP in Apple's OS X. There's even support of IBM's OS/2 and Novell Netware.
PHP still works best with the Apache Web server. But it now works very well with IIS. It also compiles as a module for the fhttpd Web server. You can make PHP work with almost any Web server using the CGI version, but I don't recommend this setup for production Web sites.

Installation on Apache for UNIX

If you are using Linux, you can easily find an RPM for Apache and PHP, but this installation may not include every PHP feature you want. I recommend this route as a very quick start. You can always pursue compiling Apache and PHP from scratch later. PHP will compile on most versions of UNIX-like operating systems, including Solaris and Linux. If you have ever compiled software you've found on the Net, you will have little trouble with this installation. If you don't have experience extracting files from a tar archive and executing make files, you may wish to rely on your system administrator or someone else more experienced. You will need to have root privileges to completely install PHP.
The first step is to download the tar files and unpack them. Download the newest versions from the PHP site <http://www.php.net/downloads.php> and the Apache site <http://httpd.apache.org/>. At the time of writing, Apache 2 is considered stable. Support for mod_php in Apache is not complete. The following instructions assume Apache 1.3 and Apache 2 may require a few changes.
After unpacking the tar file, the first step is to configure Apache. This is done by running the configure script inside the Apache directory. Listing 1.1 shows a minimal configuration.
Listing 1.1 Configuring Apache
./configure \
--server-uid=nobody \
--enable-module=so
The script will examine your system and prepare a make file for Apache. This builds Apache for using shared libraries, one of which will be PHP. You should follow the configuration step with make install, which will compile Apache and install the binaries in the default location. You may wish to test Apache by starting it with the /usr/local/apache/bin/apachectl script.
Next, configure and compile PHP. Listing 1.2 shows a command for configuring PHP with a few extensions, executed within the PHP source code directory. Follow this with a make install. In most cases, PHP can find the libraries it needs for extensions. In Listing 1.2, I'm specifically using the MySQL libraries I have in /usr/libs rather than the MySQL libraries included in the PHP distribution.
Appendix E lists the compile-time configuration directives. You can also get information by running ./configure --help. Running make will create the PHP library, and make install places the PHP module in Apache's directory of modules. It also installs the latest PEAR classes, a collection of standard PHP code.
Listing 1.2 Configuring PHP
./configure \
--with-apxs=/usr/local/apache/bin/apxs \
--with-zlib \
--with-bz2 \
--with-openssl \
--with-gd \
--enable-exif \
--with-jpeg-dir=/usr \
--with-freetype-dir \
--with-t1lib \
--enable-gd-native-ttf \
--with-mysql=/usr
To supply additional configuration options, PHP uses a file called php.ini. This file should reside in /usr/local/lib, so copy it from the PHP source directory (Listing 1.3):
Listing 1.3 Copying php.ini
cp php.ini-dist /usr/local/lib/php.ini
You may not need to edit this file. It controls certain aspects of PHP, including support for historic behavior. Chapter 15 discusses configuration directives you may use in php.ini. Many of them are in the default file. Some you must add.
The last step is to make sure Apache recognizes PHP scripts. Somewhere in Apache's configuration file, httpd.conf, you need an AddType directive that matches scripts ending in .php with application/x-httpd-php. You also need to load the PHP module. If the lines in Listing 1.4 do not appear in httpd.conf, add them.
Listing 1.4 Activating PHP for Apache
LoadModule php5_module libexec/libphp5.so
AddType application/x-httpd-php .php
AddModule mod_php5.c
This causes all files with the extension .php to be executed as PHP scripts. You may also wish to insert index.php as a default document. When the Apache server is started, it will process PHP scripts. The documentation for Apache has hints for starting Apache automatically. If you have been running Apache previously, you will need to restart it, not just use a kill –HUP command.

Installation on Apache for Windows

Compiling PHP for Windows is not an ordinary task. Windows users typically use binaries available on the PHP Web site. The same is true for Apache. Both packages include automated installers, which makes installation easy. Installing Apache this way is fine. I prefer to install PHP manually, using the archive, because it allows for better flexibility.
Unzip the PHP archive into a directory. I use C:\PHP, but you can really put it anywhere. Next, copy the file php.ini-dist into your system root directory, which is probably C:\Windows. Rename it php.ini. When PHP is invoked, it looks first for php.ini in this directory. Although you don't need to, you may wish to edit it to change configuration parameters, including automatically loading extensions. Comments in the file explain the purpose of each configuration directive. Chapter 15 discusses them in detail.
The next step is to make sure the required DLL files are in your path. One way is to copy required files to your system directory, such as C:\Windows\system32. Alternatively, you can click on the system icon in the control panel and add your PHP directory to the system path. Your Web server must be able to find php4ts.dll, which is in the root of the PHP installation directory.
Next, configure Apache to load the PHP module. Edit httpd.conf and add the lines in Listing 1.5. These lines load the module and associate the .php extension with PHP script. The final step is restarting Apache.
Listing 1.5 Activating PHP for Apache on Windows
LoadModule php5_module c:/php/sapi/php5apache.dll
AddType application/x-httpd-php .php
AddModule mod_php5.c

Editing Scripts

PHP scripts are just text files, and you can edit and create them just as you would HTML files. Certainly, you can telnet into your Web server and start creating files with vi. Or you can create files with Notepad and use FTP to upload them one by one. But these aren't ideal experiences. One handy feature of newer editors is built-in FTP. These editors can open files on a remote Web server as if they were on a local drive. A single click saves them back to the remote Web server. Another feature you may enjoy is syntax highlighting. This causes PHP keywords to be colored in order to help you read the code faster.
Everyone has a favorite editor for PHP scripts. I use UltraEdit <http://www.ultraedit.com/>. I know many Windows users prefer Macromedia's Dreamweaver <http://www.macromedia.com/software/dreamweaver/> or HomeSite <http://www.macromedia.com/software/homesite/> to edit PHP scripts. The Macintosh users I know prefer BBedit <http://www.barebones.com/products/bbedit/bbedit.html>.
On a UNIX operating system, you may prefer emacs or vi, of course. You might also consider nEdit <http://nedit.org/>. A module for PHP is available in the contrib directory. The topic of which editor is best appears frequently on the PHP mailing list. Reading the archives can be amusing and informative <http://www.progressive-comp.com/Lists/?l=php3-general>.
Although I continue to use a text editor for building PHP applications, many people prefer an integrated development environment, otherwise known as an IDE. There are several IDEs designed specifically for PHP. PHPEdit <http://www.phpedit.net/> is one example. The Zend Studio <http://www.zend.com/store/products/zend-studio.php> is another very popular choice.

Algorithms

Whenever we interact with a computer, we are instructing it to perform some action. When you drag an icon into the wastebasket on your desktop, you are asking the computer to remove the file from your hard disk. When you write an HTML file, you are instructing the computer in the proper way to display some information. There are usually many incremental steps to any process the computer performs. It may first clear the screen with the color you specified in the body tag. Then it may begin writing some text in a particular color and typeface. As you use a computer, you may not be entirely aware of each tiny step it takes, but you are giving it a list of ordered instructions that you expect it to follow.
Instructions for baking a cake are called a recipe. Instructions for making a movie are called a screenplay. Instructions for a computer are called a program. Each of these is written in its own language, a concrete realization of an abstract set of instructions. Borrowing from mathematics, computer science calls the abstract instructions an algorithm.
You may at this moment have in mind an algorithm that you'd like to implement. Perhaps you wish to display information in a Web browser that changes frequently. Imagine something simple, such as displaying today's date. You could edit a plain HTML file once a day. You could even write out a set of instructions to help remind you of each step. But you cannot perform the task with HTML alone. There's no tag that stands for the current date.
PHP is a language that allows you to express algorithms for creating HTML files. With PHP, you can write instructions for displaying the current date inside an HTML document. You write your instructions in a file called a script. The language of the script is PHP, a language that both you and the computer can understand.



1.6 What a PHP Script Looks Like

PHP exists as a tag inside an HTML file. Like all HTML tags, it begins with a less than symbol, or opening angle bracket (<), and ends with a greater than symbol, or closing angle bracket (>). To distinguish it from other tags, the PHP tag has a question mark (?) following the opening angle bracket and preceding the closing angle bracket. All text outside the PHP tag is simply passed through to the browser. Text inside the tag is expected to be PHP code and is parsed.
To accommodate XML and some picky editors such as Microsoft's Front Page, PHP offers three other ways to mark code. Putting php after the opening question mark makes PHP code friendly to XML parsers. Alternatively, you may use a script tag as if you were writing JavaScript. Finally, you can use tags that appear like ASP, using <% to start blocks of code. Appendix D explains how these alternatives work. In my own coding, I frequently use the simple and ?> method because I can be sure I can configure PHP to accept them. For code you share with others, it's best to use for the opening tag, as I have in the examples.
Listing 1.6 shows an ordinary HTML page with one remarkable difference: the PHP code between the and the ?>. When this page is passed through the PHP module, it will replace the PHP code with today's date. It might read something like Friday May 1, 1999 (see Figure 1.1).
Listing 1.6 Printing today's date


Listing 1-6


Today's date: 




Whitespace—that is, spaces, tabs, and carriage returns—is ignored by PHP. Used judiciously, it can enhance the readability of your code. Listing 1.7 is functionally the same as the previous example, though you may notice more easily that it contains PHP code.
Listing 1.7 Reformatting for readability


Listing 1-7


Today's date:
    /*
    ** print today's date
    */
    print(Date("l f d, y"));
?>

You may also notice the line of code in Listing 1.7 that begins with a slash followed by an asterisk. This is a comment. Everything between /* and */ is equivalent to whitespace. It is ignored. Comments can be used to document how your code works. Even if you maintain your own code, you will find comments necessary for all but simple scripts.
In addition to the opening and closing comment statements, PHP provides two ways to build a single-line comment. Double slashes or a pound sign will cause everything after them to the end of the line to be ignored by the parser.
After skipping over the whitespace and the comment in Listing 1.7, the PHP parser encounters the first word: print. This is one of PHP's functions. A function collects code into a unit you may invoke with its name. The print function sends text to the browser. The contents of the parentheses will be evaluated, and if it produces output, print will pass it along to the browser.
Where does the line end? Unlike BASIC and JavaScript, which use a line break to denote the end of a line, PHP uses a semicolon. On this issue PHP takes inspiration from C.
The contents of the line between print and ; is a call to a function named date. The text between the opening and closing parentheses is the parameter passed to date. The parameter tells date in what form you want the date to appear. In this case we've used the codes for the weekday name, the full month name, the day of the month, and the four-digit year. The current date is formatted and passed back to the print function.
The string of characters beginning and ending with double quotes is called a string constant or string literal. PHP knows that when quotes surround characters, you intend them to be treated as text. Without the quotes, PHP will assume you are naming a function or some other part of the language itself. In other words, the first quote is telling PHP to keep hands off until it finds another quote.
Notice that print is typed completely in lowercase letters, yet date has a leading uppercase letter. I did this to illustrate that PHP takes a lenient attitude toward the names of its built-in functions. Print, PRINT, and PrInT are all valid calls to the same function. However, for the sake of readability, it is customary to write PHP's built-in functions using lowercase letters only.


1.7 Saving Data for Later

Often it is necessary to save information for later use. PHP, like most programming languages, offers the concept of variables. Variables give a name to the information you want to save and manipulate. Listing 1.8 expands on our example by using variables (see Figure 1.2).


The first block of PHP code puts values into some variables. The four variables are YourName, Today, CostOfLunch, and DaysBuyingLunch. PHP knows they are variables because they are preceded by a dollar sign ($). The first time you use a variable in a PHP script, some memory is set aside to store the information you wish to save. You don't need to tell PHP what kind of information you expect to be saved in the variable; PHP can figure this out on its own.
The script first puts a character string into the variable YourName. As I noted earlier, PHP knows it's textual data because I put quotes around it. Likewise, I put today's date into a variable named Today. In this case PHP knows to put text into the variable because the date function returns text. This type of data is referred to as a string, which is shorthand for character string. A character is a single letter, number, or any other mark you make by typing a single key on your keyboard.
Notice that there is an equal sign (=) separating the variable and the value you put into it. This is the assignment operator. Everything to its right is put into a variable named to its left.
Listing 1.8 Assigning values to variables
    $YourName = "Leon";
    $Today = date("l F d, Y");
    $CostOfLunch = 3.50;
    $DaysBuyingLunch = 4;
?>


Listing 1-8


Today's Date:
    /*
    ** print today's date
    */
    print("

$Today

\n"); /* ** print message about lunch cost */ print("$YourName, you will be out "); print($CostOfLunch * $DaysBuyingLunch); print(" dollars this week. \n"); ?>
The third and fourth assignments are putting numerical data into variables. The value 3.5 is a floating-point, or fractional, number. PHP calls this type a double, showing some of its C heritage. The value 4 in the next assignment is an integer, or whole number.
After printing some HTML code, another PHP code block is opened. First the script prints today's date as a level-three header. Notice that the script passes some new types of information to the print function. You can give string literals or string variables to print, and they will be sent to the browser.
When it comes to variables, PHP is not so lenient with case. Today and today are two different variables. Since PHP doesn't require you to declare variables before you use them, you can accidentally type today when you mean Today and no error will be generated by default. If variables are unexpectedly empty, check your case. You can also catch these sorts of errors by configuring PHP to warn you of uninitialized variables. See Chapter 15's description of error reporting.
The script next prints Leon, you will be out 14 dollars this week. The line that prints the total has to calculate it with multiplication, using the * operator.

1.8 Receiving User Input

Manipulating variables that you set within your script is somewhat interesting, but hardly anything to rave about. Scripts become much more useful when they use input from the user. When you call PHP from an HTML form, the form fields are turned into variables. Listing 1.9 is a form that calls Listing 1.10, a further modification of our example script.
Listing 1.9 HTML form for lunch information


Listing 1-9

Your name: Cost of a lunch: Days buying lunch:
Listing 1.9 is a standard HTML form. If you have dealt at all with CGIs, it will look familiar. There are three form fields that match up with the variables from our previous example. Instead of simply putting data into the variables, we will provide a form and use the information the user types. When the user presses the submit button, the script named in the ACTION attribute will receive the three form fields, and PHP will convert them into variables (see Figure 1.3).
Listing 1.10 Computing the cost of lunch from a form
   $Today = date("l F d, Y");
?>


Listing 1-10


Today's date:
    /*
    ** print today's date
    */
    print("

$Today

\n"); /* ** print message about lunch cost */ print($_REQUEST['YourName'] . ", you will be out "); print($_REQUEST['CostOfLunch'] * $_REQUEST['DaysBuyingLunch']); print(" dollars this week. \n"); ?>


Notice that in the first segment of the PHP script, I have eliminated the lines setting the variables, except for today's date. See how instead of using $CostOfLunch, I used $_REQUEST['CostOfLunch']? PHP collects all the variables sent by forms and cookies into a collection called _REQUEST. The technical name for this type of data is array, the subject of Chapter 5.
Try experimenting with the scripts by entering nonsense in the form fields. One thing you should notice is that if you put words where the script expects numbers, PHP seems to just assign them values of zero. The variables are set with a text string, and when the script tries to treat it as a number, PHP does its best to convert the information. Entering 10 Little Indians for the cost of lunch will be interpreted as 10.

1.9 Choosing Between Alternatives

PHP allows you to test conditions and execute certain code based on the result of the test. The simplest form of this is the if statement. Listing 1.11 shows how you can customize the content of a page based on the value of a variable.


The Today variable is set with the name of today's weekday. The if statement evaluates the expression inside the parentheses as either true or false. The == operator compares the left side to the right side. If Today contains the word Friday, the block of code surrounded by curly braces ({ and }) is executed. In all other cases the block of code associated with the else statement is executed.
Listing 1.11 Conditional daily message


Listing 1-11

/* ** Get today's day of the week */ $Today = date("l"); if($Today == "Friday") { print("Thank goodness it's Friday!"); } else { print("Today is $Today."); } ?>



1.10 Repeating Code

The last type of functionality in this brief introduction is looping. Looping allows you to repeat the execution of code. Listing 1.12 is an example of a for loop. The for statement expects three parameters separated by semicolons. The first parameter is executed once before the loop begins. It usually initializes a variable. The second parameter makes a test. This is usually a test against the variable named in the first parameter. The third parameter is executed every time the end of the loop is reache.
Listing 1.12 Today's daily affirmation


Listing 1-12

Today's Daily Affirmation

Repeat three times: for($count = 1; $count <= 3; $count++) { print("$count I'm good enough, "); print("I'm smart enough, "); print("and, doggone it, people like me! \n"); } ?>


The for loop in Listing 1.12 will execute three times. The initialization code sets the variable count to be one. Then the testing code compares the value of count to three. Since one is less than or equal to three, the code inside the loop executes. Notice that the script prints the value of count. When you run this script, you will find that count will progress from one to three. The reason is that the third part of the for statement is adding one to count each time through the loop. The ++ operator increments the variable immediately to its left.
The first time through the loop, count is one, not two. This is because the increment of count doesn't occur until we reach the closing curly brace. After the third time through the loop, count will be incremented to four, but at that point four will not be less than or equal to three, so the loop will end. Execution continues at the command following the loop code block.


0 comments:

Post a Comment

Thank you for reading this article. Do you have suggestions or how to do better, please leave a few words to share with everyone. Please note you, these comments are not calculated suggestions or help build each other progress will be deleted without notice. In addition, you necessarily have a Google account, or networks are listed below (including OpenID) will be a review. The comment is absolutely not carry political content, reactionary, chửi pool, for that reason, you must have one of the accounts in question.Sorry for the inconvenience. Wish love your home more and more visitors. Content type in Vietnamese will be marked with clear easy to account for more than sympathy.

Donation

Search By Your Customize

Custom Search

Subscription

Enter your email address:

Delivered by FeedBurner

Labels

Sponsored Links

Asd by any program
Free Website Hosting affiliate_link adf.ly - shorten links and earn money!