Professional Documents
Culture Documents
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
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: "<" represents the < sign. ">" represents the > sign. "" represents the " mark. å (in decimal) represents the letter "a" with a small circle above it. И (in decimal) represents the Cyrillic capital letter "I". 水 (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.
<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.
12
CHAPTER -2
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}
Font-style
Font-weight
Specifies the weight of Lighter boldness of the font . Normal Bold Bolder 100-900
P{font-weight:bold}
Font-Size
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
image:url(..images/sand.gif);
image will be repeat-y placed. Backgroundattachment no-repeat Body {background- image: url(../images/sand.gif); background-attachment: fixed}
Backgroundposition
Specifies
the Vertical %
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
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
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.
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.
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.
23
CHAPTER- 4
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.
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'; }
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.
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 .
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
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
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.
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 + *
Value The sum of the two operands. The difference between the two operands The product of the two operands.
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: +=, -=, *=, /=, %=,
For example:
$name = "Judy"; $name_alias =& $name; $name_alias = "Jonathan"; print $name;
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
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
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:
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
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
To add new String on the left use following version $my_string_var=$new_addition . $my_string_var;
44
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.
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
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"); ?>
ucfirst()
Make a string's first character uppercase
49
Example
<?php $foo = 'hello world!'; $foo = ucfirst($foo); // 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!
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 ?>
51
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred. Syntax date( format , timestamp )
Description Required. Specifies the format of the timestamp Optional. Specifies a timestamp. Default is the current date and time
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
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 />"); ?>
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
PHP_INI_ALL
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
Syntax getdate(timestamp)
Parameter Description timestamp Optional. Specifies the time in Unix time format Example <?php print_r(getdate()); ?>
[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]"); ?>
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()); ?>
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.
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;
$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"];
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 )
66
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.
68
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:
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
71
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 ... }
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) ?>
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
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
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
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(); ?>
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 ?>
<?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';
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"; }
//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
$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;}
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.
{ 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.
105
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"); ?>
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); ?>
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"; } ?>
// FALSE from fopen will issue warning and result in infinite loop here while (!feof($file)) { } fclose($file); ?>
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); ?>
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 '\' ?>
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); ?>
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.
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.
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.
servers and clients, and trying to circumvent it by modifying the definitions of the tables in the mysql database does not work .
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 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
Example
<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); }
} // make foo the current db $db_selected = mysql_select_db('foo', $link); if (!$db_selected) { die ('Can\'t use foo : ' . 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); ?>
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
primary_key: $meta->primary_key
126
mysql_free_result($result); ?>
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
unique_key: $meta->unique_key unsigned: zerofill: </pre>"; $i++; } mysql_free_result($result); ?> $meta->unsigned $meta->zerofill
128
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
130
CHAPTER -15
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 *
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 .
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
137
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!
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.
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.
$_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 />"; }
<?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"
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()
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.
<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
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.
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 { 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.
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
154
CHAPTER-18
PHP Filter
PHP filters are used to validate and filter data coming from insecure sources, like user input.
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".
Variable
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
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
Returns an array of filtered data on success, FALSE on failure. Syntax filter_input(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
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
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
print_r(filter_var_array($arr, $filters)); ?> The output of the code should be: Array ( [name] => Peter Griffin [age] => 41 [email] => peter@example.com )
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_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
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.
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.
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(); }
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 XMLHttpRequest
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).
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.
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.
$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
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
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
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.
Then you will be asked what is the actual folder that MySite alias point to
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