You are on page 1of 184

Designing Web Applications Using PHP

Disclaimer
The copyright of the content used in the courseware will remain with principle Company

TABLE OF CONTENT
CHAPTER INTRODUCTION TO HTML INTRODUCTION TO CASCADING STYLE SHEET INTRODUCTION TO PHP VARIABLES AND INPUT OUTPUT OPERATORS SELECTION CONSTRUCT ITERATION CONSTRUCT STRINGS ARRAYS FUNCTION OBJECT ORIENTED PROGRAMMING IN PHP FILE HANDLING MYSQL ADMINISTRATION DATABASE HANDLING WITH PHP COOKIES & SESSION MANAGEMENT PHP WITH FORMS AND USER INPUT PHP EXCEPTION HANDLING PHP FILTER CREATING LIBRARIES AJAX INTRODUCTION PHP.INI CONFIGURATION PAGE NO 4 13 17 24 30 36 39 42 60 70 79 105 113 119 131 137 146 155 166 170 178

CHAPTER -1 Introduction TO HTML

A brief history of HTML


HTML was originally developed by Tim Berners-Lee while at CERN, and popularized by the Mosaicbrowser developed at NCSA. During the course of the 1990s it has blossomed with the explosive growth of the Web. During this time, HTML has been extended in a number of ways. The Web depends on Web page authors and vendors sharing the same conventions for HTML. This has motivated joint work on specifications for HTML.

A brief history of SGML


HTML is an SGML application conforming to International Standard ISO 8879 -- Standard Generalized Markup Language SGML (defined in [ISO8879]). SGML provides a means for defining markup languages. The basic idea is to annotate the text of a document with markup tags that provide additional information about the documents structure and interpretation. A complete discussion of SGMLparsing, e.g. the mapping of a sequence of characters to a sequence of tags and data, is left to the SGML standard .

An SGML application consists of several parts:


1. The SGML declaration. The SGML declaration specifies which characters and delimiters may appear in the application. 2. The document type definition (DTD). The DTD defines the syntax of markup constructs. The DTD may include additional definitions such as numeric and named character entities. 3. A specification that describes the semantics to be ascribed to the markup. This specification also imposes syntax restrictions that cannot be expressed within the DTD. 4. Document instances containing data (contents) and markup. Each instance contains a reference to the DTD to be used to interpret it.

HTML syntax
In this section, we discuss the syntax of HTML elements, attributes, and comments.

Entities
Character entity references are numeric or symbolic names for characters that may be included in an HTML document. They are useful when your authoring tools make it difficult or impossible to enter a character you may not enter often. You will see character entities throughout this document; they begin with a "&" sign and end with a semi-colon (;). Some examples include: "&lt;" represents the < sign. "&gt;" represents the > sign. "&quot; represents the " mark. &#229; (in decimal) represents the letter "a" with a small circle above it. &#1048; (in decimal) represents the Cyrillic capital letter "I". &#x6C34; (in hexadecimal) represents to the Chinese character for water.

Elements
An SGML application defines elements that represent structures or desired behavior. An element typically consists of three parts: a start tag, content, and an end tag. An elements start tag is written <element-name>, where element-name is the name of the element. An elements end tag is written with a slash before the element name: </element-name>. For example, <pre>The content of the PRE element is preformatted text.</pre>

Attributes
Elements may have associated properties, called attributes, to which authors assign values. Attribute/value pairs appear before the final ">" of an elements start tag. Any number of (legal) attribute value pairs, separated by spaces, may appear in an elements start tag. They may appear in any order.

HTML comments
HTML comments have the following syntax: <!-- this is a comment --> <!-- and so is this one, which occupies more than one line --> White space is not permitted between the markup declaration open delimiter("<!") and the comment open delimiter ("--"), but is permitted between the comment close delimiter ("--") and the markup declaration close delimiter (">"). A common error is to include a string of hyphens ("-5

-") within a comment. Authors should avoid putting two or more adjacent hyphens inside comments.

List of Elements
<A attribute=></A> Anchor is a container element that is use to create a Hyperlink.

Attributes HREF HREF TARGET = Specifies the URL of the document to be linked To. = Specifies the name of the anchor you are Created = Specifies which window the link will be loaded into.The target can be a name of a frame that you specified in the FRAME tag.

<LI attribute> Used to mark text as a list item in any of the following list type <OL> or <UL> <OL Attribute></OL> Puts the enclosed items marked with <LI>, in a numbered list. Attributes TYPE = Specifies the type of numbering to be used to for labeling items. Possible values are : A,a,I,I,1. START = Specifies the starting value for the numbering sequence.

<UL attributes></UL> Puts the enclosed items marked with <LI>, in a bulleted list.

Attributes TYPE = Specifies the type of bullet used to label the item Possible values are : DISC,CIRCLE,SQUARE. <FRAMESET attributes=></FRAMESET> Define the set of frames that will make up the page.The FRAMES and NOFRAMES tags go inside this. The FRAMESET tag is used instead of the BODY tag.

Attributes BORDER COLS = Specifies the width (in pixels) of the border drawn around the frame. =. Creates the frames as columns and specifies the width of each column. ROWS = Creates the frames as rows and specifies the width of each row. Possible values are yes, no, and auto. <FRAME attribute1=> Define the source document that should be placed within a frameset. Attributes BORDER NAME = Specifies the width (in pixel) of the border drawn around the frame. = Defines a name for frame. yes, no, and auto. SRC = Specifies the source file for frame. SCROLLING = Determines whether or not scroll bars are displayed on all the frames.

SCROLLING = Specifies if the frame with scrollbar or not. Possible values are

<TABLE attribute1=></Table> Creates a table that can include any number of row and column.

Attributes BORDER = Specifies the width of the border around the table. If set to 0, there will be no border. BACKGROUND BGCOLOR = Specifies the image that is to be tiled as the background image . = Specifies the background color of the table. = Specifies the width of the table on the page. = Specifies the amount of the space between the cell in the table = Specifies the amount the space between the edges of the cell and the text inside. <CAPTION attribute1=></CAPTION> Specifies the caption of the table.

BORDERCOLOR = Specifies the border color of the table. WIDTH CELLSPACING CELLPADDING

Attributes ALIGN = Specifies the position of the caption. Possible values are LEFT,RIGHT,BOTTOM, or TOP <TR Attributes =</TR> Specifies a table row. It can enclose the table heading and table data. Attributes ALIGN = Specifies the horizontal alignment of the row contents. Possible values are LEF, RIGHT and CENTER. ROWSPAN = Specifies the number of rows the cell will span.

<TH Attribute1=...></TH>
Specifies heading to a cell

Attributes
ALIGN = Specifies the horizontal alignment of the cell contents possible values are LEFT, RIGHT and CENTER.

<TD Attribute1=>
TR Thease go inside the tags and they define the data in a cell. End tag may be used.

Attributes
BACKGROUND = Specifies the address of the image to be tiled as background BGCOLOR ALIGN COLLSPAN WIDTH HEIGHT = Specifies the background color for the individual cell . = Specifies the horizontal alignment of the cell contents . Possible values are LEFT, RIGHT and CENTER. = Specifies the number of columns the cell will span . = Specifies the width of the cell . = Specifies the height of the cell .

<FORM Attribute1=>.</Form> Specifies a form. Form can be used to send user input to the server in the form of NAME/VALUE pair. Attributes ACTION = Specifies the address to be used in carrying out the action of the form, usually the address of the CGI file. You can also specifies a mailto address to have the contents of the form emailed to you
8

instead of passed to the server. = Post and get method are both used for sending data from the form to the backend. The only difference being POST sends the data independent of the URL of the target whereas GET Send along with the URL itself. = Specifies which window the result of the form will be loaded. The target can be the name of a frame that you specify in the FRAME tag or one of the following <INPUT Attribute1=> Specifies a control or input are for a form which a NAME/VALUE pair will be returned to the server. Attributes ALIGN = If the TYPE is IMAGE then this Specifies the alignment of the surrounding text with the image possible values are TOP,MIDDLE, BOTTOM, LEFT, or RIGHT. = Use this attribute with RADIO of CHECKBOX, and it will be preSelected when the form loads. MAXLENGTH = Specifies the maximum number of characters that can be entered in a text input area. NAME = . Specifies the name of the control or input area.0 (part of the NAME/VALUE pair). SIZE = . Specifies the size of the text entry area that is displayed by the browser. = . If the TYPE is image, then this Specifies the address of the image to be used. TYPE = Specifies the type of control being use. Possible Types

METHOD

TARGET

CHECKED

SRC

CHECKBOX
Creates a checkbox. If the user checks it, the corresponding name/value pair is sent to the server.

IMAGE
9

Like the SUBMIT Type, you can have the form sent immediately when the user clicks on an image. Along with the normal information ,when a form is submitted by clicking on an image, the coordinates of the clicked point (measured in pixels from the upper-left corner of the image) are also sent. The X-coordinates is submitted with a x appended to the name and the y-coordinates has a y appended to the name.

PASSWORD
Creates a single line entry text box just like the text type, however, user input is not echoed on the screen.

RADIO Creates a radio list of alternatives of which only one can be selected. Each alternative must have the same name, but different values can be assigned to each.

RESET Creates a 3-D button that clears the entire form to original values when clicked. You can Give the button a name by using the VALUE attribute.

SUBMIT Creates a 3-D button that submits the form when clicked. You can give the button a name by using the VALUE attribute. TEXT Creates a single line text entry box. You can specifies the size of the text box by using the size attributes . <SELECT Attribute1= ></SELECT> Creates a drop-down list of items. The OPTION tag placed inside opening and closing SELECT tags define the list items.

Attributes MULTIPLE Specifies that multiple items may be selected. NAME = Specifies the name of the list. SIZE = Specifies how many items should be visible.

10

<OPTION value=> item Specifies an item in the drop down list. Placed within the opening and closing select tags. Any text following the option tag is what the user will see in the list.

Attributes VALUE = Specifies the value to be returned(part of the NAME/VALUE pair).

SELECTED This item will be highlighted when the page loads.

<TEXTAREA Attribute1=></TEXTAREA> Creates a multi-lined text entry box. Any text placed in between the tags is used as the default text string that is displayed when the page is loaded.

Attributes COLS ROWS NAME = Specifies how wide the text box will be. = Specifies how high the text box will be. = Specifies the name of the text box for use by the program that is processing the form. WRAP = Specifies how text will wrap. Possible values are HARD, SOFT or NONE. <B></B> Bold faces the enclosed text. <BIG></BIG> Makes the enclosed text one size larger . <BLINK></BLINK> Makes the enclosed text blink continually. <BR> Inserts a line break. <CENTER></CENTER> Center the enclosed elements. This tag will center everything including images, text, Tables , forms, etc. <DIV ALIGN=></DIV> Specifies the alignment of the enclosed elements. Can be used to divide a document into sections that are aligned differently. In future browsers, more attributes will probably be supported.

Attributes
11

ALIGN

Sets the alignment of the division. Possible values are Center, right, or left.

<FONT attribute=>..</Font> Sets the font properties for the enclosed text. Attributes SIZE = Sets the size of the font to any number between 1 and 7 with 3 being default. Relative sizes also words e.g. SIZE=+2 COLOR FACE = = Specifies the color of the font. Specifies the face of the font. A list can be defined (separated by commas) and the browser will use the first one available of that computer. <HR attirbute1=> Inserts a horizontal line Attributes SIZE COLOR WIDTH ALIGN <l>..</I> The enclosed text is ITALIC. <U>..</U> The enclosed text is Underline <P attribute>..</P> Designates the enclosed text as a plain paragraph . The end tag is optional Attributes ALIGN <PRE>..</PRE> Displays text in fixed-width type without collapsing spaces. <SUP>..</SUP> Renders the enclosed text in superscript . <SUB>..</SUB> Renders the enclosed text in subscript . = . Specifies the alignment for the paragraph. Possible values are center, right, left . = Specifies the thickness of the line. = Specifies the color of the line . =. Specifies the length of the line as percentage of the screen e.g. WIDTH=90% = Specifies the alignment of the file. RIGHT, LEFT or CENTER.

NOSHADE The line is drawn Solid.

12

CHAPTER -2

Introduction To Cascading Style Sheet


An introduction to Cascading Style Sheets
CSS is the acronym for: Cascading Style Sheets. CSS is an extension to basic HTML that allows you to style your web pages

STYLE SHEETS Details With HTML


TEXT PROPERTIES PROPERTY Text-transform DESCRIPTION The case of the text is set VALUES capitalize uppercase lowercase none Text-align Aligns the contents horizontally across this page Left Right Center Justify Text-indent Indents the text in XX units the paragraph by the specified number of characters. X Line-height Specifies the height of the text along with the line space above the line and below the line Word-spacing Specifies the space between the words Letter-spacing Specifies the space between the characters Text-decoration Specifies the formatting for the text. Underline overline line-through Blink None
13

EXAMPLES P{text-transform: capitalize H1{text-transform: uppercase} H4{ text align : center}

XX units

P{text-height: 7em}

XX units

P{line-height: 12pt}

XX units

P{word-spacing:4pt}

XX units

P{letter-spacing:1pt}

H1{text-decoration: underline}

FONT PROPERTIES PROPERTY Font-family DESCRIPTION VALUES EXAMPLES P{font-family : Comic Sans MS} H2{font-family:Comic MS, font- style:italic}

Specifies the name of the Family Name font to be applied

Font-style

Specifies the style of the Normal text to be displayed Italic Oblique

Font-weight

Specifies the weight of Lighter boldness of the font . Normal Bold Bolder 100-900

P{font-weight:bold}

Font-Size

Specifies the size of the font

XX units

P{font-size:12pt}

Classification Properties
PROPERTY List-style-type DESCRIPTION Specifies the symbol that appears in front VALUES Disc Circle Square of a list item. Decimal Lowerroman Upperroman Alpha Upper-alpha List-style- image Specifies the Image to Server as a bullet for list items. url(URL name) image:url(../images/smiley.gif} EXAMPLES Ul{list-style-type:upeer-alpha}

14

List-styleposition

Specifies the position of Inside the bullet that appears in the list item outside

Ul{list-style-position: outside} ul { list-style-position: inside}

Color And Background Properties


Property Color Description Specifies Color Hex name value rgb (R%,G%,B%) rgb(R , G, B) Background- color Specifies the background color Color name hex value rgb(R%,G%,B%) rgb(R,G,B) Backgroundimage Specifies background image. Background- repeat Specifies background how Repeat repeat-x Body {backgroundthe url(URLname) Body {background-image: url(..image/sand.gif)} Value Example P {color: red} P{color:#fffffff} p {color:10%,20%,20%} P{color:255,200,0} H1 {background-color: green}

image:url(..images/sand.gif);

image will be repeat-y placed. Backgroundattachment no-repeat Body {background- image: url(../images/sand.gif); background-attachment: fixed}

Specifies if the Scroll image is fixed Fixed or will it also move.

Backgroundposition

Specifies

the Vertical %

Body{background-image: url(images/sand.gif); background position:center}

position of the horiZontal % background image. top,center bottom,left, right

15

Placement Properties
PROPERTIES Margi-top DESCRIPTION VALUE EXAMPLE Div {margin-top: 2em} Specifies the position of XX units % auto the text in the page. Margin-bottom Specifies the bottom margin of the text. Margin-left Specifies the left margin of the text. Margin-right Specifies the right margin of the text. Border-style Set the style of the elements border Dotted solid double groove ridge inset outset Border-color Sets the color of the elements border. Color name hex value rgb(R%, G%,B%) rgb(R,G,B) Border border-top border-bottom border-left border-right Sets the width color, and style of the border simultaneously. Width value style value color value Table {border: thick double red} Table {border {border-top: thin dashed red } Table {border-color: red} Table {border-style: dashed} XX units % auto Div {margin-left: 1em} XX units % auto Div {margin-left : 6em} XX units % auto Div {margin-bottom: 10%}

16

CHAPTER- 3 Introduction TO PHP What is PHP?


PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Example 1.1. An introductory example <html> <head> <title>My First PHP Application</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?> </body> </html>

What can PHP do?


Anything. PHP is mainly focused on server-side scripting, so you can do anything other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used: Server-side scripting :
This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.

17

Command line scripting :


You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on unix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

Writing desktop applications :


PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit its own website. PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor. So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code.

What do I need?
In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but if your host does not, consider reading the PHP Links section for resources on finding PHP enabled web hosts. Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as Apache, and of course PHP. You will most likely want to install a database as well, such as MySQL.
18

You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). In case you have problems with installing PHP yourself, we would suggest you ask your questions on our installation mailing list. If you choose to go on the simpler route, then locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find rpmfind and PBone helpful for locating RPMs. You may also want to visit apt-get to find packages for Debian.

History of PHP PHP/FI


PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code. PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent. By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project. PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.

PHP 3
PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found
19

PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI's existing userbase, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted. One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax. The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor. By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet. PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.

PHP 4
By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi ), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

20

Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet. PHP's development team includes dozens of developers, as well as dozens others working on PHPrelated projects such as PEAR and the documentation project.

PHP 5
PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.

Your first PHP-enabled page


Create a file named hello.php and put it in your web server's root directory ( DOCUMENT_ROOT ) with the following content: Example : Our first PHP script: hello.php <html> <head> <title>PHP Test</title> </head> <body> <?php echo '<p>Hello World</p>'; ?> </body> </html>

Use your browser to access the file with your web server's URL, ending with the "/hello.php" file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser: <html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p>
21

</body> </html>

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things. If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many PHP support options. The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?> . You may jump in and out of PHP mode in an HTML file like this anywhere you want.

For more details, read the manual section on the basic PHP syntax. A Note on Line Feeds:
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

A Note on Text Editors:


There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
22

A Note on Word Processors:


Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

A Note on Windows Notepad:


If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. " hello.php "). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information

23

CHAPTER- 4

Variables And Input Output


Variables Variables in PHP are quite different from compiled languages such as C and Java. This is because their weakly typed nature, which in short means you doesnt need to declare variables before using them, you dont need to declare their type and, as a result, a variable can change the type of its value as much as you want. Variables in PHP are preceded with a $ sign, and similar to most modern languages, they can start with a letter (A-Za-z) or (underscore) and can then contain as many alphanumeric characters and underscores as you like. Examples of legal variable names $count $_Obj $A123 Example of illegal variable names $123 $*ABC As previously mentioned,you dont need to declare variables or their type before using them in PHP. The following code example uses variables: $PI = 3.14; $radius = 5; $circumference = $PI * 2 * $radius;

You can see that none of the variables are declared before they are used.Also, the fact that $PI is a floating-point number, and $radius (an integer) is not declared before they are initialized. PHP does not support global variables like many other programming languages (except for some special predefined variables, which we discuss later). Variables are local to their scope, and if created in a function, they are only available for the lifetime of the function. Variables that are created in the main script (not within a function) arent global variables; you cannot see.

Indirect References to Variables


An extremely useful feature of PHP is that you can access variables by using indirect references, or to put it simply, you can create and access variables byname at runtime.

24

Consider the following example: $name = "John"; $$name = "Registered user"; print $John; This code results in the printing of "Registered user." The bold line uses an additional $ to access the variable with name specified by the value of $name("John") and changing its value to "Registered user". Therefore, a variable called $John is created. You can use as many levels of indirections as you want by adding additional $signs in front of a variable.

Managing Variables
Three language constructs are used to manage variables. They enable you to check if certain variables exist, remove variables, and check variables truth values. Isset : Determine whether a variable is set 1. Cheack ing an variable if (isset($first_name)) { print '$first_name is set'; }

2. Checking an array element if (isset($arr["offset"])) { ... }

3. Checking an object property if (isset($obj->property)) { ... } Unset :Unset a given variable 1. destroy a single variable <?php unset($var); ?> 2. destroy a single element of an array <?php unset($arr['quux']); ?> 3. destroy more than one variable <?php unset($foo1, $foo2, $foo3); ?> empty : Determine whether a variable is empty

25

Superglobals
PHP does not support global variables (variables that can automatically be accessed from any scope). However, certain special internal variables behave like global variables similar to other languages. These variables are called superglobals and are predefined by PHP for you to use. Some examples of these superglobals are $_GET[ ] An array that includes all the GET variables that PHP received from the client browser. $_POST[ ] An array that includes all the POST variables that PHP received from the client browser. $_COOKIE[ ] An array that includes all the cookies that PHP received from the client browser. $_ENV[ ] An array with the environment variables. $_SERVER[ ] An array with the values of the web-server variables.

Basic Data Types


Eight different data types exist in PHP, five of which are scalar and each of the remaining three has its own uniqueness. The previously discussed variables can contain values of any of these data types without explicitly declaring their type. The variable behaves according to the data type it contains. These Data Types are
1. 2. 3. 4. 5. 6. 7. 8.

Booleans Integers Floating point numbers Strings Arrays Objects Resources NULL

Booleans
This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE .

Note: The boolean type was introduced in PHP 4.


To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive. <?php $foo = True; // assign the value TRUE to $foo ?>
26

Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure. <?php // == is an operator which test equality and returns a boolean if ($action == "show_version") { echo "The version is 1.23"; } // this is not necessary... if ($show_separators == TRUE) { echo "<hr><br>"; } // ...because you can simply type if ($show_separators) { echo "<hr><br>"; } ?>

Integers
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. Integers can be specified in decimal (10-based), hexadecimal (16-based) octal (8-based) notation optionally preceded by a sign (- or +).If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x . Example Integer literals <?php $a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) ?>
27

Floating point numbers


Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes: <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?>

Strings
A string is series of characters.

Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys.

Objects
To create a new object, use the new statement to instantiate a class .

Resources
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.

Null
The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL. A variable is considered to be NULL if it has been assigned the constant NULL. it has not been set to any value yet. it has been unset(). Syntax: There is only one value of type NULL, and that is the case-insensitive keyword NULL. <?php $var = NULL; ?> Note: The null type was introduced in PHP 4. 0

28

Basic Output Construct


Echo() and print() are basic output function used in PHP. Both Have little Difference Which is Echo Example Echo This is my Printing line . I will Learn It ; Or Echo(This is my Printing Line); Note: Difference Is that Second Version of echo cant Except More than One parameters. Print Example print(This is my printing line); Or print(This is my printing line . Parse Error);

Difference Between Echo And Print ()


Unlike echo, print can accept only one argument. Unlike ehco , print return a value, which represents whether the print statement succeeded.

29

CHAPTER- 5

Operators
Unary Operator Incrementing/Decrementing Operators
PHP supports C-style pre- and post-increment and decrement operators. Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1 .

Increment/decrement Operators
Example ++$a $a++ --$a $a-Name Pre-increment Post-increment Pre-decrement Post-decrement Effect Increments $a by one, then returns $a. Returns $a, then increments $a by one. Decrements $a by one, then returns $a. Returns $a, then decrements $a by one.

Here's a simple example script: <?php echo "<h3>Post increment</h3>"; $a = 5; echo "Should be 5: " . $a++ . "<br />"; echo "Should be 6: " . $a . "<br />"; echo "<h3>Pre increment</h3>"; $a = 5; echo "Should be 6: " . ++$a . "<br />"; echo "Should be 6: " . $a . "<br />"; echo "<h3>Post decrement</h3>"; $a = 5; echo "Should be 5: " . $a-- . "<br />"; echo "Should be 4: " . $a . "<br />"; echo "<h3>Pre decrement</h3>"; $a = 5; echo "Should be 4: " . --$a . "<br />"; echo "Should be 4: " . $a . "<br />"; ?>
30

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

Example . Arithmetic Operations on Character Variables


<?php $i = 'W'; for ($n=0; $n<6; $n++) { echo ++$i . "<br/>"; } ?> The above example will output: X Y Z AA AB AC

Binary Operator Binary operators are used on two operands:


2+3 14 * 3.1415 $i 1 These examples are also simple examples of expressions. PHP can only perform binary operations on two operands that have the same type. However, if the two operands have different types, PHP automatically converts one of them to the others type, according to the following rules (unless stated differently, such as in the concatenation operator). Type of One of the Operands Integer Type of the Other Operand Floating point Conversion Performed The integer operand is converted to a floating point number. Integer String The string is converted to a number. If the converted. strings
31

type is real, the integer operand is converted to a real as well. Real String The sting is converted to a real.

Booleans, nulls, and resources behave like integers, and they convert in the following manner: Boolean: False = 0, True = 1 Null = 0 Resource = The resources # (id)

Binary Operators
Numeric Operators All the binary operators (except for the concatenation operator) work only on numeric operands. If one or both of the operand share strings, Booleans, nulls, or resources, they are automatically converted to their numeric equivalents before the calculation is performed (according to the previous table).

Operator + *

Name Addition Subtraction Multiplcation

Value The sum of the two operands. The difference between the two operands The product of the two operands.

Concatenation Operator (.)


The concatenation operator concatenate two strings. This operator works only on strings; thus, any non-string operand is first converted to one. The following example would print out "The year is 2011": <?php $year = 2011; print "The year is " . $year; ?>

The integer $year is internally converted to the string "2011" before it is concatenated with the strings prefix, "The year is".

32

Assignment Operators
Assignment Operators enable you to write a value to a variable. The first Operand (the one on the left of the assignment operator or l value) must be a variable . The value of an assignment is the final value assigned to the variable. For example: The expression $var = 5 has the value 5 (and assigns 5 to $var). In addition to the regular assignment operator =, several other assignment operators are composites of an operator followed by an equal sign. These composite operators apply the operator taking the variable on the left as the first operand and the value on the right (the r value) as the second operand, and assign the result of the operation to the variable on the left.

For example:
$counter += 2; // This is identical to $counter = $counter + 2; $offset *= $counter ; // This is identical to $offset = $offset * $counter; The following list show the valid composite assignment operators: +=, -=, *=, /=, %=,

By-Reference Assignment Operator


PHP enables you to create variables as aliases for other variables. You can achieve this by using the by-reference assignment operator =&. After a variable aliases another variable, changes to either one of them affects the other.

For example:
$name = "Judy"; $name_alias =& $name; $name_alias = "Jonathan"; print $name;

The result of this example is


Jonathan When returning a variable by-reference from a function (covered later in this book), you also need to use the assign by-reference operator to assign the returned variable to a variable:

$retval =& func_that_returns_by_reference();

Comparison Operators
Comparison operators, as their name implies, allow you to compare two values. You may
33

also be interested in viewing the type comparison tables, as they show examples of various type related comparisons. Example $a == $b $a === $b Equal Identical Name Result TRUE if $a is equal to $b. TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4) $a != $b $a <> $b $a !== $b Not equal Not equal Not identical TRUE if $a is not equal to $b. TRUE if $a is not equal to $b. TRUE if $a is not equal to $b, or they are not of the Same type. (introduced in PHP 4) $a < $b $a > $b $a <= $b $a >= $b Less than Greater than Less than or equal to Greater than or equal to TRUE if $a is strictly less than $b. TRUE if $a is strictly greater than $b. TRUE if $a is less than or equal to $b. TRUE if $a is greater than or equal to $b.

Comparison Operators
If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement. <?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true var_dump("1" == "1e0"); // 1 == 1 -> true switch ("a") { case 0: echo "0"; break; case "a": echo "a"; break; } ?> // never reached because "a" is already matched with 0

34

Logical Operators Example $a and $b $a or $b $a xor $b ! $a $a && $b $a || $b And Or Xor Not And Or Name Result TRUE if both $a and $b are TRUE TRUE if either $a or $b is TRUE TRUE if either $a or $b is TRUE, but not both. TRUE if $a is not TRUE. TRUE if both $a and $b are TRUE TRUE if either $a or $b is TRUE

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.) Example: Logical operators illustrated <?php // foo() will never get called as those operators are short-circuit $a = (false && foo()); $b = (true || foo()); $c = (false and foo()); $d = (true or foo()); // "||" has a greater precedence than "or"

$e = false || true; // $e will be assigned to (false || true) which is true $f = false or true; // $f will be assigned to false var_dump($e, $f);

// "&&" has a greater precedence than "and" $g = true && false; // $g will be assigned to (true && false) which is false $h = true and false; // $h will be assigned to true var_dump($g, $h); ?>

35

CHAPTER- 6

Selection Constructs
IF Statements If statements are the most common conditional constructs, and they exist in most programming languages. The expression in the if statement is referred to as the

Truth Expression. If the truth expression evaluates to true, the statement or statement list following it are executed; otherwise, theyre not. You can add an else branch to an if tatement to execute code only if all the truth expressions in the if statement evaluated to false: <?php if ($var >= 50) { print '$var is in range'; } else { print '$var is invalid'; } ?> Notice the braces that delimit the statements following if and else, which make these statements a statement block. In this particular case, you can omit the braces because both blocks contain only one statement in them It is good practice to write these braces even if theyre not syntactically required. Doing so improves readability, and its easier to add more statements to the if block later (for example, during debugging). The elseif construct can be used to conduct a series of conditional checks and only execute the code following the first condition that is met. For example: if ($num < 0) { print '$num is negative'; } elseif ($num == 0)
36

{ print '$num is zero'; } elseif ($num > 0) { print '$num is positive'; }

Statement List
if ( expr ) statement elseif ( expr ) statement elseif ( expr ) statement ... else statement

Switch Statements
You can use the switch construct to elegantly replace certain lengthy if/ elseif constructs. It is given an expression and compares it to all possible case expressions listed in its body. When theres a successful match, the following code is executed, ignoring any further case lines (execution does not stop when the next case is reached). The match is done internally using the regular equality operator (==), not the identical operator (===). You can use the break statement to end execution and skip to the code following the switch construct.

Statement switch ( expr ) { case expr : statement list case expr : statement list
37

... default: statement list }

Usually, break statements appear at the end of a case statement list, although it is not mandatory. If no case expression is met and the switch construct contains default, the default statement list is executed. Note that the default case must appear last in the list of cases or not appear at all:

Example
switch ($answer) { case 'y': case 'Y': print "The answer was yes\n"; break; case 'n': case 'N': print "The answer was no\n"; break; default: print "Error: $answer is not a valid answer\n"; break; }

38

CHAPTER- 7

Iteration Constructs
They are used to manipulate same set of instruction more than once they are also known as loops. Following are the loops provided by PHP .

While Loop
While loops are the simplest kind of loops. In the beginning of each iteration, the whiles truth expression is evaluated. If it evaluates to true, the loop keeps on running and the statements inside it are executed. If it evaluates to false, the loop ends and the statement(s) inside the loop is skipped.For example, heres one possible implementation of factorial, using a while loop (assuming $n contains the number for which we want to calculate the factorial): Example: $result = 1; while ($n > 0) { $result *= $n--; } print "The result is $result";

Do...While Loop
do statement while ( expr ); The do...while loop is similar to the previous while loop, except that the truth expression is checked at the end of each iteration instead of at the beginning. This means that the loop always runs at least once. do...while loops are often used as an elegant solution for easily breaking out of a code block if a certain condition is met. Consider the following example:

do { statement list if ($error) {


39

break; } statement list } while (false);

Because do...while loops always iterate at least one time, the statements inside the loop are executed once, and only once. The truth expression is always false. However, inside the loop body, you can use the break statement to stop the execution of the statements at any point, which is convenient. Of course, do...while loops are also often used for regular iterating purposes.

For Loop
PHP provides C-style for loops. The for loop accepts three arguments: for (start_expressions; truth_expressions; increment_expressions) Most commonly, for loops are used with only one expression for each of the start,truth, and increment expressions, which would make the previous syntax table look slightly more familiar Heres an Example: for ($i = 0; $i < 10; $i++) { print "The square of $i is " . $i*$i . "\n"; } The result of running this code is The square of 0 is 0 The square of 1 is 1 ... The square of 9 is 81 Tip: PHP doesnt know how to optimize many kinds of loop invariants. For example, in the following for loop, count($array) will not be optimized to run only once. for ($i = 0; $i <= count($array); $i++) { }

It should be rewritten as
$count = count($array); for ($i = 0; $i <= $count; $i++) { ..} This ensures that you get the best performance during the execution of the loop.
40

Loop Control: Break And Continue


Sometimes, you want to terminate the execution of a loop in the middle of an iteration. For this purpose, PHP provides the break statement. If break appears alone, as in break; the innermost loop is stopped. break accepts an optional argument of the amount of nesting levels to break out of, break n ; Example break ; break expr; continue ; continue expr;

which will break from the n innermost loops (break 1; is identical to break;). n can be any valid expression. In other cases, you may want to stop the execution of a specific loop iteration and begin executing the next one. Complimentary to break, continue provides this functionality. continue alone stops the execution of the innermost loop iteration and continues executing the next iteration of that loop. Continue n can be used to stop execution of the n innermost loop iterations. PHP goes on executing the next iteration of the outermost loop. As the switch statement also supports break, it is counted as a loop when you want to break out of a series of loops with break n.

41

CHAPTER- 8

Strings
Strings are a sequence of characters that are always internally null terminated. However, unlike some other languages, such as C, PHP does not rely on the terminating null to calculate a strings length, but remembers its length internally. This allows for easy handling of binary data in PHPfor example, creating an image on-the-fly and outputting it to the browser. The maximum length of strings varies according to the platform and C compiler, but you can expect it to support at least 2GB. Dont write programs that test this limit because youre likely to first reach your memory limit. When writing string values in your source code, you can use double quotes ("), single quotes (') or here-docs to delimit them. Each method is explained in this section.

Double Quotes Examples for double quotes: "PHP: Hypertext Pre-processor" "GET/HTTP/1.0\n" "1234567890" Strings can contain pretty much all characters. Some characters cant be written as is, however, and require special notation: An additional feature of double-quoted strings is that certain notations of variables and expressions can be embedded directly within them. Without going into specifics, here are some examples of legal strings that embed variables. The references to variables are automatically replaced with the variables values, and if the values arent strings, they are converted to their corresponding string representations (for example, the integer 123 would be first converted to thestring "123"). "The result is $result\n" "The array offset $i contains $arr[$i]"In cases, where youd like to concatenate strings with values (such as variables and expressions) and this syntax isnt sufficient, you can use the . (dot) operator to concatenate two or more strings. This operator is covered in a later section.

Single Quotes
In addition to double quotes, single quotes may also delimit strings. However, in contrast to double quotes, single quotes do not support all the double quotes escaping and variable substitution. The following table includes the only two escapings supported by single quotes : \n Newline.
42

\t Tab. \\ Backslash. \r Line feed.

Difference Between Single Quoted And Double Quoted Strings


The difference between singly and double quoted lines in how much interpretation PHP does of the characters between the quote signs before creating the string itself. If you enclose a string in single quotes, almost no interpretation will be performed; if you enclose it in double quotes, PHP will splice in the values of any variables you include, as well as make substitutions for certain special character sequences that begin with the backlash(\) character. For Example $statement=everything I say; $question_1=Do you have to take $statement so literally?<br>; $question_2=Do you have to take $statement so literally?<br>; echo $question_1; echo $question_2; You should expect to see the browser output: Do you have to take everything I say so literally? Do you have to take $statement so literally?

Interpolation With Curly Braces


We can use curly Braces within a string to differentiate a variable in a string. For Example $sport_1=Cricket; $sport _2=Soccer; $player=I will play $sport_1 and $sport_2 Both; echo $player; Will Give Output: I will play $sport_1and$sport_2 Both (Or) $player=I will play {$sport_1}and{$sport_2} Both; echo $player; Will Give Output I will play Cricket and Soccer Both
43

Concatenating Two String


(.) Dot Operation Is used To Concat to Strings. For Example $str1=This is; $str2=a book; $sentence=$str1.$str2; print($sentence); will give output on browser This is a book. Print(This is. . . a book.); Will give output This is .. a book.

Concatination And Assignment


Just as with arithmetic operators, PHP has a shothand operator(.=) that combines concatenation with assignment. The Following statement $my_string_var .= $new_addition; is exactly equivalent to: $my_string_var=$my_string_var . $new_addition;

To add new String on the left use following version $my_string_var=$new_addition . $my_string_var;

The Heredoc Syntax


PHP Offers another way to specify a string, called the heredoc syntax. This syntax turns out to be extremely useful for specifying large chunks of variable-interpolated text, because it spares you from the need to escape internal quotes. It is especially useful in creating pages that contain HTML forms. The operator in the heredoc syntax is (<<<). For Example $my_string_var=<<EOT Everything in this rather unnecessarily wordy Ramble of prose will be incorporated into the String that we are building up inevitably, inexorably, Character by character, line by line, until we reach that Blessed final line which is this one EOT;

44

Another Useful Form Example will be


Echo<<<ENDOFFORM <form method=post action={[$_ENV[PHP_SELF]}> <input type=text name=firstname value=$firstname> <input type=submit name=submit value=SUBMIT> </form> ENDOFFORM;

String Function
PHP gives you a huge variety of functions for the munching and crunching of strings. If youre ever tempted to roll your own function that reads strings character-by-character to produce a new string, pause for a moment to think whether the task might be common. If so, there is probably a built-in function that handles it.

strlen Get string length


int strlen ( string $string ) Returns the length of the given string . <?php $str = 'abcdef'; echo strlen($str); // 6 $str = ' ab cd '; echo strlen($str); // 7 ?>

strcmp Binary safe string comparison


int strcmp ( string $str1, string $str2 )
Note that this comparison is case sensitive. <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo '$var1 is equal to $var2 in a non case-insensitive string comparison'; } ?>

strcasecmp Binary safe string comparison


45

int strcasecmp ( string $str1, string $str2 )


Note that this comparison is case sensitive. <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo '$var1 is equal to $var2 in a case-insensitive string comparison'; } ?>

str_repeat Repeat a string


string str_repeat ( string $input, int $multiplier ) Returns input repeated multiplier times. <?php echo str_repeat("-=", 10); ?>

strstr Find first occurrence of a string


string strstr ( string $haystack, string $needle, bool $before_needle ) Returns part of haystack string from the first occurrence of needle to the end of haystack For Example $str1=" Computer Education"; $str2="Computer"; if(strstr($str1,$str2)) { echo "$str1 contains $str2"; } else { echo "$str1 Doesnot contains $str2"; }

Will Give Output


Computer Education Contains Computer And $str1="Info Computer Education";
46

$str2="Computer"; $str3=strstr($str1,$str2); echo "$str3"; Will give output Computer Education

str_split Convert a string to an array


array str_split ( string $string [, int $split_length] )
<?php $str = "Hello Friend"; $arr1 = str_split($str); $arr2 = str_split($str, 3); print_r($arr1); print_r($arr2); ?>

The above example will output:


Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d

Array (
47

[0] => Hel [1] => lo [2] => Fri [3] => end )

str_replace()
Replace all occurrences of the search string with the replacement string

Examples
<?php // Provides: <body text='black'> $bodytag = str_replace("%body%", "black", "<body text='%body%'>"); // Provides: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); // Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); // Use of the count parameter is available as of PHP 5.0.0 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count; // 2 // Order of replacement $str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";

$order = array("\r\n", "\n", "\r"); $replace = '<br />'; // Processes \r\n's first so they aren't converted twice. $newstr = str_replace($order, $replace, $str); // Outputs: apearpearle pear $letters = array('a', 'p'); $fruit = array('apple', 'pear'); $text = 'a p';
48

$output = str_replace($letters, $fruit, $text); echo $output; ?>

substr()
Return part of a string

Example
<?php $rest = substr("abcdef", 0, -1); // returns "abcde" $rest = substr("abcdef", 2, -1); // returns "cde" $rest = substr("abcdef", 4, -4); // returns "" $rest = substr("abcdef", -3, -1); // returns "de" ?>

strrrev()
Reversing a string with strrev() Example: <?php echo strrev("Hello world!"); // outputs "!dlrow olleH" ?>

str_shuffle()
The str_shuffle() function randomly shuffles all the characters of a string. Example: <?php echo str_shuffle("Hello World"); ?>

The output of the code above could be:


H leooWlrld

ucfirst()
Make a string's first character uppercase
49

Example
<?php $foo = 'hello world!'; $foo = ucfirst($foo); // Hello world!

$bar = 'HELLO WORLD!'; $bar = ucfirst($bar); // HELLO WORLD!

$bar = ucfirst(strtolower($bar)); // Hello world! ?>

ucwords ()
Uppercase the first character of each word in a string.Returns a string with the first character of each word in str capitalized, if that character is alphabetic. The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab). Example: <?php $foo = 'hello world!'; $foo = ucwords($foo); $bar = 'HELLO WORLD!'; $bar = ucwords($bar); // HELLO WORLD! // Hello World!

$bar = ucwords(strtolower($bar)); // Hello World! ?>

strtolower Make a string lowercase


string strtolower ( string $str ) Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C"
locale, characters such as umlaut-A () will not be converted.

Example: <?php $str = "Mary Had A Little Lamb and She LOVED It So";
50

$str = strtolower($str); echo $str; // Prints mary had a little lamb and she loved it so ?>

strtoupper Make a string uppercase


string strtoupper ( string $string ) Returns string with all alphabetic characters converted to uppercase. Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a () will not be converted. Example: <?php $str = "Mary Had A Little Lamb and She LOVED It So"; $str = strtoupper($str); echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO ?>

explode Split a string by string .


array explode ( string $delimiter, string $string [, int $limit] ) Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter . <?php // Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 // Example 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // * ?> The PHP Date() Function The PHP date() function formats a timestamp to a more readable date and time.

51

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred. Syntax date( format , timestamp )

Parameter Format Timestamp

Description Required. Specifies the format of the timestamp Optional. Specifies a timestamp. Default is the current date and time

Formats the Date


The required format parameter in the date() function specifies how to format the date/time.

Here are some characters that can be used:


d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits)

Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting: <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d") ?>

The output of the code above could be something like this: 2009/05/11 2009.05.11 2009-05-11

52

More Formates Date Function


Parameter Format D D J l (lowercase 'L') N Description Required. Specifies how to return the result: The day of the month (from 01 to 31) A textual representation of a day (three letters) The day of the month without leading zeros (1 to 31) A full textual representation of a day The ISO-8601 numeric representation of a day (1 for Monday through 7 for Sunday) S The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j) W A numeric representation of the day (0 for Sunday through 6 for Saturday) Z W F M M N T L O Y Y A A B G G H H I S The day of the year (from 0 through 365) The ISO-8601 week number of year (weeks starting on Monday) A full textual representation of a month (January through December) A numeric representation of a month (from 01 to 12) A short textual representation of a month (three letters) A numeric representation of a month, without leadingzeros (1 to 12) The number of days in the given month Whether it's a leap year (1 if it is a leap year, 0 otherwise) The ISO-8601 year number A four digit representation of a year A two digit representation of a year Lowercase am or pm Uppercase AM or PM Swatch Internet time (000 to 999) 12-hour format of an hour (1 to 12) 24-hour format of an hour (0 to 23) 12-hour format of an hour (01 to 12) 24-hour format of an hour (00 to 23 Minutes with leading zeros (00 to 59) Seconds, with leading zeros (00 to 59)
53

E I (capital i)

The timezone identifier (Examples: UTC, Atlantic/Azores) Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)

O T Z

Difference to Greenwich time (GMT) in hours (Example: +0100) Timezone setting of the PHP machine (Examples:EST, MDT) Timezone offset in seconds. The offset west of UTC isnegative, and the offset east of UTC is positive (-43200 to 43200)

C R U

The ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00) The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07 +0200) - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

Example <?php echo("Result with date():<br />"); echo(date("l") . "<br />"); echo(date("l dS \of F Y h:i:s A") . "<br />"); echo("Oct 3,1975 was on a ".date("l", mktime(0,0,0,10,3,1975))."<br />"); echo(date(DATE_RFC822) . "<br />"); echo(date(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br /><br />"); echo("Result with gmdate():<br />"); echo(gmdate("l") . "<br />"); echo(gmdate("l dS \of F Y h:i:s A") . "<br />"); echo("Oct 3,1975 was on a ".gmdate("l", mktime(0,0,0,10,3,1975))."<br />"); echo(gmdate(DATE_RFC822) . "<br />"); echo(gmdate(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br />"); ?>

The output of the code above could be something like this:

Result with date():


Tuesday Tuesday 24th of January 2006 02:41:22 PM Oct 3,1975 was on a Friday Tue, 24 Jan 2006 14:41:22 CET 1975-10-03T00:00:00+0100
54

Result with gmdate():


Tuesday Tuesday 24th of January 2006 01:41:22 PM Oct 3,1975 was on a Thursday Tue, 24 Jan 2006 13:41:22 GMT 1975-10-02T23:00:00+0000

Adding a Timestamp
The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used. The mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Syntax for mktime() mktime(hour,minute,second,month,day,year,is_dst) To go one day in the future we simply add one to the day argument of mktime(): <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> The output of the code above could be something like this: Tomorrow is 2009/05/12

Runtime Configuration
The behavior of the date/time functions is affected by settings in php.ini. Date/Time configuration options: Name date.default_latitude Default "31.7667" Description Specifies the default latitude (available since PHP 5). This option is used by date_sunrise() and date_sunset() Changeable PHP_INI_ALL

55

date.default_longitude "35.2333"

Specifies the default longitude (available since PHP 5). This option is used by date_sunrise() and date_sunset()

PHP_INI_ALL

date.sunrise_zenith

"90.83"

Specifies the default sunrise zenith (available since PHP 5). This option is used by date_sunrise() and date_sunset()

PHP_INI_ALL

date.sunset_zenith

"90.83"

Specifies the default sunset zenith (available since PHP 5). This option is used by date_sunrise() and date_sunset()

PHP_INI_ALL

date.timezone

Specifies the default timezone (available since PHP 5.1)

PHP_INI_ALL

PHP checkdate() Function Definition and Usage


The checkdate() function returns true if the specified date is valid, and false otherwise.

A date is valid if:


month is between 1 and 12 inclusive day is within the allowed number of days for the particular month year is between 1 and 32767 inclusive

Syntax :checkdate(month , day , year) Parameter Month Day Year Example <?php var_dump(checkdate(12,31,2000)); var_dump(checkdate(2,29,2003)); var_dump(checkdate(2,29,2004)); ?>
56

Description Required. Specifies the month Required. Specifies the day Required. Specifies the year

The output of the code above will be:


bool(true) bool(false) bool(true)

PHP getdate() Function


Definition and Usage The getdate() function returns an array that contains date and time information for a Unix timestamp. The returning array contains ten elements with relevant information needed when formatting a date string: [seconds] - seconds [minutes] - minutes [hours] - hours [mday] - day of the month [wday] - day of the week [year] - year [yday] - day of the year [weekday] - name of the weekday [month] - name of the month

Syntax getdate(timestamp)
Parameter Description timestamp Optional. Specifies the time in Unix time format Example <?php print_r(getdate()); ?>

The output of the code above could be:


Array ( [seconds] => 45 [minutes] => 52 [hours] => 14 [mday] => 24
57

[wday] => 2 [mon] => 1 [year] => 2006 [yday] => 23 [weekday] => Tuesday [month] => January [0] => 1138110765 )

Example
<?php $my_t=getdate(date("U")); print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]"); ?>

The output of the code above could be:


Wednesday, January 25, 2006

PHP gettimeofday() Function


Definition and Usage
The gettimeofday() function returns an array that contains current time information.

The meaning of the returning array keys:


[sec] - seconds since the Unix Epoch [usec] - microseconds [minuteswest] - minutes west of Greenwich [dsttime] - type of dst correction gettimeofday(return_float)

Syntax

Parameter Description
return_float Optional. Makes gettimeofday() return a float when it is set to true. Example <?php echo(gettimeofday(true) . "<br /><br />"); print_r(gettimeofday()); ?>

The output of the code above could be:


58

1138111447.4 Array ( [sec] => 1138111447 [usec] => 395863 [minuteswest] => -60 [dsttime] => 0 ) Example <?php $my_t=gettimeofday(); print("$my_t[sec].$my_t[usec]"); ?> The output of the code above could be: 1138197006.988273

59

CHAPTER- 9

Arrays
Array() Construct
Arrays can be declared using the array() language construct, which generally takes the following form (elements inside square brackets, [], are optional): array([key =>value,key=>value,...) The key is optional, and when its not specified, the key is automatically assigned one more than the largest previous integer key (starting with 0). You can inter mix the use with and without the key even within the same declaration. The value itself can be of any PHP type, including an array. Arrays containing arrays give a similar result as multi-dimensional arrays in other languages. Here are a few examples: array(1, 2, 3) is the same as the more explicit array(0 => 1, 1 => 2, 2 one is a collection (array) of a persons information.

Accessing Array Elements


Array elements can be accessed by using the $arr[key] notation, where key is either an integer or string expression. When using a constant string for key, make sure you dont forget the single or double quotes, such as $arr["key"]. This notation can be used for both reading array elements and modifying or creating new elements.

Modifying/Creating Array Elements


$arr1 = array(1, 2, 3); $arr2[0] = 1; $arr2[1] = 2; $arr2[2] = 3; print_r($arr1); print_r($arr2); The print_r() function has not been covered yet in this book, but when it is passed an array, it prints out the arrays contents in a readable way. You can use this function when debugging your scripts. So, you can see that you can use both the array() construct and the $arr[key] notation to create arrays. Usually, array() is used to declare arrays whose elements are known at compile-time, and the $arr[key] notation is used when the elements are only computed at runtime. PHP also supports a special notation, $arr[], where the key is not specified. When creating new array offsets
60

using this notation (fo example, using it as the l-value), the key is automatically assigned as one more than the largest previous integer key. There fore, the previous example can be rewritten as follows: $arr1=array(1, 2, 3); $arr2[] = 1; $arr2[] = 2; $arr2[] = 3;

The result is the same as in the previous example.


The same holds true for arrays with string keys $arr1 = array("name" => "John", "age" => 28) $arr2["name"] = "John" $arr2["age"] = 28 if ($arr1 == $arr2) { print '$arr1 and $arr2 are the same' . "\n"; } The message confirming the equality of both arrays is printed.

Reading Array Values


You can use the $arr[key] notation to read array values. The next few examples build on top of the previous example: print $arr2["name"]; if ($arr2["age"] < 35) { print " is quite young\n"; } This example prints John is quite young Note: As previously mentioned, using the $arr[] syntax is not supported when reading array indexes, but only when writing them.

Accessing Nested Arrays (Or Multi-Dimensional Arrays)


When accessing nested arrays, you can just add as many square brackets as required to reach the relevant value. The following is an example of how you can declare nested arrays:
61

$arr = array(1 => array("name" => "John", "age" => 28), array("name" => "Barbara", "age" => 67)) You could achieve the same result with the following statements: $arr[1]["name"] = "John"; $arr[1]["age"] = 28; $arr[2]["name"] = "Barbara"; $arr[2]["age"] = 67; Reading a nested array value is trivial using the same notation. For example, if you want to print Johns age, the following statement does the trick: print $arr[1]["age"];

Traversing Arrays Using Foreach


There are a few different ways of iterating over an array. The most elegant way is the foreach() loop construct. The general syntax of this loop is foreach($array as [$key =>] [&] $value) ... $key is optional, and when specified, it contains the currently iterated values key, which can be either an integer or a string value, depending on the keys type.

Traversing Arrays Using List() And Each()


Although foreach() is the nicer way of iterating over an array, an additional way of traversing an array is by using a combination of the list() construct and the each() function: $players = array("John", "Barbara", "Bill", "Nancy"); reset($players); while (list($key, $val) = each($players)) { print "#$key = $val\n"; }

The output of this example is


#0 = John #1 = Barbara #2 = Bill #3 = Nancy
62

reset()
Iteration in PHP is done by using an internal array pointer that keeps record of the current position of the traversal. Unlike with foreach(), when you want to use each() to iterate over an array, you must reset() the array before you start to iterate over it. In general, it is best for you to always use foreach() and not deal with this subtle nuisance of each() traversal.

each()
The each() function returns the current key/value pair and advances the internal pointer to the next element. When it reaches the end of of the array, it returns a booloean value of false. The key/value pair is returned as an array with four elements: the elements 0 and "key", which have the value of the key, and elements 1 and "value", which have the value of the value. The reason for duplication is that, if youre accessing these elements individually, youll probably want to use the names such as $elem["key"] and $elem["value"]: $ages = array("John" => 28, "Barbara" => 67); reset($ages); $person = each($ages); print $person["key"]; print " is of age "; print $person["value"]; This prints John is of age 28 When we explain how the list() construct works, you will understand why offsets 0 and 1 also exist.

list()
The list() construct is a way of assigning multiple array offsets to multiple variables in one statement: list($var1, $var2, ...) = $array; The first variable in the list is assigned the array value at offset 0, the second is assigned offset 1, and so on. Therefore, the list() construct translates into the following series of PHP statements: $var1 = $array[0];
63

$var2 = $array[1]; As previously mentioned, the indexes 0 and 1 returned by each() are used by the list() construct. You can probably already guess how the combination of list() and each() work.

Consider the highlighted line from the previous $players traversal example:
$players = array("John", "Barbara", "Bill", "Nancy"); reset($players); while (list($key, $val) = each($players)) { print "#$key = $val\n"; } What happens in the boldfaced line is that during every loop iteration, each() returns the current positions key/value pair array, which, when examined with print_r(), is the following array: Array ( [1] => John [value] => John [0] => 0 [key] => 0 ) Then, the list() construct assigns the arrays offset 0 to $key and offset 1 to $val .

Some Of The Most Used Array Functions array_combine Creates an array by using one array for keys and another for its values
array array_combine ( array $keys, array $values ) Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Example:
<?php $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b); print_r($c); ?>

64

The above example will output: Array ( [green] => avocado [red] => apple [yellow] => banana )

array_count_values Counts all the values of an array


array array_count_values ( array $input ) array_count_values() returns an array using the values of the input array as keys and their frequency in input as values. <?php $array = array(1, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?> The above example will output : Array ( [1] => 2 [hello] => 2 [world] => 1 )

array_diff Computes the difference of arrays


array array_diff ( array $array1, array $array2 [, array $ ...] ) Compares array1 against array2 and returns the difference. Example: <?php $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); print_r($result); ?> Array ( [1] => blue )
65

array_keys Return all the keys of an array


array array_keys ( array $input [, mixed $search_value [, bool $strict]] ) array_keys() returns the keys, numeric and string, from the input array. If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. As of PHP 5, you can use strict parameter for comparison including type (===). <?php $array = array(0 => 100, "color" => "red"); print_r(array_keys($array)); $array = array("blue", "red", "green", "blue", "blue"); print_r(array_keys($array, "blue")); $array = array("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large")); print_r (array_keys($array)); ?> The above example will output: Array ( [0] => 0 [1] => color ) Array ( [0] => 0 [1] => 3 [2] => 4 ) Array ( [0] => color [1] => size )

66

array_merge Merge one or more arrays


array array_merge ( array $array1 [, array $array2 [, array $...]] ) array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. Example: <?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?>

The above example will output: Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )

array_search- Searches the array for a given value and returns the corresponding
key if successful mixed array_search ( mixed $needle, array $haystack [, bool $strict] ) Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.

Note: If needle is a string, the comparison is done in a case-sensitive manner.


Example: <?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array); // $key = 1; ?>
67

array_shift Shift an element off the beginning of array


mixed array_shift ( array &$array ) array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be returned. Example: <?php $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_shift($stack); print_r($stack); ?> This would result in $stack having 3 elements left: Array ( [0] => banana [1] => apple [2] => raspberry )

sort Sort an array


bool sort ( array &$array [, int $sort_flags] ) Example: <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange

68

rsort Sort an array in reverse order


bool rsort ( array &$array [, int $sort_flags] ) This function sorts an array in reverse order (highest to lowest). Example: <?php $fruits = array("lemon", "orange", "banana", "apple"); rsort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?>

The above example will output: 0 = orange 1 = lemon 2 = banana 3 = apple

reset Set the internal pointer of an array to its first element.


mixed reset ( array &$array ) reset() rewinds array 's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty. Example <?php $array = array('step one', 'step two', 'step three', 'step four'); // by default, the pointer is on the first element echo current($array) . "<br /> "; // "step one" // skip two steps next($array); next($array); echo current($array) . "<br /> "; // "step three" // reset pointer, start again on step one reset($array); echo current($array) . "<br /> "; // "step one" ?>
69

CHAPTER - 10

Functions
Function can be defined as small peace of code within you program which performs a predefined task within your program. Function can be understood as smallest execution unit of your program. They can be categorized as following

Built-In Functions
These are the function which are provided to us by language itself we just use these function within our program. We are already familiar with Built-in function some of the most used built in functions are as follows Print(), printf() ,include(),require() etc.

User-Defined Functions
These are the function which definition is defined by the user itself according to their need. The general way of defining a function is function function _ name ( arg1 , arg2 , arg3 , ) { statement list } To return a value from a function, you need to make a call to return expr inside your function. This stops execution of the function and returns expr as the functions value.The following example function accepts one argument, $x, and returns its square: Example: function square ($x) { return $x*$x; } After defining this function, it can be used as an expression wherever you desire.

Example: print 'The square of 5 is ' . square(5);

Returning Values By Value


You can tell from the previous example that the return statement is used to return values from functions. The return statement returns values by value ,which means that a copy of the value is created and is returned to the caller of the function.

Example:
70

function get_global_variable_value($name) { return $GLOBALS[$name]; } $num = 10; $value = get_global_variable_value("num"); print $value;

This code prints the number 10. However, making changes to $value before the print statement only affects $value and not the global variable $num. This is because its value was returned by the get_global_variable_value() by value and not by reference

Returning Values By Reference


PHP also allows you to return variables by reference . This means that youre not returning a copy to the variable, but youre returning the address of your variable instead, which enables you to change it from the calling scope. To return a variable by-reference, you need to define the function as such by placing an & sign in front of the functions name and in the callers code, assigning the return value by reference to $value: function &get_global_variable($name) { return $GLOBALS[$name]; } $num = 10; $value =& get_global_variable("num"); print $value . <br>"; $value = 20; print $num; The previous code prints as 10 20 You can see that $num was successfully modified by modifying $value, because it is a reference to the global variable $num. You wont need to use this returning method often. When you do, use it with care, because forgetting to assign by reference the by-reference returned value can lead to bugs that are difficult to track down.

71

Declaring Function Parameters


As previously mentioned, you can pass an arbitrary amount of arguments to a function. There are two different ways of passing these arguments. The first is the most common, which is called passing by value , and the second is called passing by reference . Which kind of argument passing you would like is specified in the function definition itself and not during the function call.

By-Value Parameters
Here, the argument can be any valid expression, the expression is evaluated, and its value is assigned to the corresponding variable in the function. Example here, $x is assigned the value 8 and $y is assigned the value of $c: function pow($x, $y) { ... } pow(2*4, $c);

By-Reference Parameters
Passing by-reference requires the argument to be a variable. Instead of the variables value being passed, the corresponding variable in the function directly refers to the passed variable whenever used. Thus, if you change it inside the function, it affects the sent variable in the outer scope as well: Example function square(&$n) { $n = $n*$n; } $number = 4; square($number); print $number; The & sign that proceeds $n in the function parameters tells PHP to pass it by-reference, and the result of the function call is $number squared; thus, this code would print 16.

72

Default Parameters
Default parameters like C++ are supported by PHP. Default parameters enable you to specify a default value for function parameters that arent passed to the function during the function call. The default values you specify must be a constant value, such as a scalar, array with scalar values, or constant.

Static Variables
Like C, PHP supports declaring local function variables as static. These kind of variables remain in tact in between function calls, but are still only accessible from within the function they are declared. Static variables can be initialized, and this initialization only takes place the first time the static declaration is reached. Heres an example for the use of static that runs initialization code the first time (and only the first time) the function is run: Example function do_something() { static first_time = true; if (first_time) { // Execute this code only the first time the function is called ... } // Execute the function's main logic every time the function is called ... }

Some Usefull Built-In Functions require()


The require() statement includes and evaluates the specific file. require() includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for include(). require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.
73

Example. <?php require 'prepend.php'; require $somefile; require ('somefile.txt'); ?>

include()
The include() statement includes and evaluates the specified file. The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does. Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries , current working directory is /www/ , you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/ . If filename begins with ./ or ../ , it is looked only in the current working directory. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. Example . vars.php <?php $color = 'green'; $fruit = 'apple'; ?>

74

test.php <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?>

require_once()
The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again. See the documentation for require() for more information on how this statement works. require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc. For examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions. Return values are the same as with include(). If the file was already included, this function returns TRUE Note: require_once() was added in PHP 4.0.1 Note: Be aware, that the behaviour of require_once() and include_once() may not be what you expect on a non case sensitive operating system (such as Windows). Example: require_once() is case insensitive on Windows <?php require_once "a.php"; // this will include a.php require_once "A.php"; // this will include a.php again on Windows! (PHP 4 only) ?>

include_once()
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once. include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included
75

exactly once to avoid problems with function edefinitions, variable value reassignments, etc. For more examples on using require_once() and include_once() , look at the PEAR code included in the latest PHP source code distributions. Return values are the same as with include(). If the file was already included, this function returns TRUE

Note: include_once() was added in PHP 4.0.1 Note: Be aware, that the behaviour of include_once() and require_once() may not be what you
expect on a non case sensitive operating system (such as Windows). Example 16.12. include_once() is case insensitive on Windows <?php include_once "a.php"; // this will include a.php include_once "A.php"; // this will include a.php again on Windows! (PHP 4 only) ?>

printf Output a formatted string


int printf ( string $format [, mixed $args [, mixed $...]] ) Produces output according to format . For Example $var=This is a book; printf(%-25s,$var);

rename Renames a file or directory


bool rename ( string $oldname, string $newname [, resource $context] )

Attempts to rename oldname to newname .


For Example <?php rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt"); ?>

sleep Delay execution


int sleep ( int $seconds ) Delays the program execution for the given number of seconds .

76

Example <?php // current time echo date('h:i:s') . "<br>"; // sleep for 10 seconds sleep(10); // wake up ! echo date('h:i:s') . "<br>"; ?> This example will output (after 10 seconds) 05:31:23 05:31:33

exit() - Output a message and terminate the current script.


Example: <?php $filename = '/path/to/data-file'; $file = fopen($filename, 'r') or exit("unable to open file ($filename)"); ?>

get_browser()
Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file. Listing all information about the users browser

<?php echo $_SERVER['HTTP_USER_AGENT'] . "<br>"; $browser = get_browser(null, true); print_r($browser); ?>

77

The above example will output something similar to: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3 Array ( [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$ [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9* [parent] => Firefox 0.9 [platform] => WinXP [browser] => Firefox [version] => 0.9 [majorver] => 0 [minorver] => 9 [css] => 2 [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [vbscript] => [javascript] => 1 [javaapplets] => 1 [activexcontrols] => [cdf] => [aol] => [beta] => 1 [win16] => [crawler] => [stripper] => [wap] => [netclr] => )

78

CHAPTER -11

Object Oriented Programming in PHP


Introduction
Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model. Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and type hinting. PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

Class
A class is the blueprint for your object. The class contains the methods and properties, or the characteristics of the object. It defines the object. Lets just start with some examples to see how it all pieces together. We will use a vehicle as our object.All vehicles share similar charactaristics, eg: number of doors,they are painted some color, they each have a price. All vehicles do similar things also, drive, turn left, turn right, stop etc. These can be described as functions,or in OOP parlance, methods. So, the class holds the definition, and the object holds the value. You declare class in PHP by using the class keyword. Example: <?php Class SimpleClass { // property declaration Public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; } } ?>

79

Extends
A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class .The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden.It is possible to access the overridden methods or static properties by referencing them with parent. Example: <?php class Myclass { function myfun() { echo "Hello Word"; } } class MyChildClass extends Myclass { public function myfun() { parent::myfun(); } } $obj = new MyChildClass(); $obj->myfun(); ?>

Properties
Class member variables are called "properties". You may also see them referred to using Other terms such as "attributes" or "fields", but for the purposes of this reference we will use properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
80

Class Constants
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. Example <?php class MyClass { const constant = 'constant value'; function showConstant() { echo self::constant . "<br>"; } } echo MyClass::constant . "<br>"; $classname = "MyClass"; echo $classname::constant . "<br>"; // As of PHP 5.3.0 $class = new MyClass(); $class->showConstant(); echo $class::constant."<br>"; // As of PHP 5.3.0 ?>

Autoloading Classes
A very convenient feature, __autoload allows you to get rid of all those annoying includes that need to be managed. This magic function will execute whenever a class or interface is referenced that hasnt been defined.That gives you the opportunity to include it. Example : autoload_test.php <?php class autoload_test { function myfun() { echo "Hello HPES Student"; } } ?>
81

use_autoload.php
<?php function __autoload($className) { include $className . '.php'; } $obj_autoload = new autoload_test(); $obj_autoload->myfun(); ?>

Constructors and Destructors


Constructor : void __construct ([ mixed $args [, $... ]] ) it provides an opportunity for doing necessary setup operations like initializing class variables, opening databaseconnections or socket connections, etc. In simple terms, it is needed to setup the object before it can be used. In PHP5 a constructor is defined by implementing the __construct () method.This naming style has been introduced in PHP5. In PHP4, the name of the constructor was the same name as that of the class.So, for example if you had a class Customer, you would have to implement a function Customer() <?php class BaseClass { function __construct() { } class SubClass extends BaseClass { function __construct() { parent:: __construct(); print "In SubClass constructor <br>"; } } $obj = new BaseClass(); $obj = new SubClass(); ?> only case that would have compatibility issues is if the class had a method named__cons truct() whichwas used for different semantics.
82

print "In BaseClass constructor <br>"; }

Destructor :

void__destructor ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++.The destructor method will be called as soon as all references to a particular object are removed orwhen the object is explicitly destroyed or in any order in shutdown sequence. Example: <?php Class MyDestructableClass { function __construct() { print "In constructor <br>"; $this->name ="MyDestructableClass"; } function __destruct() { print "Destroying " .$this->name ."<br>"; } } $obj = new MyDestructableClass(); ?> Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly callp aren t::__d es tru ct() in the destructor body.

Note: Destructors called during the script shutdown have HTTP headers already sent. The
working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).

Note: Attempting to throw an exception from a destructor (called in the time of script
termination) causes a fatal error.

83

Visibility
PHP 5 allows you to declare the visibility of methods and properties. There are three types of visibility: Public Protected

Private.
Public
Public methods and properties are visible (accessible) to any code that queries them. No accessibility restrictions are applied.In PHP 5, methods without visibility declaration are assumed public, the visibility declaration is required, excluding static class members (if you dont include it, public is assumed). Class constants are always globally available. Protected Requests are only allowed from within the objects blueprint (that includes parent and child classes). Private Access is limited to the declaring class (the class the property is declared in). No external access whatsoever is allowed. One thing that should be noted when using protected or private properties, is that if you attempt to assign a value to a property that isnt visible to the class you are doing it in, you will be creating a new property instead of resetting the original. Keep that in mind when you get unexpected values: check the propertys visibility. Example: <?php class MyClass { public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj = new MyClass();
84

echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private //Define MyClass2 class MyClass2 extends MyClass { // We can redeclare the public and protected method, but not private protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj2 = new MyClass2(); echo $obj2->public; // Works echo $obj2->private; // Undefined echo $obj2->protected; // Fatal Error $obj2->printHello(); // Shows Public, Protected2, Undefined ?>

Scope Resolution Operator (::)


The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static,cons tant, and overridden properties or methods of a class. When referencing these items from outside the class definition, use the name of the class. As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g.s elf,p are n t ands tati c). Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon.However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew! Example: <?php Class MyClass { Const CONST_VALUE = 'A constant value'; }

$classname= 'MyClass'; echo $classname::CONST_VALUE; // As of PHP 5.3.0 echo MyClass::CONST_VALUE; ?>


85

<?php class OtherClass extends MyClass { public static$my_static = 'static var'; public static functiondoubleColon() { echo parent::CONST_VALUE ."<br/>"; echo self::$my_static ."<br/>"; } } $classname= 'OtherClass'; echo $classname::doubleColon(); // As of PHP 5.3.0 OtherClass::doubleColon(); ?> When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Static Keyword
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can). For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public. Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.Static properties cannot be accessed through the object using the arrow operator ->. Calling non-static methods statically generates an E_STRICT level warning. Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object. As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static).
86

Example: <?php classFoo { public static $my_static = 'foo'; public function staticValue() { return self::$my_static; } } class Bar extends Foo { public function fooStatic() { returnparent::$my_static; } } print Foo::$my_static ."<br/>"; $foo = new Foo(); print $foo->staticValue()."<br/>"; print $foo->my_static ."<br/>"; // Undefined "Property" my_static print $foo::$my_static ."<br/>"; $classname= 'Foo'; print $classname::$my_static ."<br>"; // As of PHP 5.3.0 print Bar::$my_static ."<br/>"; $bar = new Bar(); print$bar->fooStatic() ."<br/>"; ?>

Class Abstraction
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.

87

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Example: <?php abstract class AbstractClass { // Force Extending class to define this method abstract protected function getValue(); abstract protected function prefixValue($prefix); // Common method public function printOut() { print $this->getValue() . "\n"; } } class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1"; }

public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; } } $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue('FOO_') ."<br/>; ?>

88

Object Interfaces
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.All methods declared in an interface must be public, this is the nature of an interface.

implements
To implement an interface, the implements operator is used. All methods in theinterfacemust be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma. Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity. Interface Example : <?php // Declare the interface 'iTemplate' interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // Implement the interface // This will work class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template);
89

} return $template; } } // This will not work // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (iTemplate::getHtml) class BadTemplate implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } } ?>

Overloading
Overloading in PHP provides means to dynamically "create" members and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. The overloading methods are invoked when interacting with members or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible members" and "inaccessible methods" to refer to this combination of declaration and visibility. All overloading methods must be defined as public.

Note: None of the arguments of these magic methods can be passed by reference. Note: PHP's interpretation of "overloading" is different than most object oriented languages.
Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

90

Changelog
Version 5.3.0 5.1.0 Description Added __callStatic(). Added warning to enforce public visibility and non-static declaration. Added __isset() and __unset().

Property overloading
1. void __set ( string $name , mixed $value ) 2. mixed __get ( string $name ) 3. bool __isset ( string $name ) 4. void __unset ( string $name ) __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties. __isset() is triggered by calling isset() or empty() on inaccessible properties. __unset() is invoked when unset() is used on inaccessible properties. The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to. Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods cannot be declared static.

Note: The return value of __set() is ignored because of the way PHP processes the assignment
operator. Similarly, __get () is never called when chaining assignments together like this: $a = $obj->b = 8;

Example :
<?php class PropertyTest { /** Location for overloaded data. */ private $data = array(); /** Overloading not used on declared properties. */ public $declared = 1;
91

/** Overloading only used on this when accessed outside the class. */ private $hidden = 2; public function __set($name, $value) { echo "Setting '$name' to '$value'\n"; $this->data[$name] = $value; } public function __get($name) { echo "Getting '$name'\n"; if (array_key_exists($name, $this->data)) { return $this->data[$name]; } $trace = debug_backtrace(); trigger_error( 'Undefined property via __get(): ' . $name.'in'. $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE); return null; } /** As of PHP 5.1.0 */ public function __isset($name) { echo "Is '$name' set?\n"; return isset($this->data[$name]); } /** As of PHP 5.1.0 */ public function __unset($name) { echo "Unsetting '$name'\n"; unset($this->data[$name]); } /** Not a magic method, just here for example. */ public function getHidden() { return $this->hidden; } } echo "<pre>\n";
92

$obj = new PropertyTest; $obj->a = 1; echo $obj->a . "<br>"; var_dump(isset($obj->a)); unset($obj->a); var_dump(isset($obj->a)); echo "\n"; echo $obj->declared . "\n\n"; echo "Let's experiment with the private property named 'hidden':\n"; echo "Privates are visible inside the class, so __get() not used...\n"; echo $obj->getHidden() . "\n"; echo "Privates not visible outside of class, so __get() is used...\n"; echo $obj->hidden . "\n"; ?>

Method overloading
1. mixed __call ( string $name , array $arguments ) 2. mixed __callStatic ( string $name , array $arguments ) __call() is triggered when invoking inaccessible methods in an object context. __callStatic() is triggered when invoking inaccessible methods in a static context. The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method. The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method. Example: Overloading methods via the __call() and __callStatic() methods <?php class MethodTest { public function __call($name, $arguments) { // Note: value of $name is case sensitive. echo "Calling object method '$name'". implode(', ', $arguments). "\n"; } /** As of PHP 5.3.0 */
93

public static function __callStatic($name, $arguments) { // Note: value of $name is case sensitive. echo "Calling static method '$name'". implode(', ', $arguments). "\n"; } } $obj = new MethodTest; $obj->runTest('in object context'); MethodTest::runTest('in static context'); // As of PHP 5.3.0 ?>

Object Iteration
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration. Example : Simple Object Iteration <?php class MyClass { public $var1 = 'value 1'; public $var2 = 'value 2'; public $var3 = 'value 3';

protected $protected = 'protected var'; private $private = 'private var';

function iterateVisible() { echo "MyClass::iterateVisible:\n"; foreach($this as $key => $value) { print "$key => $value\n"; } } } $class = new MyClass();
94

foreach($class as $key => $value) { print "$key => $value\n"; } echo "\n"; $class->iterateVisible(); ?>

Magic Methods
PHP has lot of magic stored in it. Magic methods in PHP is one way to witness it. These methods are executed automatically on certain event or situation. The function names__construct , __destruct, __get, __set etc are known as magic methods in PHP classes. That means these function names are reserved and you cannot have these function names in your PHP classes when writing you favorite PHP code. According to a disclaimer on PHPs official site, it is mentioned that all functions starting with __ (double underscore) is reserved in PHP. So what does these magical methods do and how can you benefit from these. A common example is the magic method __construct which gets called automatically when an object of a class is created and similarly __destruct is executed when as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence. Example: <?php class foo{ private $private_var = 'my private variable'; function __construct() { echo 'Called __contruct();<br/>'; } function __get($name) { echo "Called __get(); with argument $name"; }

function __set($name,$value) { } $obj=new foo(); //output ->> Called __contruct();


95

echo "Called __set(); with argument $name and value = $value"; }

$obj->private_var ; $obj->pop; $obj->pop='foo '; unset ($obj); ?>

//output ->> Called __get(); with argument private_var

//output ->> Called __get(); with argument pop //output ->> Called __set(); with argument pop and value = foo

In the above example - using __get and _set magic methods of PHP. The __get function or method is called when an inaccessible property is of a class is accessed. In normal case you wont see any errors showing up but a call to the variable has been made, which has not fetched any result. So to avoid such cases or handle such failed calls we use __get function. It is only used to handle properties which are not present instead one can handle request to the variables which are not accessible in the calling context. For example in the above code, the $private_var cannot be called directly outside the class, so in that case __get is executed to handle the request properly. Same is with __set magic method, it gets called when user tries to set a value of the variable or property which is not present or in other terms which is not accessible.

Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Example: <?php class BaseClass { public function test() { echo "BaseClass::test() called\n"; } final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } } class ChildClass extendsBaseClass {
96

public functionmoreTesting() { echo "ChildClass::moreTesting() called\n"; } }// Results in Fatal error: Cannot override final method BaseClass::moreTesting() ?>

Final Class
A final class is a class that cannot be extended. To declare a class as final, you need to prefix the class keyword with final. Example <?php final class BaseClass { public function myMethod() { echo "BaseClass method called"; } } //this will cause Compile error class DerivedClass extends BaseClass { public function myMethod() { echo "DerivedClass method called"; } }

$c = new DerivedClass(); $c->myMethod() ?> In the above example, BaseClass is declared as final and hence cannot be extended (inherited). DerivedClass tries to extend from BaseClass and hence the compiler will throw a compile error

Final Method
A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the final keyword. Example <?php
97

class BaseClass { final public function myMethod() { echo "BaseClass method called"; } } class DerivedClass extends BaseClass { //this will cause Compile error public function myMethod() { echo "DerivedClass method called"; } } $c = new DerivedClass(); $c->myMethod() ?> In the above example, Derived Class extends from BaseClass. BaseClass has the method myMethod() declared as final and this cannot be overridden. In this case the compiler causes a compile error

Object Cloning
Meaning of clone is that make multiple identical copies of the original one, the process of cloning in PHP 5 is quite different from PHP 4, in the earlier version of PHP all we need to do is to assign an object to another object. But in the latest version of PHP, clone construct along with a magic method is used to control the cloning process. A clone object is created by using clone keyword which is called implicitly, and it is not possible to call the method explicitly. When an object is cloned a shallow copy of the original object is created. After the creation of cloned object, if a __clone() method is defined, __clone() method of the newly created object is called, to change any properties which is need to be changed. <?php class A { public $var1; static $var2=0;
98

public function __construct(){ $this->var1=++self::$var2; } public function __clone(){ $this->var1=++self::$var2;}} class B{ public $obj1; public $obj2; function __clone() { $this->obj1=$this->obj2;} } $objA=new B(); $objA->obj1=new A; $objA->obj2=new A; $objB=clone $objA; print("Actual Object is:<br/>"); print_r($objA); print("<br/>Clone Object is:<br/>"); print_r($objB); ?> Output: Actual Object is: B Object ( [obj1] => A Object ( [var1] => 1 ) [obj2] => A Object ( [var1] => 2 ) ) Clone Object is: B Object ( [obj1] => A Object ( [var1] => 2 ) [obj2] => A Object ( [var1] => 2 ) )

Comparing objects
There are several ways are provided in PHP to compare two objects of class (same or different). There are mainly = =, = = = operators are used to compare two objects, and instance of operator can be used also. The operator = = checks the attributes and values of objects and returns true if the objects are of same class and has equal values .The operator = = = checks two objects and returns true if both

99

refers two the same object a class. Instance of is an operator which is used to check whether an object is an instance of a class or not. Following examples will exemplify these operators: Example of object comparison in PHP 5 <?php class A { public $one; } class B{ public $two; } $obj1=new A(); $obj2=new B(); $obj3=new A(); $obj4=$obj1; echo "<b>Comparison of two objects of same class</b>"; compareObjects($obj1,$obj3); echo "<br/><b>Comparison of two objects of different class</b>"; compareObjects($obj1,$obj2); echo "<br/><b>Comparison of two references of same object</b>"; compareObjects($obj1,$obj4); function compareObjects($obj1,$obj2){ echo "<br/>Using = = operator"; echo "<br/>Objects are same: ".op1($obj1,$obj2); echo "<br/>Using instanceof operator"; echo "<br/> Objects are same: ".instance($obj1,$obj2); echo "<br/>Using = = = operator"; echo "<br/> Objects are same: ".op2($obj1,$obj2); }
100

function op1($obj1,$obj2){ if($obj1==$obj2)return "true"; else return "false";} function instance($obj1,$obj2){ if(($obj1 instanceof A)&&($obj2 instanceof A)) return "true"; else return 'false'; } function op2($obj1,$obj2){ if($obj1===$obj2)return "true"; else return "false"; }?>

Type Hinting
PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). Examples <?php class MyClass { //A test function //First parameter must be an object of type OtherClass public function test(OtherClass $otherclass) { echo $otherclass->var; } //Another test function // First parameter must be an array public function test_array(array $input_array)

101

{ print_r($input_array); } // Another example class class OtherClass {

public $var = 'Hello World'; ?>

Failing to satisfy the type hint results in a fatal error.


<?php // An instance of each class $myclass = new MyClass; $otherclass = new OtherClass; // Fatal Error: Argument 1 must be an object of class OtherClass $myclass->test('hello'); // Fatal Error: Argument 1 must be an instance of OtherClass $foo = new stdClass; $myclass->test($foo); // Fatal Error: Argument 1 must not be null $myclass->test(null); // Works: Prints Hello World $myclass->test($otherclass); // Fatal Error: Argument 1 must be an array $myclass->test_array('a string'); // Works: Prints the array
102

$myclass->test_array(array('a','b','c')); ?> Type hinting also works with functions: <?php class MyClass { public $var = 'Hello World';} //A test function //First parameter must be an object of type MyClass function MyFunction (MyClass $foo) { echo $foo->var;}

$myclass = new MyClass; MyFunction($myclass); ?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

Serialization
Resource handles dont serialize. If one of your properties has a resource handle as its value, for example a file handle or database connection, You can use the __wakeup magic to reestablish these handles. This method will be called when you call unserialize($serializedObject). The __sleep method is invoked when you serialize an object, and is expected to return an array of property names to be included in the serialization. This allows you to exclude certain properties.

Late Static Binding


A new feature called late static binding is introduced in PHP 5.3.0 which can be used to refer the called class.The name late static binding is coined because of the static:: will no longer be resolved using the class where the method is defined. <?php class One { public static function classIdentifier()
103

{ echo __CLASS__; } public static function classtest() { self::classIdentifier(); } } class Two extends One { public static function classIdentifier() { } Two:: classtest(); ?> echo __CLASS__; }

104

CHAPTER-12

File Handling
A file can be defined as a collection of related data items which is stored in a particular location in computes secondry memory unit. A file saves data on permanent basis data saved to it does not deleted untill we intensionaly delete it. This is a supermely useful set of functions, paritcularly for data sets too small of saca ttered to merit the use of a database. File reading is pretty safe unless you keep unencrypted passwords lying around, but file writing can be quite unsafe.

File Handling
To handle these files from our programs and manipulation them such as performing Reading,Writing,Searching,Updating,Deleting Is know as file handling.

Understanding PHP File Permission


We are going to break it down for you into two simple default rules specially for PHP users Unless you have a good reason to do oterwise, your PHP Files should all be set to 644(rw-rr--) Unless you have a good reason to do otherwise, you PHP enabled directories should all be set to 751(rwxr-xx).

File Reading And Writing Function


A file manipulation session might involve the following steps: 1. Open the file for read/write. 2. Read in the file. 3. Close the file(may happen later). 4. Perform operations on the file contents. 5. Write results out

105

Most Essential File Operation Functions fopen Opens file or URL


resource fopen( string $filename, string $mode [, bool $use_include_path [, resource $context]] ) fopen() binds a named resource, specified by filename , to a stream. <?php $handle = fopen("c:\\data\\info.txt", "r"); ?> A List OfF Possible Modes For fopen () Using Mode Mode 'r' r+' 'w' Description Open for reading only; place the file pointer at the beginning of the file. Open for reading and writing; place the file pointer at the beginning of the file. Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. 'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level . 'x' E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level . x+ E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

106

For Example <?php $handle = fopen("/home/rasmus/file.txt", "r"); $handle = fopen("/home/rasmus/file.gif", "wb"); $handle = fopen("http://www.example.com/", "r"); $handle = fopen("ftp://user:password@example.com/somefile.txt", "w"); ?>

fread Binary-safe file read


string fread ( resource $handle, int $length ) fread() reads up to length bytes from the file pointer referenced by handle . Reading stops as soon as one of the following conditions is met: length bytes have been read EOF (end of file) is reached a packet becomes available (for network streams) 8192 bytes have been read (after opening userspace stream)

Example <?php // get contents of a file into a string $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); ?>

fwrite Binary-safe file write


int fwrite ( resource $handle, string $string [, int $length] ) fwrite() writes the contents of string to the file stream pointed to by handle .

107

A simple fwrite() example <?php $filename = 'test.txt'; $somecontent = "Add this to the file<br>"; if (is_writable($filename)) { if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename)"; fclose($handle); } else { echo "The file $filename is not writable"; } ?>

fclose Closes an open file pointer


bool fclose ( resource $handle ) The file pointed to by handle is closed . A simple fclose() example <?php $handle = fopen('somefile.txt', 'r'); fclose($handle); ?>

feof Tests for end-of-file on a file pointer


bool feof ( resource $handle ) Tests for end-of-file on a file pointer <?php // if file can not be read or doesn't exist fopen function returns FALSE $file = @fopen("no_such_file", "r");
108

// FALSE from fopen will issue warning and result in infinite loop here while (!feof($file)) { } fclose($file); ?>

chmod Changes file mode


bool chmod ( string $filename, int $mode ) Attempts to change the mode of the specified file to that given in mode . Example <?php chmod("/somedir/somefile", 755); // decimal; probably incorrect chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect chmod("/somedir/somefile", 0755); // octal; correct value of mode ?>

Example <?php // Read and write for owner, nothing for everybody else chmod("/somedir/somefile", 0600); // Read and write for owner, read for everybody else chmod("/somedir/somefile", 0644); // Everything for owner, read and execute for others chmod("/somedir/somefile", 0755); // Everything for owner, read and execute for owner's group chmod("/somedir/somefile", 0750); ?>

dirname Returns directory name component of path


string dirname ( string $path ) Given a string containing a path to a file, this function will return the name of the directory. Example <?php $path = "/etc/passwd"; $file = dirname($path); // $file is set to "/etc" ?>
109

Check the following change example: <?php //before PHP 4.3.0 dirname('c:/'); // returned '.' //after PHP 4.3.0 dirname('c:/x'); // returns 'c:\' dirname('c:/Temp/x'); // returns 'c:/Temp' dirname('/x'); // returns '\' ?>

fseek Seeks on a file pointer


int fseek ( resource $handle, int $offset [, int $whence] ) Sets the file position indicator for the file referenced by handle . The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence . whence whence values are: SEEK_SET - Set position equal to offset bytes. SEEK_CUR - Set position to current location plus offset . SEEK_END - Set position to end-of-file plus offset . If whence is not specified, it is assumed to be SEEK_SET . fseek() example <?php $fp = fopen('somefile.txt', 'r'); // read some data $data = fgets($fp, 4096); // move back to the beginning of the file // same as rewind($fp); fseek($fp, 0); ?> ftell Tells file pointer read/write position int ftell ( resource $handle ) Tells the file pointer read/write position.

110

ftell() example <?php // opens a file and read some data $fp = fopen("/etc/passwd", "r"); $data = fgets($fp, 12); // where are we ? echo ftell($fp); // 11 fclose($fp); ?>

is_file Tells whether the filename is a regular file


bool is_file ( string $filename )

is_readable Tells whether the filename is readable


bool is_readable ( string $filename ) Tells whether the filename is readable. is_readable() example <?php $filename = 'test.txt'; if (is_readable($filename)) { echo 'The file is readable'; } else { echo 'The file is not readable'; } ?>

is_writable Tells whether the filename is writable


bool is_writable ( string $filename ) Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable. Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account. <?php $filename = 'test.txt'; if (is_writable($filename)) { echo 'The file is writable';
111

} else { echo 'The file is not writable'; } ?>

rewind Rewind the position of a file pointer


bool rewind ( resource $handle ) Sets the file position indicator for handle to the beginning of the file stream. Note: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

rename Renames a file or directory


Example: <?php rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt"); ?>

fgets Gets line from file pointer


string fgets ( resource $handle [, int $length] ) Gets a line from file pointer. Example <?php $handle = @fopen("/tmp/inputfile.txt", "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); echo $buffer; } fclose($handle); } ?>

112

CHAPTER -13

MySQL Administration
What Is MySQL?
MySQL, the most popular Open Source SQL database management system, is developed, distributed, and supported by MySQL AB. MySQL AB is a commercial company, founded by the MySQL developers. It is a second generation Open Source company that unites Open Source values and methodology with a successful business model. The MySQL Web site (http://www.mysql.com/) provides the latest information about MySQL software and MySQL AB.

MySQL is a database management system


A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL Server. Since computers are very good at handling large amounts of data, database management systems play a central role in computing, as standalone utilities, or as parts of other applications.

MySQL is a relational database management system


A relational database stores data in separate tables rather than putting all the data in one big storeroom. This adds speed and flexibility. The SQL part of MySQL stands for Structured Query Language. SQL is the most common standardized language used to access databases and is defined by the ANSI/ISO SQL Standard. The SQL standard has been evolving since 1986 and several versions exist. In this manual, SQL-92 refers to the standard released in 1992, SQL:1999 refers to the standard released in 1999, and SQL:2003 refers to the current version of the standard. We use the phrase the SQL standard to mean the current version of the SQL Standard at any time.

MySQL software is Open Source.


Open Source means that it is possible for anyone to use and modify the software. Anybody can download the MySQL software from the Internet and use it without paying anything. If you wish, you may study the source code and change it to suit your needs. The MySQL software uses the GPL (GNU General Public License), http://www.fsf.org/licenses/, to define what
113

you may and may not do with the software in different situations. If you feel uncomfortable with the GPL or need to embed MySQL code into a commercial application, you can buy a commercially licensed version from us. See the MySQL Licensing Overview for more information.

The MySQL Database Server is very fast, reliable, and easy to use
If that is what you are looking for, you should give it a try. MySQL Server also has a practical set of features developed in close cooperation with our users. You can find a performance comparison of MySQL Server with other database managers on our benchmark page. The MySQL Benchmark Suite. MySQL Server was originally developed to handle large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Although under constant development, MySQL Server today offers a rich and useful set of functions. Its connectivity, speed, and security make MySQL Server highly suited for accessing databases on the Internet.

MySQL Server works in client/server or embedded systems


The MySQL Database Software is a client/server system that consists of a multi-threaded SQL server that supports different backend , several different client programs and libraries, administrative tools, and a wide range of application programming interfaces (APIs). We also provide MySQL Server as an embedded multi-threaded library that you can link into your application to get a smaller, faster, easier-to-manage standalone product.

A large amount of contributed MySQL software is available


It is very likely that your favorite application or language supports the MySQL Database Server. The official way to pronounce MySQL is My Ess Que Ell (not my sequel), but we don't mind if you pronounce it as my sequel or in some other localized way.

History Of MySQL
We started out with the intention of using the mSQL database system to connect to our tables using our own fast low-level (ISAM) routines. However, after some testing, we came to the conclusion that mSQL was not fast enough or flexible enough for our needs. This resulted in a new SQL interface to our database but with almost the same API interface as mSQL. This API was designed to allow third-party code that was written for use with mSQL to be ported easily for use with MySQL.

114

The derivation of the name MySQL is not clear. Our base directory and a large number of our libraries and tools have had the prefix my for well over 10 years. However, co-founder Monty Widenius's daughter is also named My. Which of the two gave its name to MySQL is still a mystery, even for us. The name of the MySQL Dolphin (our logo) is Sakila, which was chosen by the founders of MySQL AB from a huge list of names suggested by users in our Name the Dolphin contest. The winning name was submitted by Ambrose Twebaze, an Open Source software developer from Swaziland, Africa. According to Ambrose, the feminine name Sakila has its roots in SiSwati, the local language of Swaziland. Sakila is also the name of a town in Arusha, Tanzania, near Ambrose's country of origin, Uganda.

MySQL Useraccount Management


This section describes how to set up accounts for clients of your MySQL server.

It discusses the following topics:


The meaning of account names and passwords as used in MySQL and how that compares to names and passwords used by your operating system How to set up new accounts and remove existing accounts How to change passwords Guidelines for using passwords securely How to use secure connections with SSL

MySQL Usernames And Passwords


A MySQL account is defined in terms of a username and the client host or hosts from which the user can connect to the server. The account also has a password. There are several distinctions between the way usernames and passwords are used by MySQL and the way they are used by your operating system: Usernames, as used by MySQL for authentication purposes, have nothing to do with usernames (login names) as used by Windows or Unix. On Unix, most MySQL clients by default try to log in using the current Unix username as the MySQL username, but that is for convenience only. The default can be overridden easily, because client programs allow any username to be specified with a -u or --user option. Because this means that anyone can attempt to connect to the server using any username, you cannot make a database secure in any way unless all MySQL accounts have passwords. Anyone who specifies a username for an account that has no password is able to connect successfully to the server. MySQL usernames can be up to 16 characters long. This limit is hard- coded in the MySQL
115

servers and clients, and trying to circumvent it by modifying the definitions of the tables in the mysql database does not work .

mysql_upgrade Check Tables for MySQL Upgrade. Attempting to redefine MySQL's


system tables in any other fashion results in undefined (and unsupported!) behavior .Operating system usernames are completely unrelated to MySQL usernames and may even be of a different maximum length. For example, Unix usernames typically are limited to eight characters. MySQL passwords have nothing to do with passwords for logging in to your operating system.

There is no necessary connection between the password you use to log in to a Windows or Unix machine and the password you use to access the MySQL server on that machine. MySQL encrypts passwords using its own algorithm. This encryption is different from that

used during the Unix login process. MySQL password encryption is the same as that implemented by the PASSWORD () SQL function . Unix password encryption is the same as that implemented by the ENCRYPT() SQL function. It is secure even if TCP/IP packets are sniffed or the mysql database is captured. (In earlier versions, even though passwords are stored in encrypted form in the user table, knowledge of the encrypted password value could be used to connect to the MySQL server) . When you connect to a MySQL server with a command-line client, you should specify the username and password for the account that you want to use: shell> mysql --user=monty --password= guess db_name If you prefer short options, the command looks like this: shell> mysql -u monty -p guess db_name There must be no space between the -p option and the following password value. The preceding commands include the password value on the command line, which can be a security risk. Keeping Your Password Secure. To avoid this problem, specify the --password or -p option without any following password value: shell> mysql --user=monty --password db_name shell> mysql -u monty -p db_name

Creating User
Create user db_user IDENTIFIED BY db_password;

Deleting User
Drop user db_user;

Creating Database
Create database database_name;
116

Deleting Database
Drop database_name;

When the password option has no password value, the client program prints a prompt and waits for you to enter the password. (In these examples, db_name is not interpreted as a password because it is separated from the preceding password option by a space.) On some systems, the library routine that MySQL uses to prompt for a password automatically limits the password to eight characters. That is a problem with the system library, not with MySQL. Internally, MySQL doesn't have any limit for the length of the password. To work around the problem, change your MySQL password to a value that is eight or fewer characters long, or put your password in an option file.

mysql > GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'


-> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;

mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'


-> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;

mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost'; mysql> GRANT USAGE ON *.* TO 'dummy'@'localhost';

Databases
There were some changes in PHP 5 regarding databases (MySQL and SQLite). In PHP 5 the MySQL client libraries are not bundled, because of license problems and some others. For more information, read the FAQ entry. There is also a new extension, MySQLi (Improved MySQL), which is designed to work with MySQL 4.1 and above. Since PHP 5, the SQLite extension is built-in PHP. SQLite is an embeddable SQL database engine and is not a client library used to connect to a big database server (like MySQL or PostgreSQL). The SQLite library reads and writes directly to and from the database files on disk.

MySQL Datatypes
Other Vendor Type BOOL BOOLEAN CHARACTER VARYING(M) FIXED MySQL Type TINYINT TINYINT VARCHAR(M) DECIMAL
117

FLOAT4 FLOAT8 INT1 INT2 INT3 INT4 INT8 LONG VARBINARY LONG VARCHAR LONG MIDDLEINT NUMERIC

FLOAT DOUBLE TINYINT SMALLINT MEDIUMINT INT BIGINT MEDIUMBLOB MEDIUMTEXT MEDIUMTEXT MEDIUMINT DECIMAL

CREATING Table
Create table table_name(column1_name datatype option, column2_name datatype option);

ALTER Table
Alter table table_name alter_options Drop_column add_column

118

CHAPTER -14

Database Handling With PHP


PHP/MySQL Function mysql_connect Open a connection to a MySQL Server
resource mysql_connect ( [string $server [,string $username [, string $password [, bool $new_link [, int $client_flags]]]]] ) Opens or reuses a connection to a MySQL server. Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?>

Example using hostname:port syntax


<?php // we connect to example.com and port 3307 $link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); // we connect to localhost at port 3307 $link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); }
119

echo 'Connected successfully'; mysql_close($link); ?>

mysql_connect() example using ":/path/to/socket" syntax


<?php // we connect to localhost and socket e.g. /tmp/mysql.sock //variant 1: ommit localhost $link = mysql_connect('/tmp/mysql', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); // variant 2: with localhost $link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?>

mysql_close Close MySQL connection


bool mysql_close ( [resource $link_identifier] ) mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used. Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Example
<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); }

echo 'Connected successfully'; mysql_close($link); ?>


120

The above example will output: Connected successfully

mysql_create_db Create a MySQL database


bool mysql_create_db ( string $database_name [, resource $link_identifier]) mysql_create_db() attempts to create a new database on the server associated with the pecified link identifier. Example The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue a sql CREATE DATABASE statement instead. <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } $sql = 'CREATE DATABASE my_db'; if (mysql_query($sql, $link)) { echo "Database my_db created successfully\n"; } else { echo 'Error creating database: ' . mysql_error() . "\n"; } ?> The above example will output something similar to: Database my_db created successfully

mysql_select_db Select a MySQL database


bool mysql_select_db ( string $database_name [, resource $link_identifier] ) Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database. Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Not connected : ' . mysql_error());
121

} // make foo the current db $db_selected = mysql_select_db('foo', $link); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); } ?>

mysql_query Send a MySQL query


resource mysql_query ( string $query [, resource $link_identifier] ) mysql_query() sends an unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier . Example <?php $result = mysql_query('SELECT * WHERE 1=1'); if (!$result) { die('Invalid query: ' . mysql_error()); } ?>

Valid Query
The following query is valid, so mysql_query() returns a resource. Example <?php // This could be supplied by a user, for example $firstname = 'fred'; $lastname = 'fox'; $query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'", mysql_real_escape_string($firstname), mysql_real_escape_string($lastname)); $result = mysql_query($query); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "<BR>"; $message .= 'Whole query: ' . $query; die($message); // Use result
122

// Attempting to print $result won't allow access to information in the resource // One of the mysql result functions must be used // See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc. while ($row = mysql_fetch_assoc($result)) { echo $row['firstname']; echo $row['lastname']; echo $row['address']; echo $row['age']; } // Free the resources associated with the result set // This is done automatically at the end of the script mysql_free_result($result); ?>

mysql_result Get result data


string mysql_result ( resource $result, int $row [, mixed $field] ) Retrieves the contents of one cell from a MySQL result set. When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result() . Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument. Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('SELECT name FROM work.employee'); if (!$result) { die('Could not query:' . mysql_error()); } echo mysql_result($result, 2); // outputs third employee's name mysql_close($link); ?>
123

mysql_fetch_row Get a result row as an enumerated array .


array mysql_fetch_row ( resource $result ) Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. Fetching one row with mysql_fetch_row() Example <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_row($result); echo $row[0]; // 42 echo $row[1]; // the email value ?>

mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both


array mysql_fetch_array ( resource $result [, int $result_type] ) Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. Example <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("ID: %s Name: %s", $row[0], $row[1]); } mysql_free_result($result); ?>

124

mysql_fetch_array() with MYSQL_ASSOC <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { printf("ID: %s Name: %s", $row["id"], $row["name"]); } mysql_free_result($result); ?> mysql_fetch_array() with MYSQL_BOTH <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error());

mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { printf ("ID: %s Name: %s", $row[0], $row["name"]); } mysql_free_result($result); ?> mysql_fetch_array() with MYSQL_BOTH <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { printf ("ID: %s Name: %s", $row[0], $row["name"]); }

mysql_free_result($result); ?>
125

mysql_fetch_field Get column information from a result and return as an object


object mysql_fetch_field ( resource $result [, int $field_offset] ) Returns an object containing field information. This function can be used to obtain information about fields in the provided query result. Example <?php $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$conn) { die('Could not connect: ' . mysql_error()); } mysql_select_db('database'); $result = mysql_query('select * from table'); if (!$result) { die('Query failed: ' . mysql_error()); } /* get column metadata */ $i = 0; while ($i < mysql_num_fields($result)) { echo "Information for column $i:<br />\n"; $meta = mysql_fetch_field($result, $i); if (!$meta) { echo "No information available<br />\n"; } echo "<pre> blob: max_length: $meta->blob $meta->max_length

multiple_key: $meta->multiple_key name: not_null: numeric: $meta->name $meta->not_null $meta->numeric

primary_key: $meta->primary_key
126

table: type: default: unique_key: unsigned: zerofill: </pre>"; $i++; }

$meta->table $meta->type $meta->def $meta->unique_key $meta->unsigned $meta->zerofill

mysql_free_result($result); ?>

mysql_field_seek Set result pointer to a specified field offset


bool mysql_field_seek ( resource $result, int $field_offset ) Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned. Example <?php $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$conn) { die('Could not connect: ' . mysql_error()); }

mysql_select_db('database'); $result = mysql_query('select * from table'); if (!$result) { die('Query failed: ' . mysql_error()); } /* get column metadata */ $i = 0; while ($i < mysql_num_fields($result)) { echo "Information for column $i:<br />\n"; $meta = mysql_fetch_field($result, $i); if (!$meta) { echo "No information available<br />\n"; } echo "<pre> blob: $meta->blob
127

max_length: $meta->max_length multiple_key: $meta->multiple_key name: not_null: numeric: $meta->name $meta->not_null $meta->numeric

primary_key: $meta->primary_key table: type: default: $meta->table $meta->type $meta->def

unique_key: $meta->unique_key unsigned: zerofill: </pre>"; $i++; } mysql_free_result($result); ?> $meta->unsigned $meta->zerofill

mysql_num_fields Get number of fields in result


int mysql_num_fields ( resource $result ) Retrieves the number of fields from a query. Example <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } /* returns 2 because id,email === two fields */ echo mysql_num_fields($result); ?>

128

mysql_num_rows Get number of rows in result


int mysql_num_rows ( resource $result ) Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows(). Example <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("database", $link); $result = mysql_query("SELECT * FROM table1", $link); $num_rows = mysql_num_rows($result); echo "$num_rows Rows<br>"; ?>

mysql_error Returns the text of the error message from previous MySQL operation
string mysql_error ( [resource $link_identifier] ) Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function. Example <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("nonexistentdb", $link); echo mysql_errno($link) . ": " . mysql_error($link). "<br>"; mysql_select_db("kossu", $link); mysql_query("SELECT * FROM nonexistenttable", $link); echo mysql_errno($link) . ": " . mysql_error($link) . "<br>"; ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist

129

mysql_affected_rows Get number of affected rows in previous MySQL operation


int mysql_affected_rows ( [resource $link_identifier] ) Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier Example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10'); printf("Records deleted: %d<br> ", mysql_affected_rows()); /* with a where clause that is never true, it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'); printf("Records deleted: %d<br>", mysql_affected_rows()); ?>

130

CHAPTER -15

Cookies & Session Management


Cookies
Cookies are sent with the HTTP headers,so setcookie() must be called before any output is generated. You can pass additional arguments to setcookie() to control cookie behavior. The third argument to setcookie() is an expiration time,expressed as an epoch timestamp. For example: this cookie expires at noon GMT on December 3, 2004:

setcookie('flavor','chocolate chip',1102075200);
If the third argument to setcookie() is missing (or empty),the cookie expires when the browser is closed. Also,many systems cant handle a cookie expiration time greater than 2147483647,because thats the largest epoch timestamp that fits in a 32-bit integer. The fourth argument to setcookie() is a path. The cookie is sent back to the server only when pages whose path begin with the specified string are requested. For example, the following cookie is sent back only to pages whose path begins with /products/ : setcookie('flavor','chocolate chip','','/products/'); The page thats setting this cookie doesnt have to have a URL that begins with /products/ , but the following cookie is sent back only to pages that do. The fifth argument to setcookie() is a domain. The cookie is sent back to the server only when pages whose hostname ends with the specified domain are requested. For example: the first cookie in the following code is sent back to all hosts in the com domain,but the second cookie is sent only with requests to the host jeannie. Example.com : setcookie('flavor','chocolate chip','','','.example.com'); setcookie('flavor','chocolate chip','','','jeannie.example.com'); If the first cookies domain was just example.com instead of .example.com , it would be sent only to the single host example.com (and not www.example.com or jeannie. example.com ). The last optional argument to setcookie() is a flag that if set to 1,instructs the browser only to send the cookie over an SSL connection. This can be useful if the cookie contains sensitive information,but remember that the data in the cookie is stored in the clear on the users computer. Different browsers handle cookies in slightly different ways,especially with regard to how strictly they match path and domain strings and how they determine priority between different cookies of
131

the same name. The setcookie() page of the online manual has helpful clarifications of these differences.

Reading Cookie Values You want to read the value of a cookie thats been previously set.
Look in the $_COOKIE superglobal array: if (isset($_COOKIE['flavor'])) { print "You ate a $_COOKIE[flavor] cookie."; } A cookies value isnt available in $_COOKIE during the request in which the cookie is set. In other words,the setcookie() function doesnt alter the value of $_COOKIE. On subsequent requests,however,each cookie is stored in $_COOKIE. If register_globals is on, cookie values are also assigned to global variables. When a browser sends a cookie back to the server,it sends only the value. You cant access the cookies domain,path,expiration time,or secure status through $_COOKIE because the browser doesnt send that to the server. To print the names and values of all cookies sent in a particular request,loop through the $_COOKIE array: foreach ($_COOKIE as $cookie_name => $cookie_value) { print "$cookie_name = $cookie_value<br>"; }

Deleting Cookies
You want to delete a cookie so a browser doesnt send it back to the server. Call setcookie() with no value for the cookie and an expiration time in the past: setcookie('flavor','',time()-86400); Its a good idea to make the expiration time a few hours or an entire day in the past, in case your server and the users computer have unsynchronized clocks. For example, if your server thinks its 3:06 P.M. and a users computer thinks its 3:02 P.M., a cookie with an expiration time of 3:05 P.M. isnt deleted by that users computer even though the time is in the past for the server. The call to setcookie() that deletes a cookie has to have the same arguments (except for value and time) that the call to setcookie() that set the cookie did,so include the path, domain, and secure flag if necessary.

132

Persistent Cookies
There are two kinds of cookies: persistent cookies and temporary cookies. 1. A persistent cookie is stored in a file on your computer. It remains there when you close Internet Explorer. The cookie can be read by the Web site that created it when you visit that site again. 2. A temporary or session cookie is stored only for your current browsing session. It is deleted from your computer when you close Internet Explorer. The default behavior of setcookie(name,value) is to set a cookie as a temporary cookie. To set a persistent cookie, we need to add another parameter to the setcookie() function call as in the following syntax: bool setcookie(string name, string value, int expire) where "expire" specifies when this cookie should be expired. If the expiration time is a future time, like 30 days from today, this cookie will be set as a persistent cookie. Note that "expire" should be represented in number of seconds since the epoch. The best way to set "expire" is use the time() function, which represents the current time in number of seconds since the epoch. Example, 30 days from today can be expressed as "time()+60*60*24*30". If "expire" is not given, a temporary cookie will be created. To show you how to set a persistent cookie, and how the cookie is store in a file, The following PHP script page, CookiePersisted.php: <?php $cookieName = "User"; $cookieValue = "Herong Yang"; $expiration = time()+60*60*24*30; setcookie($cookieName, $cookieValue, $expiration); print("<pre>\n"); print("Cookies added by the server:\n"); print(" $cookieName: $cookieValue\n"); print(" Expires at: $expiration\n"); print "</pre>\n"; ?> I opened this page with IE, I got: Cookies added by the server: User: Herong Yang Expires at: 1134531525

133

To find out in which file this cookie is stored in my computer, I clicked at IE "Tools" menu, selected "Internet Options...". and clicked the "Settings..." button in the "Temporary Internet files" section of the "General" tab. I saw where is my "Temporary Internet files folder". So I went to that folder, and saw a cookie file named something like "Cookie:user@localhost/". I double clicked on that file, and managed to open it in notepad: User Herong+Yang localhost/ 1024 3801469056 29753439 3934260416 29747404 *

PHP Session Variables


A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:
Example <?php session_start(); ?> <html>
134

<body> Statement </body> </html> The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session .

Storing a Session Variable


The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: Example <?php session_start(); $_SESSION['views']=1; // store session data ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> Output: Pageviews=1 In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: Example <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
135

Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?> You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy(); ?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

136

CHAPTER-16

PHP With Form and User Input


The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

PHP Form Handling


The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": <html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> Output could be something like this: Welcome John! You are 28 years old.

137

$_GET superglobal variable


The built-in $_GET superglobal variable is used to collect values from a form sent with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send
(Max 100 characters).

Example <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL sent to the server could look something like this: http://localhost/welcome.php?fname=Peter&age=37 The "welcome.php" file can now use the $_GET superglobal variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!

When to use method="get"?


When using method="get" in HTML forms, all variable names and values are displayed in the URL.

Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

Note: The get method is not suitable for large variable values; the value cannot exceed 100
characters.

$_POST superglobal variable


The built-in $_POST function is used to collect values in a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).

138

Example <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL will look like this: http://localhost/welcome.php The "welcome.php" file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old.

When to use method="post"?


Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. $_REQUEST superglobal variable The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST function can be used to collect form data sent with both the GET and POST methods. Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old.

PHP File Upload


With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br />
139

<input type="submit" name="submit" value="Submit" /> </form> </body> </html>

Notice the following about the HTML form above:


The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.

Create The Upload Script


The "upload_file.php" file contains the code for uploading a file: <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } ?> By using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this: $_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file
140

$_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Restrictions on Upload
In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } ?> Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg. echo "Error: " . $_FILES["file"]["error"] . "<br />"; }

Saving the Uploaded File


The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server. The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:
141

<?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>

142

The script above checks if the file already exists, if it does not, it copies the file to the specified folder. Note: This example saves the file to a new folder called "upload"

PHP Sending E-mails :


PHP allows you to send e-mails directly from a script. The mail() function allows you to send emails directly from a script.

Requirements
For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file. Installation The mail functions are part of the PHP core. There is no installation needed to use these functions. Runtime Configuration The behavior of the mail functions is affected by settings in the php.ini file. Mail configuration options: Name SMTP Default "localhost" Description Windows only: The DNS name or IP address of the SMTP server smtp_port "25" Windows only: The SMTP port number. Available since PHP 4.3 sendmail_from NULL Windows only: Specifies the "from" address to be used in email sent from PHP sendmail_path NULL Unix systems only: Specifies where the sendmail program can be found (usually /usr/sbin/sendmail or /usr/lib/sendmail) PHP_INI_SYSTEM PHP_INI_ALL PHP_INI_ALL Changeable PHP_INI_ALL

PHP Mail Functions PHP : indicates the earliest version of PHP that supports the function.

Function ezmlm_hash()

Description Calculates the hash value needed by the EZMLM mailing list system 3

PHP

mail()

Allows you to send emails directly from a script

3
143

The PHP mail() Function The PHP mail() function is used to send emails from inside a script. Syntax : mail(to,subject,message,headers,parameters) Parameter To Subject Description Required. Specifies the receiver / receivers of the email Required. Specifies the subject of the email. cannot contain any newline characters Message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters Headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n) Parameters Optional. Specifies an additional parameter to the sendmail program Note: This parameter

Note: For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.

PHP Simple E-Mail


The simplest way to send an email with PHP is to send a text email. In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail: <?php $to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>

PHP Mail Form


With PHP, you can create a feedback-form on your website. The example below sends a text message to a specified e-mail address:
144

<html> <body> <?php if (isset($_REQUEST['email'])) { $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail( "someone@example.com", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } else { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br /> Subject: <input name='subject' type='text' /><br /> Message:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>"; } ?> </body> </html>

145

CHAPTER-17

PHP Exception Handling


Exceptions are used to change the normal flow of a script if a specified error occurs

What is an Exception
With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:


The current code state is saved The code execution will switch to a predefined (custom) exception handler function Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

We will show different error handling methods:


Basic use of Exceptions Creating a custom exception handler Multiple exceptions Re-throwing an exception Setting a top level exception handler Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

Basic Use of Exceptions


When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block . If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Lets try to throw an exception without catching it: <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); }
146

return true; } //trigger exception checkNum(2); ?>

The code above will get an error like this: Fatal error : Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch


To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include: 1. Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" 2. Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" 3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information Lets try to trigger an exception with valid code: <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }

//trigger exception in a "try" block


147

try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; }

//catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?> The code above will get an error like this: Message: Value must be 1 or below

Example explained:
The code above throws an exception and catches it: 1. The checkNum() function is created. It checks if a number is greater than If it is, an exception is thrown 2. The checkNum() function is called in a "try" block 3. The exception within the checkNum() function is thrown 4. The "catch" block retrives the exception and creates an object ($e) containing the exception information 5.The error message from the exception is echoed by calling $e->getMessage() from the exception object . However, one way to get around the "every throw must have a catch" rule is to set a top level exception handler to handle errors that slip through.

Creating a Custom Exception Class


Creating a custom exception handler is quite simple. We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class. The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it.

148

Lets create an exception class: <?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; } } $email = "someone@example...com"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>

The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage().

149

Example explained: The code above throws an exception and catches it with a custom exception class: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid . 3. The $email variable is set to a string that is not a valid e-mail address 4. The "try" block is executed and an exception is thrown since the e-mail address is invalid 5. The "catch" block catches the exception and displays the error message

Multiple Exceptions
It is possible for a script to use multiple exceptions to check for multiple conditions. It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages: <?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; } } $email = "someone@example.com"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); }
150

//check for "example" in mail address if(strpos($email, "example") !== FALSE) { throw new Exception("$email is an example e-mail"); } } catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); } ?>

Example explained: The code above tests two conditions and throws an exception if any of the conditions are not met: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid . 3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example" 4. The "try" block is executed and an exception is not thrown on the first condition 5. The second condition triggers an exception since the e-mail contains the string "example" 6. The "catch" block catches the exception and displays the correct error message If there was no customException catch, only the base exception catch, the exception would be handled there .

Re-throwing Exceptions
Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block .

151

A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message: <?php class customException extends Exception { public function errorMessage() { //error message $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } $email = "someone@example.com"; try { try { //check for "example" in mail address if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); } } catch(Exception $e) { //re-throw exception throw new customException($email); } } catch (customException $e) { //display custom message
152

echo $e->errorMessage(); } ?> Example explained: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown: 1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage() function is created. This function returns an error essage if an e-mail address is invalid 3. The $email variable is set to a string that is a valid e-mail address, but contains the string "example" 4. The "try" block contains another "try" block to make it possible to re-throw the exception 5. The exception is triggered since the e-mail contains the string "example" 6. The "catch" block catches the exception and re-throws a "customException" 7. The "customException" is caught and displays an error message If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels". Set a Top Level Exception Handler The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions. <?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?> The output of the code above should be something like this: Exception: Uncaught Exception occurred In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions.

153

Rules for exceptions


Code may be surrounded in a try block, to help catch potential exceptions Each try block or "throw" must have at least one corresponding catch block Multiple catch blocks can be used to catch different classes of exceptions Exceptions can be thrown (or re-thrown) in a catch block within a try block

A simple rule: If you throw something, you have to catch it.

154

CHAPTER-18

PHP Filter
PHP filters are used to validate and filter data coming from insecure sources, like user input.

What is a PHP Filter?


A PHP filter is used to validate and filter data coming from insecure sources. To test, validate and filter user input or custom data is an important part of any web application. The PHP filter extension is designed to make data filtering easier and quicker.

Why use a Filter?


Almost all web applications depend on external input. Usually this comes from a user or another application (like a web service). By using filters you can be sure your application gets the correct input type. You should always filter all external data! Input filtering is one of the most important application security issues.

What is external data?


Input data from a form Cookies Web services data Server variables Database query results

Functions and Filters


To filter a variable, use one of the following filter functions:

1. filter_var() - Filters a single variable with a specified filter


2. filter_var_array() - Filter several variables with the same or different filters 3. filter_input - Get one input variable and filter it 4. filter_input_array - Get several input variables and filter them with the same or different filters In the example below, we validate an integer using the filter_var() function: <?php $int = 123; if(!filter_var($int, FILTER_VALIDATE_INT)) {
155

echo("Integer is not valid"); } else { echo("Integer is valid"); } ?>

The code above uses the "FILTER_VALIDATE_INT" filter to filter the variable. Since the integer is valid, the output of the code above will be: "Integer is valid". If we try with a variable that is not an integer (like "123abc"), the output will be: "Integer is not valid".

PHP Filter Functions


PHP : indicates the earliest version of PHP that supports the function. Function filter_has_var() filter_id() filter_input() filter_input_array() filter_list() filter_var_array() filter_var() Description Checks if a variable of a specified input type exist Returns the ID number of a specified filter Get input from outside the script and filter it Get multiple inputs from outside the script and filters them Returns an array of all supported filters Get multiple variables and filter them Get a variable and filter it PHP 5.2.6 5.2.6 5.2.6 5.2.6 5.2.6 5.2.6 5.2.6

PHP filter_has_var() Function


Definition and Usage The filter_has_var() function checks if a variable of a specified input type exist. Returns TRUE on success or FALSE on failure. Syntax filter_has_var(type, variable) Parameter Type Description Required. Specifies the type to check for Possible input types: INPUT_GET INPUT_POST
156

Variable

INPUT_COOKIE INPUT_SERVER INPUT_ENV

Required. Specifies the variable to check

Example In this example the input variable "name" is sent to the PHP page: <?php if(!filter_has_var(INPUT_GET, "name")) { echo("Input type does not exist"); } else { echo("Input type exists"); } ?> The output of the code should be something like this: Input type exists

PHP filter_id() Function


Definition and Usage The filter_id() function returns the ID number of a specified filter. Returns the filter ID number on success, or NULL if the filter does not exist. Syntax filter_id(filter_name) Parameter filter_name Description Required. Specifies the filter to get the id from. Must be a filter name (not a filter ID name), use the filter_list() function for name of all supported filters Example <?php echo(filter_id("validate_email")); ?>
157

The output of the code should be: 274

PHP filter_input() Function


Definition and Usage The filter_input() function filters gets input from outside the script and filters it. This function is used to validate variables form insecure sources such as user input. This function can get input from several sources: INPUT_GET INPUT_POST INPUT_COOKIE INPUT_ENV INPUT_SERVER INPUT_SESSION (Not yet implemented) INPUT_REQUEST (Not yet implemented)

Returns the filtered data on success, FALSE on failure or NULL if the "variable" parameter is not set. Syntax filter_input(input_type, variable, filter, options) Parameter input_type Variable Filter Description Required. Specifies the input type. See possible types in list above Required. Specifies the variable to filter Optional. Specifies the ID of the filter to use. Default is FILTER_SANITIZE_STRING. A filter ID can be an ID name (like FILTER_VALIDATE_EMAIL) or an ID number (like 274) Options Optional. Specifies an associative array of flags/options or a single flag/option. Check each filter for possible options and flags

Example In this example we use the filter_input() function to filter a POST variable. The received POST variable is a valid e-mail address:
158

<?php if (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)) { echo "E-Mail is not valid"; } else { echo "E-Mail is valid"; } ?> The output of the code should be: E-Mail is valid

PHP filter_input_array() Function


Definition and Usage The filter_input_array() function filters gets multiple inputs from outside the script and filters them. This function is useful for filtering many input variables without calling filter_input() over and over. This function can get input from several sources: INPUT_GET INPUT_POST INPUT_COOKIE INPUT_ENV INPUT_SERVER INPUT_SESSION (Not yet implemented) INPUT_REQUEST (Not yet implemented)

Returns an array of filtered data on success, FALSE on failure. Syntax filter_input(input_type, args)

Parameter input_type args

Description Required. Specifies the input type. See possible types in list above Optional . Specifies an array of filter arguments. A valid array key is a variable name and a valid value is a filter ID, or an array specifying the filter, flags and options.
159

This parameter can also be a single filter ID, if so, all values in the input array are filtered by the specified filter A filter ID can be an ID name (like FILTER_VALIDATE_EMAIL) or an ID number (like 274) Example In this example we use the filter_input_array() function to filter three POST variables. The received POST variables is a name, an age and an e-mail address: <?php $filters = array ( "name" => array ( "filter"=>FILTER_CALLBACK, "flags"=>FILTER_FORCE_ARRAY, "options"=>"ucwords" ), "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array( "min_range"=>1, "max_range"=>120 ) ), "email"=> FILTER_VALIDATE_EMAIL, ); print_r(filter_input_array(INPUT_POST, $filters)); ?> The output of the code should be: Array ( [name] => Peter [age] => 41 [email] => peter@example.com )
160

PHP filter_list() Function


Definition and Usage The filter_list() function returns an array of all supported filters. Syntax Tips and Notes

filter_list()
Note: The results of this function is not the filter ID, but filter names. Use the filter_id() function to get the filter ID . Example <?php print_r(filter_list()); ?> The output of the code should be something like this: Array ( [0] => int [1] => boolean [2] => float [3] => validate_regexp [4] => validate_url [5] => validate_email [6] => validate_ip [7] => string [8] => stripped [9] => encoded [10] => special_chars [11] => unsafe_raw [12] => email [13] => url [14] => number_int [15] => number_float [16] => magic_quotes [17] => callback )
161

PHP filter_var_array() Function


Definition and Usage The filter_var_array() function gets multiple variables and optionally filters them This function is useful for filtering many values without calling filter_var() over and over. Returns an array of values of the requested variables on success or FALSE on failure. Syntax : filter_var_array(array, args) Parameter Array Args Description Required. Specifies an array with string keys containing the data to filter Optional. Specifies an array of filter arguments. A valid array key is a variable name and a valid value is a filter ID, or an array specifying the filter, flags and options. This parameter can also be a single filter ID, if so, all values in the input array are filtered by the specified filter A filter ID can be an ID name (like FILTER_VALIDATE_EMAIL) or an ID number (like 274)

Example <?php $arr = array ( "name" => "peter griffin", "age" => "41", "email" => "peter@example.com", ); $filters = array ( "name" => array ( "filter"=>FILTER_CALLBACK, "flags"=>FILTER_FORCE_ARRAY, "options"=>"ucwords" ), "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array
162

( "min_range"=>1, "max_range"=>120 ) ), "email"=> FILTER_VALIDATE_EMAIL, );

print_r(filter_var_array($arr, $filters)); ?> The output of the code should be: Array ( [name] => Peter Griffin [age] => 41 [email] => peter@example.com )

PHP filter_var() Function


Definition and Usage The filter_var() function filters a variable with the specified filter. Returns the filtered data on success or FALSE on failure. Syntax: Parameter Variable Filter filter_var(variable, filter, options) Description Required. Specifies the variable to filter Optional. Specifies the ID of the filter to use. Default is ILTER_SANITIZE_STRING. A filter ID can be an ID name (like FILTER_VALIDATE_EMAIL) or an ID number (like 274) Options Optional. Specifies an associative array of flags/options or a single flag/option. Check each filter for possible options and flags

163

Example <?php if(!filter_var("someone@example.com", FILTER_VALIDATE_EMAIL)) { echo("E-mail is not valid"); } else { echo("E-mail is valid"); } ?> The output of the code should be: E-mail is not valid

PHP Filters
ID Name FILTER_CALLBACK FILTER_SANITIZE_STRING FILTER_SANITIZE_STRIPPED FILTER_SANITIZE_ENCODED Description Call a user-defined function to filter data Strip tags, optionally strip or encode Alias of "string" filter URL-encode string, optionally strip or encode special characters FILTER_SANITIZE_SPECIAL_CHARS HTML-escape '"<>& and characters with ASCII value less than 32 FILTER_SANITIZE_EMAIL Remove all characters, except letters, digits and !#$%&'*+-/=?^_`{|}~@.[] FILTER_SANITIZE_URL Remove all characters, except letters

_.+!*'(),{}|\\^~[]`<>#%";/?:@&= FILTER_SANITIZE_NUMBER_INT Remove all characters, except digits and + -

FILTER_SANITIZE_NUMBER_FLOAT Remove all characters, except digits, +- and optionally ., eE FILTER_SANITIZE_MAGIC_QUOTES FILTER_UNSAFE_RAW Apply addslashes() Do nothing, optionally strip or encode special characters. FILTER_VALIDATE_INT Validate value as integer, optionally from the specified range
164

FILTER_VALIDATE_BOOLEAN

Return TRUE for "1", "true", "on" and yes, FALSE for 0 false , off,no , and , NULL otherwise

FILTER_VALIDATE_FLOAT FILTER_VALIDATE_REGEXP

Validate value as float Validate value against regexp, a Perl-Compatible regular expression.

FILTER_VALIDATE_URL

Validate value as URL, optionally with required components

FILTER_VALIDATE_EMAIL FILTER_VALIDATE_IP

Validate value as e-mail Validate value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges.

165

CHAPTER-19

Creating Libraries
Libraries
When we use the term "Libraries" we are normally referring to the classes that are located in the libraries directory and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can create your own libraries within your application/libraries directory in order to maintain separation between your local resources and the global framework resources. As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in your application/libraries folder.In summary: You can create entirely new libraries. You can extend native libraries. You can replace native libraries. The page below explains these three concepts in detail. Note: The Database classes can not be extended or replaced with your own classes. All other classes are able to be replaced/extended.

Storage
Your library classes should be placed within your application/libraries folder, as this is where CodeIgniter will look for them when they are initialized.

Naming Conventions
File names must be capitalized. For example: Myclass.php Class declarations must be capitalized. For example: class Myclass Class names and file names must match.

The class File


Classes should have this basic prototype (Note: We are using the name Someclass purely as an example): <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Someclass { public function some_function() { } /* End of file Someclass.php */
166

Using your Class


From within any of your Controller functions you can initialize your class using the standard: $this->load->library('someclass'); Where someclass is the file name, without the ".php" file extension. You can submit the file name capitalized or lower case. CodeIgniter doesn't care. Once loaded you can access your class using the lower case version: $this->someclass->some_function(); // Object instances will always be lower case

Passing Parameters When Initializing Your Class


In the library loading function you can dynamically pass data as an array via the second Parameter and it will be passed to your class constructor: $params = array('type' => 'large', 'color' => 'red'); $this->load->library('Someclass', $params); If you use this feature you must set up your class constructor to expect data: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Someclass { public function __construct($params) { // Do something with $params } } ?> You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name and store it in your application/config/ folder. Note that if you dynamically pass parameters as described above, the config file option will not be available. Utilizing CodeIgniter Resources Within Your Library To access CodeIgniter's native resources within your library use the get_instance() function. This function returns the CodeIgniter super object.Normally from within your controller functions you will call any of the available CodeIgniter functions using the $this construct: $this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url'); etc.

167

$this, however, only works directly within your controllers, your models, or your views. If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows: First, assign the CodeIgniter object to a variable: $CI =& get_instance(); Once you've assigned the object to a variable, you'll use that variable instead of $this: $CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url') Note: You'll notice that the above get_instance() function is being passed by reference: $CI =& get_instance(); This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

Replacing Native Libraries With Your Versions:


Simply by naming your class files identically to a native library will cause CodeIgniter to use it instead of the native one. To use this feature you must name the file and the class declaration exactly the same as the native library. For example, to replace the native Email library you'll create a file named application/libraries/Email.php, and declare your class with: class CI_Email { } Note that most native classes are prefixed with CI_ . To load your library you'll see the standard loading function: $this->load->library('email'); Note: At this time the Database classes can not be replaced with your own versions.

Extending Native Libraries


If all you need to do is add some functionality to an existing library - perhaps add a function or two - then it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: The class declaration must extend the parent class. Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
168

For example, to extend the native Email class you'll create a file named application/libraries/MY_Email.php, and declare your class with: class MY_Email extends CI_Email { }

Note: If you need to use a constructor in your class make sure you extend the parent constructor:
class MY_Email extends CI_Email { public function __construct() { } parent::__construct(); }

Loading Your Sub-class


To load your sub-class you'll use the standard syntax normally used. DO NOT include your prefix. For example, to load the example above, which extends the Email class, you will use: $this->load->library('email'); Once loaded you will use the class variable as you normally would for the class you are extending. In the case of the email class all calls will use: $this->email->some_function();

Setting Your Own Prefix


To set your own sub-class prefix, open your application/config/config.php file and look for this item: $config['subclass_prefix'] = 'MY_'; Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

169

CHAPTER-19

Introduction To Ajax
AJAX = Asynchronous JavaScript and XML
AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user - friendly.

AJAX is based on Internet standards


AJAX is based on the following web standards: 1. JavaScript 2. XML 3. HTML 4. CSS AJAX applications are browser- and platform-independent.

AJAX is about better Internet-applications


Internet-applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop. However, Internetapplications are not always as "rich" and user-friendly as traditional desktop applications. With AJAX, Internet applications can be made richer and more user-friendly. AJAX is based on existing standards. These standards have been used by developers for several years.

PHP With AJAX


There is no such thing as an AJAX server. AJAX runs in your browser. AJAX uses HTTP requests to request small pieces of information from the server, instead of whole pages.

AJAX XMLHttpRequest

AJAX uses the XMLHttpRequest object

To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run
170

slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background. The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).

AJAX - Browser support


All new browsers use the built-in JavaScript XMLHttpRequest object to create an XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).

The JavaScript code for creating an XMLHttpRequest object:


if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); } if (window.ActiveXObject) { // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); }

PHP Example - AJAX Suggest


AJAX can be used to create more interactive applications.

AJAX Suggest example


The following AJAX example will demonstrate how a web page can communicate with a web server while a user enters data into an HTML form. Type a name in the input field below: First name: Suggestions: Example explained - The HTML page The HTML page contains a link to an external JavaScript, a simple HTML form, and a span element:

171

<html> <head> <script type="text/javascript" src="clienthint.js"></script> </head> <body> <form> First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html> The HTML form above has an input field called "txt1". An event attribute for this field defines a function to be triggered by the onkeyup event. The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server. When a user inputs data, the function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time a user moves the finger away from a keyboard key inside the input field, the function showHint is called.

Example explained - The JavaScript code


This is the JavaScript code, stored in the file "clienthint.js": var xmlhttp function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Your browser does not support XMLHTTP!"); return; }
172

var url="gethint.php"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("GET",url,true); xmlhttp.send(null); } function stateChanged() { if (xmlhttp.readyState==4) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } function GetXmlHttpObject() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); } if (window.ActiveXObject) { // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); } return null; } The showHint() function The showHint() function above is executed every time a character is entered in the "txt1" input field. If there is input in the input field (str.length > 0), the showHint() function executes

173

The following: Calls the GetXmlHttpObject() function to create an XMLHTTP object Defines the URL (filename) to send to the server Adds a parameter (q) to the URL with the content of the input field Adds a random number to prevent the server from using a cached file Each time the readyState property changes, the stateChanged() function will be executed Opens the XMLHTTP object with the given URL Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the txtHint placeholder.

The GetXmlHttpObject() function


The showHint() function above calls a function named GetXmlHttpObject(). The purpose of the GetXmlHttpObject() function is to solve the problem of creating different XMLHTTP objects for different browsers.

The stateChanged() function


The stateChanged() function executes every time the state of the XMLHTTP object changes. When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with the response text. Example explained - The PHP page The code in the "gethint.php" checks an array of names and returns the corresponding names to the client: <?php // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty";
174

$a[]="Linda"; $a[]="Nina"; $q=$_GET["q"]; //get the q parameter from URL if (strlen($q) > 0) //lookup all hints from array if length of q>0 { $hint=""; for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) { if ($hint=="") { $hint=$a[$i]; } else { $hint=$hint." , ".$a[$i]; } } } } // Set output to "no suggestion" if no hint were found // or to the correct values if ($hint == "") { $response="no suggestion"; } else { $response=$hint; } echo $response; ?>

175

If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
1. Find a name matching the characters sent from the JavaScript 2. If no match were found, set the response string to "no suggestion" 3. If one or more matching names were found, set the response string to all these names 4. The response is sent to the "txtHint" placeholder

176

CHAPTER-20

PHP.INI Configuration
Activating extensions
A number of different extensions are available for PHP. OnUNIX systems, extensions need to be built at compile-time; on Windows, binaryDLL files are included with the PHP distributions. The extension_dir variable contains the name of the directory PHPshould look in for these extensions. extension_dir = "C:\Program Files\Internet Tools\Apache\bin\php4\extensions" The Windows PHP distribution comes with over 20 differentextensions, and they're all listed (though commented out) in the php.ini file. To activate a particularextension, simply remove the semicolon at the beginning of the line and restartthe server. To deactivate an extension (say, for better performance), add asemicolon to comment out the line. If the extension is not listed in the file, use the extension variable, and pass it the filename of the corresponding DLL. extension=php_domxml.dll extension=php_dbase.dll

Setting extension-specific variables


Extension-specific variables are stored in separate sectionsof the configuration file. For example, all the variables related to the MySQLextension should be in the [MySQL] section of the php.ini file.If you're going to use PHP's mail() function, there arethree variables you may need to set. The SMTP and sendmail_from variables (on Windows) or the sendmail_path variable (on UNIX) are used when sending e-mailmessages through PHP's mail() function. On Windows, these variables set theSMTP server to be used and the From:address to display in e-mail messages; on UNIX, thesendmail_path variable sets the path of the MTA (mail transfer agent)for mail delivery: SMTP = myserver.localnet.com sendmail_from = me@localhost.com sendmail_path = /usr/sbin/sendmail The java.class.path,java.home, java.library and java.library.pathvariables all set the directories to look in for Java classes and libraries.These values are used by the Java extension, so make sure you set themcorrectly if you want PHP to integrate correctly with your Java applications: java.class.path = .\php_java.jar java.home = c:\jdk
177

java.library = c:\jdk\jre\bin\hotspot\jvm.dll java.library.path = .\ The session.save_pathvariable specifies the temporary directory for session information. Normally,this defaults to /tmp, but since thisdirectory does not exist on Windows systems, you must reset it to the appropriateWindows temporary directory or else the session handler will pop up unsightlyerror messages whenever you call session_start(). You can also control how longa session cookie remains valid, in seconds, with the session.cookie_lifetime variable: session.save_path = c:\windows\temp session.cookie_lifetime = 1800

Security settings
There are a number of variables in php.ini related to thesecurity of your PHP installation. The most interesting of these is the safe_mode variable, recommended for ISPsand shared-hosting services as it limits the things a user can do with PHP: safe_mode = Off With safe mode turned on, you can specify which directoriesare searched for files with thesafe_mode_include_dirvariable. You can also restrict the types of programs a PHP script can run withthe exec() command by placing the program binaries in a special directory andtelling PHP about it via the safe_mode_include_dirvariable. Only binaries in this directory will be accessible via exec(): safe_mode_include_dir = /usr/local/lib/php/safe-include safe_mode_exec_dir = /usr/local/lib/php/safe-bin You can restrict file operations with the open_basedir variable, which sets thenamed directory as the root for file operations. When this value is set, filesoutside the named directory tree will be inaccessible to PHP. This is a goodway to restrict a shared system's users to their own home or Web directories: open_basedir = /home/web/ The max_execution_timevariable sets the maximum number of seconds PHP will wait for a script tofinish executing before forcibly terminating it. This comes in handy when yourscript spirals into an infinite loop. However it can trip you up if you have alegitimate activity that takes time to completefor example, a large fileupload. In such situations you should consider increasing this value to avoidhaving PHP shut down your script when it's in the middle of somethingimportant. max_execution_time = 90 Speaking of uploads, now let's look at how you configure foruploads and form variables.

178

file_uploads = On upload_max_filesize = 2M If you're not interested in uploading files but use a lot offorms in your PHP application, there are two variables that will be of particularinterest to youfirst, the register_globalsvariable, the cause of much heartache to longtime PHP developers. In PHP 3.x,this variable was On by default, leading form variables to be automaticallyconverted to PHP variables when a form was submitted. Security concerns led to this variable being set to Off inPHP 4.x. As a result, form variables could only be accessed through the special$_GET and $_POST arrays. This broke many scripts written in PHP 3.x, and forceddevelopers to rewrite and retest their scripts. For example, the value enteredinto the field <input type="text" name="email"> wouldbe available as $email in a PHP 3.x script, but as $_POST['email'] or$_GET['email'] in a PHP 4.x script. You should generally set this variable to Off, as thatoffers greater security against script attacks through forms. For compatibilitywith older PHP 3.x scripts, turn it On: register_globals = Off Also related to form submission is the post_max_size variable, which controls the maximum amount of datathat PHP will accept in a single form submission with the POST method. It'sunlikely you'll ever need to increase this from the default value of 8 MB;instead, you should probably reduce it to a more realistic figure. However, ifyou're planning on using the file upload features of PHP, keep this valuegreater than the value of upload_max_filesize. post_max_size = 8M New in PHP 5 is the max_input_timevariable, which sets a time limit in seconds for receiving input data throughPOST, GET, and PUT. If your application is running over a slow link, it issometimes worthwhile to explore increasing this value to allow the script moretime to receive input data. max_input_time = 90

Tweaking performance
There are even some values you can tweak to improve the performance of the PHP interpreter. In order to avoid runaway scripts using upall the available memory on the system, PHP allows you to define limits onmemory usage. This value is set via the memory_limitvariable, and it specifies the maximum memory a single script may use: memory_limit = 8M The memory_limitvalue should generally be higher than the value of post_max_size.

179

Another thing you can do to improve performance is disablethe $argc and $argv variables, which store the number of arguments passed to anapplication on the command line as well as the actual argument values. register_argc_argv = false Similarly, disable the $HTTP_GET_VARS and $HTTP_POST_VARSarrays, since you're unlikely to use them in the modern world of $_GET and$_POST. Disabling these features can improve performance, but is only availablein PHP 5 via the register_long_arraysvariable. register_long_arrays = false

The ini_set() function


Finally, a note on the ini_set() function. While PHP readsall its settings at startup from thephp.iniconfiguration file, it also lets you override those settings on a per-scriptbasis with the very cool ini_set() function. This function accepts twoarguments: the name of the configuration variable to alter, and its new value.Here is an example, which increases the maximum execution time for the scriptin which it appears: <?php ini_set('max_execution_time', 600); ?> The setting only affects the script in which it is set. Oncethe script has completed executing, the original value of the variable isrestored automatically. If your PHP applications are running on a shared server,it's unlikely that you will have access to the master php.ini configuration file. The ini_set() function can helpsignificantly by allowing you to reconfigure PHP on the fly for your specialneeds.

Configure a virtual directory using WAMP


As a web developer many want to test their developments on their local machines. But when it comes to dealing with PHP and MySQL you will need a web server (software) to test the sites you make. Normally we would have to download Apache from www.apache.org , MySQL from MySQL.net and configure these separately to work with each other on our local machine. Also if you want to administer MySQL on the browser you will have to install PHPMyAdmin which is a burden for the novice user. To tackle these problems there are several packaged solutions on the net. Popular and more robust one is WAMP server. Let see step by step on how to create a root folder for our new web site that has to be built using PHP.

180

Step 1: Easiest way! After installing WAMP on your local machine (You should see a white Speedo meter on the notification area) goes the folder where WAMP resides (If you install it on you C: partition then it is C:/wamp/). The folder structure is as follows,

Go inside the www folder and create a new folder inside it called "TestSite". This is the rot folder of your web site. Better if you do not put spaces. Open up a simple notepad insert the following on it (don't copy the formatting. Just type it), <?php echo "Hello World!"; ?> Then same it inside the newly created folder and name it index.php. Go to your browser and call http://localhost/TestSite/ If you see something like this then you are ready to do building rest of your dynamic web site. document and

Step2: Assigning a root folder outside "www".


Well, if we want separate our web site folders from the WAMP server folder and put somewhere else in the hard drive then procedure gets a bit tricky for the beginners. First create the folder you want as the web site root folder. Let's say D:/MyNewTest/ Now we have to tell the WAMP server that this folder contains a web site and it should come up when the URL is called through the browser right?
181

Ok, first click on the little Speedometer icon on the notification area. Then go to, Apache > Alias directories > Add an alias

Then you will be asked to give an alias to the site, this is what you type after http://localhost/ in the browser. Previous one was "TestSite" which is actually the folder name itself. But this is not necessary in this case. You can put anything. But don't use spaces or dots.

Let's put "MySite".


182

Then you will be asked what is the actual folder that MySite alias point to

Give the following, D:/MyNewTest/ Note the forward slashes.

183

Now press enter to close the DOS prompt.Go to your browser and type the http://localhost/MySite/ You will see the root index now. Put the notepad file we created earlier to "D:/MyNewTest"and refresh the browser page to test the PHP.

184

You might also like