Vous êtes sur la page 1sur 131

UNIT I CORE COURSE - XV - PHP & SCRIPTING LANGUAGES UNIT I: VB Script and Java Script: Language structure control

l structure - Procedures and functions - Error handling. UNIT II: VB Script: Input & Output - Data Validation Integration with Forms Activex Control & Scripting UNIT III: Java Script: Form Validation SSI and Cookies Frames and Windows MIME Types - Plugins UNIT IV: PHP: Server side scripting Language: Basic syntax - Types - Variables - Constants - Expressions Operators - Control Structures UNIT V: PHP: Functions - Classes and Objects - HTML forms - HTTP authentication with PHP - Cookies - Handling file uploads - Using remote files - Connection handling Database Connections BOOK(S) FOR STUDY: 1. Christopher J.Goddard, Mark White, Mastering VB Script, Galgotia publications, New Delhi, 2. Mary Jane Mara, The ABCs of Javascript, Lee Purcell 3. Steven Holzner, PHP: The Complete Reference JAVA SCRIPT and VB SCRIPT
Java and JavaScript are not the same. Nor are they competitors to each other. Java is an object-oriented programming language. JavaScript is a scripting language. JavaScript is embedded within your HTML code. It is an extension to your HTML code. You can change the appearance and behavior of your Web pages dynamically using JavaScript. You can process mouse events such as mouse click or the mouse moving over a certain part of the Web page and initiate certain actions on such events. For example, you can display different background bitmaps, depending on the day of the week. You can process form data when the user clicks the submit button and alert the user of any invalid data. JavaScript supports dynamic binding. With JavaScript it is not necessary to declare the type. If you do not declare the type of the variable, JavaScript interprets it at runtime, based on the context in which it is used. For example, if a variable is used to perform addition of numbers, it is interpreted as a number. If a variable is used to perform string concatenation, it is interpreted as a string. Such loose binding makes JavaScript lightweight and portable. Similarly, if you declare functions in JavaScript, it is not necessary to specify the type of the return value of the function. What is JavaScript?

JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license

What can a JavaScript do?

window document history form date math string radio checkbox select button text, textarea location

Base class for the document object Contains information about all HTML properties inside the current page Contains browser's URL history list Contains information about the defined form Contains date information, including system date function Includes math constants and functions Contains information about string functions Contains information about a form's radio button Contains information about a form's checkbox button Represents a form's list as an array Contains information about a form's button; it could represent a form's reset, submit, or custom button Contains information about a form's text box Contains information about the current URL location

JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer NOTE

JavaScript Language Structure


Listing 1.1 shows an example of HTML code that includes a JavaScript function. The JavaScript code is identified by the <SCRIPT> tag. The code is embedded between the beginning and ending <SCRIPT> tags. Listing 1.1. Basic structure of a JavaScript function.
<SCRIPT LANGUAGE="JavaScript"> <!-function <function_name> { ... } // --> </SCRIPT>

You can use Java to develop non-Web-based applications. Since JavaScript and VBScript are extensions to HTML, they are used primarily to create Web applications. However, VBScript can be used as a component in other Windows applications.

JavaScript Objects
JavaScript is an object-based scripting language. Even though it is objectbased, JavaScript does not support inheritance. You can define your own objects in JavaScript and use them together with JavaScript's built-in objects to write Web pages. As of this writing, there are a total of 17 JavaScript objects. Table 1.1 lists them. Table 1.1. JavaScript objects. Object Meaning navigator Base class for all HTML objects

Listing 1.2 shows a JavaScript-based HelloWorld function. Listing 1.2. JavaScript HelloWorld function.

<SCRIPT LANGUAGE="JavaScript"> <!-function HelloWorld() { alert("Hello World!"); } // --> </SCRIPT>

Operator Meaning != > >= < <= Non-equality Greater than Greater than or equal to Less than Less than or equal to

The LANGUAGE attribute indicates the scripting language that is used. The browser interprets the code accordingly. Microsoft Internet Explorer 3.0 can interpret both JavaScript and VBScript. Netscape Navigator can interpret only JavaScript. NOTE Although currently only Microsoft Internet Explorer supports VBScript, other browsers are expected to include support for interpreting VBScript code. JavaScript functions can be placed anywhere inside the HTML code, including the HEAD and BODY sections. It is recommended you place all your functions and procedures in one location, usually toward the end of the BODY section, before the </BODY> tag.

Table 1.4. JavaScript logical operators. Operator Meaning && || ! Logical AND Logical OR Logical NOT

Table 1.5. JavaScript bit operators. Operator Meaning & Bitwise AND Bitwise OR Bitwise XOR | ^

JavaScript Operators
JavaScript operators include arithmetic, comparison, logical, and bit operators. Table 1.2. JavaScript arithmetic operators. Operator Meaning + * / ++ -% Addition Subtraction/negation Multiplication Division Increment Decrement Modulus

A single = is the assignment operator. It is used to store a value into a variable.

JavaScript Flow of Control Statements


Statement Table 1.6. JavaScript flow of control statements. Meaning

Table 1.3. JavaScript comparison operators.

For ([initial_expression;] Execute the code within the [condition;][increment_expression]) loop for N times where N is { specified in the For loop statement 1 ... statement N }

For Each...Next

Execute the code within the loop for each item in the specified collection If...Else statement

condition can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed. statements1 and statements2 can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces. Here's an example:
if (weather == 'good') { go_out(we); have_a_picnic(we); do_cartwheels(Lisa); } else { stay_in(we); watch_TV(Catherine); }

If (condition) { statement 1... statement N} [else { statement 2}] while (condition) { statement 1 ... statement N }

Execute the code within the loop as long as the specified condition is true

If/Else Statements if statements execute a set of commands if a specified condition is true. If the condition is false, another set of statements can be executed through the use of the else keyword. The main idea behind if a statement is embodied by the sentence: "If the weather's good tomorrow, we'll go out and have a picnic and Lisa will do cartwheels -- else, we'll stay in and Catherine will watch TV." As you can see, the idea is quite intuitive and, surprisingly enough, so is the syntax:
if (condition) { statements1 }

Loops
Loops are an incredibly useful programming tool. Loops handle repetitive tasks extremely well, especially in the context of consecutive elements. Arrays immediately spring too mind here, since array elements are numbered consecutively. It would be quite intuitive (and equally practical), for instance, to write a loop that added 1 to each element within an array. Don't worry if this doesn't make a lot of sense now, it will, after you finish reading the tutorial. The two most common types of loops are for and while loops: for Loops A for loop constitutes a statement which consists of three expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop. A for loop resembles the following: for (initial-expression; condition; increment-expression) { statements }

-orif (condition) { statements1 } else { statements2 }

The initial-expression is a statement or variable declaration. (See the section on variables for more information.) It is typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. The condition is evaluated on each pass through the loop. If this condition evaluates to true, the statements in statements are performed. When the condition evaluates to false, the execution of the for loop stops. This conditional test is optional. If omitted, the condition always evaluates to true. The increment-expression is generally used to update or increment the counter variable. The statements constitute a block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is good practice to indent these statements from the beginning of the for statement to make your code more readable. Check out the following for statement. It starts by declaring the variable i and initializing it to zero. It checks whether i is less than nine, performs the two successive statements, and increments i by one after each pass through the loop: var n = 0; for (var i = 0; i < 3; i++) { n += i; alert("The value of n is now " + n); } while Loops The while loop, although most people would not recognize it as such, is for's twin. The two can fill in for one another - using either one is only a matter of convenience or preference according to context. while creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true. The syntax of while differs slightly from that of for:
while (condition) {

statements

condition is evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements. statements is a block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the statement. The following while loop iterates as long as n is less than three.
var n = 0; var x = 0; while(n < 3) { n++; x += n; alert("The value of n is " + n + ". The value of x is " + x); }

Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure -- a set of statements that performs a specific task. A function definition has these basic parts:

The function keyword A function name A comma-separated list of arguments to the function in parentheses The statements in the function in curly braces: { }

Defining a Function When defining a function, it is very important that you pay close attention to the syntax. Unlike HTML, JavaScript is case sensitive, and it is very important to remember to enclose a function within curly braces { }, separate parameters with commas, and use a semi-colon at the end of your line of code. It's important to understand the difference between defining and calling a function.

Defining the function names the function and specifies what to do when the function is called. You define a function within the <SCRIPT>...</SCRIPT> tags within the <HEAD>...</HEAD> tags. In defining a function, you must also declare the variables which you will be calling in that function. Here's an example of defining a function:
function popupalert() { alert('This is an alert box.'); }

Calling a Function Calling the function actually performs the specified actions. When you call a function, this is usually within the BODY of the HTML page, and you usually pass a parameter into the function. A parameter is a variable from outside of the defined function on which the function will act. Here's an example of calling the same function: popupalert(); For the other example, this is how you may call it:
<A HREF="#top" onClick="anotherAlert('top')">top</A>

Notice the parentheses after the function name. It is imperative that you include these parentheses, even if they are empty. If you want to pass a parameter into the function, you would include that parameter inside of the parentheses. A parameter is a bit of extra information that can be different each time the function is run. It is stored in a variable and can be accessed just like any other variable. Here's an example of a function that takes a parameter: function anotherAlert(word) { alert(word + ' is the word that you clicked on'); } When you call this function, you need to pass a parameter (such as the word that the user clicked on) into the function. Then the function can use this information. You can pass in a different word as a parameter each time you call the function, and the alert box will change appropriately. You'll see how to pass a parameter a little later on. You can pass in multiple parameters, by separating them with a comma. You would want to pass in a few parameters if you have more than one variable that you either want to change or use in your function. Here are two examples of passing in multiple parameters when you are defining the function: function secondAlert(word,password) { confirm(word + ' is the word that you clicked on. The secret password is ' + password); } You'll notice that the same parameters are passed into both of these functions. However, you can pass in whatever values you want to use.

This would bring you to the top of the page, and bring up an alert box that said: "top is the word you clicked on" Here is the same example with multiple parameters that was shown above:
<A HREF="#top" onClick="secondAlert('awesome','pandas')">awesome</A>

You'll notice in the code that different values for the variables word and password are passed in. These values here are what the function will need to perform the actions in the function. Make sure that the values you pass in are in the correct order because the function will take them in and assign these values to the parameters in the parentheses of the function declaration. Once you pass values into your function, you can use them however you want within your function.

JavaScript error handling


javascript also supports error handling constructs. These constructs will help the developer to handle errors within the code. JavaScript provides two constructs to handle the errors: 1. try/catch block 2. onError event First, we will look into try/catch block followed by onError event. The syntax of try/catch is similar to that of other languages as shown below:

try { //Executable script } catch (errorObject) { //Error handler } finally { //Code to execute all the time,irrespective of error occurrence. } Whenever an error occurs while processing code present in try block, it will hand it over to catch block for executing the code present in it. A try/catch block cannot handle syntax errors like semicolon missing. So, it cannot handle errors generated by javascript engine.

How does VBScript compare with JavaScript? Well, it is directly comparable to JavaScript. In fact, VBScript is a competitor to JavaScript. Both languages have their advantages and disadvantages. Visual Basic has been around for quite some time. Java is relatively new. According to a recent Computer World survey, there are approximately 3 million programmers who use Visual Basic as their primary programming language. The introduction of VBScript is clearly a welcome sign for these programmers. A lot of them would find it easier to use VBScript with their HTML code than to learn a new language, JavaScript. Neither JavaScript nor VBScript can produce standalone applets. However, they can be used to add intelligence and interactivity to HTML documents. NOTE If you are an experienced Visual Basic programmer you will find it easy to learn and understand the lightweight subset of Visual Basic, VBScript. Presently, VBScript is available for Windows 95, Windows NT, Windows 3.1, and Power Macintosh platforms. VBScript can be used with HTML code with or without ActiveX controls. Using JavaScript and VBScript with your HTML code reduces Internet traffic. You can perform data validation on the client side instead of sending the data over to the server to be processed by CGI scripts. Only valid data is transmitted over the Net. This is similar to a client/server environment using PowerBuilder or Visual Basic and Sybase where the data validation is performed by the GUI front end and Sybase receives only validated data to work with. VBScript Examples Listing 1.3 shows HTML code that includes a VBScript subroutine. If you know Visual Basic, you realize that VBScript coding is very similar because it is a subset of Visual Basic. Listing 1.3. VBScript HelloWorld function.
<SCRIPT LANGUAGE="VBScript"> <!-Sub HelloWorld

VBScript Language Structure


VBScript is a lightweight portable subset of Visual Basic, the language, and Visual Basic for Applications, the scripting language used in Microsoft Excel and Word. It is a scripting language that can be used as part of your HTML code for designing and modifying Web pages. Similar to JavaScript, you can change the appearance and behavior of your Web pages dynamically using VBScript. You can process mouse events such as a mouse click or the mouse moving over a certain part of the Web page and initiate certain actions on such events. For instance, you can display different background bitmaps, depending on the day of the week. You can process form data when the user clicks the Submit button and alert the user of any invalid data. VBScript can also be used as part of other applications that use ActiveX controls, OLE Automation servers, and Java applets. As of this writing, VBScript is available only as part of Microsoft Internet Explorer 3.0. If you are already familiar with Visual Basic, the programming language, you will be able to quickly and easily grasp VBScript. There are a few important differences, though. VBScript does not support strict data types. It supports only variants. It does not support file I/O. Nor does it include direct access to the underlying operating system.

Msgbox "Hello World!" End Sub --> </SCRIPT>

NOTE VBScript can be used to control and integrate both HTML intrinsic controls and ActiveX controls. VBScript Variables VBScript supports arrays and collections of variables, similar to Visual Basic. VBScript Operators VBScript operators include arithmetic, comparison, and logical operators. Table 1.7. VBScript arithmetic operators. Operator Meaning + * / \ &
'this is the commented line

VBScript supports procedures or subroutines just as Visual Basic does. Subroutines are defined in VBScript using the sub keyword. Use the Call statement to initiate a call to the VBScript subroutine. Listing 1.4 shows a Call statement to the HelloWorld subroutine declared in Listing 1.3. Listing 1.4. Calling a VBScript subroutine.
<SCRIPT LANGUAGE="VBScript"> <!-Call HelloWorld Sub HelloWorld Msgbox "Hello World!" End Sub --> </SCRIPT>

Addition Subtraction/negation Multiplication Division Integer division String concatenation Exponentiation Remainder on division

Listing 1.5. Use of comments in VBScript.


<SCRIPT LANGUAGE="VBScript"> <!-'Call the HelloWorld subroutine Call HelloWorld Sub HelloWorld Msgbox "Hello World!" End Sub --> </SCRIPT>

^ mod

Table 1.8. VBScript comparison operators. Operator Meaning = <> > >= < <= Is Equality Non-equality Greater than Greater than or equal to Less than Less than or equal to Object equivalence

Not all browsers support VBScript. Therefore, the VBScript functions and procedures are embedded within the comment tags (<!-- and -->). Any browser that does not interpret VBScript can bypass the VBScript functions and procedures without displaying the code. VBScript functions and procedures can be placed anywhere inside the HTML code, including the HEAD and BODY sections. It is recommended you place all your functions and procedures in one location, usually toward the end of the BODY section before the </BODY> tag, similar to JavaScript coding.

Table 1.9. VBScript logical operators.

Operator And Or Not Xor Eqv Imp VBScript Err Object

Meaning Logical AND Logical OR Logical NOT Logical exclusion Logical equivalence Logical implication

single

Single precision floating-point number. The range for negative values is -3.402823E38 to -.1401298E-45. The range for positive values is 1.401298E-45 to 3.402823E38. Date. If it represents a number, its value is 0. If it represents a string, its value is "". Variable length string; it can hold up to 2 billion characters in length. Contains no valid data. True or false. Integer range: 0-255. Object. Error number.

date Empty string Null Boolean Byte Object Error

The VBScript error object Err is built into it. It can be used to track runtime errors. It has several properties that can be used to track and handle runtime errors. VBScript Variant Data Type The only data type VBScript supports is a variant. It is a one for all data type. A single data type makes the language lightweight and portable. It also makes it easier and faster to download. A variant is a special kind of data type that can contain different kinds of information, depending on the context in which it is used. If it is used in numeric context, a variant data type contains numeric data. If it is used in string context, a variant data type contains string data.

You can use the function vartype to return information about the type of data stored in a variant. VBScript Constants You can define constants in your VBScript code using the DIM statement. Listing 1.6 shows an example of declaring a constant MyString. The assignment statement determines the data type of the constant. In this case the variant MyString is of type string. Listing 1.6. Assign a string to a variant.

Data Type integer Double

Table 1.10. VBScript variant data types. Meaning Integer value between -32,768 and 32,767. Double-precision, floating-point number. The range for negative values is -1.7976931348232E308 to -4.940656458412E-324. The range for positive values is 4.940656458412347E-324 to .79769313486232E308.

Dim MyString MyString = "This is my string".

Long integer Integer in the range -2,147,483,648 to 2,147,483,648.

If you assign a number, MyString represents a numeric data type. Listing 1.7 shows an example of assigning a number to a variant. Listing 1.7. Assign a number to a variant.
Dim MyString MyString = 786

If you assign a number as a quoted string, MyString represents a string data type. Listing 1.8 shows an example of assigning a number as a quoted string to a variant. Listing 1.8. Assign a number as a quoted string to a variant.
Dim MyString MyString = "786"

VBScript Functions VBScript supports functions just like Visual Basic does. Functions are defined in VBScript using the Function keyword. Similar to variables, VBScript functions are also loosely typed. You need not explicitly define the type of return value of a function. The type of return value is automatically set, based on the context in which it is used. VBScript Procedures

and Time literals are represented by enclosing them within # signs. Listing 1.9 shows an example of assigning a date to a variant.
Date

Listing 1.9. Assign a date to a variant.


Dim DepartureDate DepartureDate = #08-23-96#

VBScript supports procedures just as Visual Basic does. Procedures are defined in VBScript using the sub keyword. JavaScript does not support procedures. Defining Subroutines: The Sub . . . End Sub Construct Subroutine Names There are several very straightforward rules to remember when giving names to your subroutines:
The name can contain any alphabetical or numeric characters and the

VBScript Flow of Control Statements


Statement For.Next For Each.Next If.Then Select Table 1.10. VBScript flow of control statements. Meaning Execute the code within the loop for N times, where N is specified in the For loop. Execute the code within the loop once for each item in the specified collection. Simple If.Then statement. Select Case test expression. Case Case End Select Execute the code within the loop as long as the loop expression is true. Execute the code within the loop as long as the specified condition is true.

underscore character. The name cannot start with a numeric character. The name cannot contain any spaces. Use the underscore character to separate words to make them easier to read. For example: Sub 123MySub( ) ' Illegal Sub My Sub Routine( ) ' Illegal both contain illegal subroutine names. However: Sub MySub123( ) ' Legal Sub MySubRoutine( ) ' Legal are legal subroutine names.

If.Then.Else.End If The standard If.Then.Else.End If statement.

Do.Loop While.Wend

VBScript error handling


When routines in the Rational ClearQuest API encounter unexpected conditions, they throw an exception. If the exception is not caught by the

calling program, the language interpreter terminates your program. If there is any possibility that the Rational ClearQuest API call will fail, you should catch and handle exceptions. Use the standard means of handling VBScript errors by using the VBScript On Error statement. You can then examine the Err error object and analyze errors at any time. For example: On Error Resume Next Err.Clear ' perform some operation here... if Err.Number <> 0 then ' An exception occurred StdOut "Exception:" & vbCrLf &_ " Error number: " & Err.Number & vbCrLf &_ " Error description: '" & Err.Description & vbCrLf
...

You should check such a return value with the IsEmpty or IsArray functions before applying any array-related function on it. For example:
fieldObjs = GetInvalidFieldValues ' Check the return value If (IsArray(fieldObjs)) Then For Each fieldInfo In fieldObjs fieldValue = field.GetValue fieldName = field.GetName currentsession.outputdebugstring "This is the fieldvalue " & fieldvalue Next Else currentsession.outputdebugstring "This is not an array or it is empty" End If

You can use a GoTo statement for Visual Basic but not for VBScript. For example: ' VB exception handling example On Error GoTo HandleError fieldValue = record.GetFieldStringValue(fieldname) ... HandleError: StdOut "Got error number " & Err.Number & ":" StdOut Err.Description Several functions which are expected to commonly fail are exceptions to this. In particular, validate and set field functions return error indications instead of throwing exceptions. For more information, see "Error checking and validation". Handling VARIANT return values For VBScript, some of the properties and methods return a VARIANT value which is supposed to contain an array of objects or Strings. If the array contains zero elements, then the VARIANT value would simply have a value of EMPTY. An empty value is not considered to be an array, and if you try to iterate over something that's not an array, it is considered a type-mismatch.

UNIT II VB SCRIPT

Input & Output:


Reference the Contents of Another Loaded Document or Documents Many of us use frames in our web pages and applications. Implemented correctly, frames enhance the experience of a web site by creating a presentation that is more pleasing to the eye, and by making navigation easier. Using VBScript, we can reference the document in one frame from a document in a different frame, or from the document that created the frameset. Figure 1-19 shows two documents loaded into two frames, named LeftFrame and RightFrame. The VBScript code linked to the button in LeftFrame actually retrieves a value located in a form embedded in RightFrame. The relatively simple code from LeftFrame is shown in Figure 1-20. Figure 1-19: Using VBScript to retrieve a value in another document

Figure 1-20: The code used in Figure 1-19

As you can see from the code in Figure 1-20, we can also reference the frame itself. This allows us, for example, to have a VBScript in one frame that decides which page the browser needs to load in another frame, based upon some input from the user. We can even reference another VBScript program in another frame. Store, Reference, and Manipulate Data Input by the User Although VBScript does not currently allow us to store data to the user's disk (with the exception of cookies), we can store data in memory. For example, as the user enters data in a form, VBScript allows us to retrieve this data and store it in arrays or variables that can later be manipulated in some way by our script. Figure 1-21 shows how we can extract the data input by a user and manipulate it in some way before sending it to the server. The left frame contains a text box and a command button. Sample text is entered into the text box, and when the user clicks the button, the text is manipulated by the VBScript program and-just for this example-a page is generated by the VBScript program and placed in the right-hand frame. The code snippet from this example is shown in Figure 1-22.

Figure 1-21: Using VBScript to manipulate user input

Store, Reference, and Manipulate Data Downloaded from the Server Let's say we have a fixed data set we wish to include in our page. We can hard code this data set into the HTML page using an array variable. VBScript will then automatically load this data into the memory of the client machine. We can then directly reference this data, again based on input from the user. Another method of implementing this data set is to create our initial page using a server-side script to include data in our page based on the request from the client, in very much the same way as most search engines operate. But with the inclusion of VBScript, we can manipulate this data further once the page has been downloaded to the client browser. In Figure 1-23, for example, data are hardcoded into the HTML page, although it could just as easily be added by a server-side script. The user selects a product from a drop-down list box and enters the quantity required. When the user clicks the Calculate button, the price of the product is accessed from the data array, and a simple calculation is performed to determine the total cost. Figure 1-23: Using VBScript to manipulate dataa

Figure 1-22: VBScript code to manipulate user input

The complete source code for the example shown in Figure 1-23 appears in Example 1-3. Don't worry about the ins and outs of the code at this stage. It is shown here purely to illustrate how quickly and easily you can perform program- matic tasks at the browser. And as you can see, the majority of code for this example is in fact good old HTML!

Example 1-3: HTML source with VBScript for Figure 1-23


<HTML> <HEAD> <TITLE> Manipulating Data from the Server </TITLE> <SCRIPT LANGUAGE="vbscript"> OPTION EXPLICIT Dim dblPrices(2) Dim dblShipping dblPrices(0) = 25.95 dblPrices(1) = 30.50 dblPrices(2) = 50.55 dblShipping = 10.99 Sub cmdCalc_OnClick Dim intSelected Dim dblTotal Dim dblTot intSelected = frmForm1.cboProducts.SelectedIndex dblTot = dblPrices(intSelected) * frmForm1.txtQty.Value dblTot = dblTot + dblShipping frmForm1.txtTotal.Value = "$" & dblTot End Sub </SCRIPT> </HEAD> <BODY BGCOLOR="white"> <FONT FACE="arial" SIZE=2><B> <CENTER> <H3>Order Form</H3> <P> Select the product you require from the list, then simply enter the quantity, and click the Calculate button to see the total cost. </P> <FORM NAME="frmForm1"> <SELECT NAME="cboProducts"> <OPTION>Product A <OPTION>Product B <OPTION>Product C </SELECT> Qty <INPUT TYPE="text" NAME="txtQty" SIZE=10> <P>

<INPUT TYPE="button" NAME="cmdCalc" VALUE="Calculate"> <P> Total Cost including Shipping and Handling <INPUT TYPE="text" NAME="txtTotal"> </FORM> </BODY> </HTML>

Perform Calculations on Data Once we have captured data either from the server or as a result of user input, using VBScript to perform calculations on this data is very straightforward, as Figure 1-23 and the HTML source code in Example 1-3 illustrate. Whether a simple calculation or a series of complex calculations is required, VBScript gives us control over form data. VBScript provides a rich assortment of builtin func- tions for numerical operations, and also allows calculations to be performed on dates and times. Display Messages to the User One way we can interact with the user is to display a simple message box, or alert box, like the ones we've seen in earlier examples. Messages such as these quickly and easily guide users of our web site or page. Messages that our program displays do not necessarily have to be fixed; they can be built dynamically, based on the values of program variables. For example, a message box linked to an input form could include the user's name, for that personal touch ("Hey Paul, you didn't enter your Zip Code!"). The techniques for doing this are covered in Chapter 15, Error Handling and Debugging.

Integration with Forms


Adding VBScript Code to an HTML Page
You can use the SCRIPT element to add VBScript code to an HTML page. The <SCRIPT> Tag VBScript code is written within paired <SCRIPT> tags. For example, a procedure to test a delivery date might appear as follows:

<SCRIPT LANGUAGE="VBScript"> <!-Function CanDeliver(Dt) CanDeliver = (CDate(Dt) - Now()) > 2 End Function --> </SCRIPT>

Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE attribute indicates the scripting language. You must specify the language because browsers can use other scripting languages. Notice that the CanDeliver function is embedded in comment tags (<!-- and -->). This prevents browsers that don't understand the <SCRIPT> tag from displaying the code. Since the example is a general function it is not tied to any particular form control you can include it in the HEAD section of the page:
<HTML> <HEAD> <TITLE>Place Your Order</TITLE> <SCRIPT LANGUAGE="VBScript"> <!-Function CanDeliver(Dt) CanDeliver = (CDate(Dt) - Now()) > 2 End Function --> </SCRIPT> </HEAD> <BODY> ...

<HTML> <HEAD> <TITLE>Test Button Events</TITLE> </HEAD> <BODY> <FORM NAME="Form1"> <INPUT TYPE="Button" NAME="Button1" VALUE="Click"> <SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript"> MsgBox "Button Pressed!" </SCRIPT> </FORM> </BODY> </HTML>

Most of your code will appear in either Sub or Function procedures and will be called only when specified by your code. However, you can write VBScript code outside procedures, but still within a SCRIPT block. This code is executed only once, when the HTML page loads. This allows you to initialize data or dynamically change the look of your Web page when it loads.

VBScript with Forms


The Events of a Control We mentioned that a user can interact with a web page using the controls on it. To do this, the user can click a control, type in it, move the caret from it to another control, etc. Everyone of these actions creates a message that must be sent to a program used by the programmer: the interpreter. The interpreter then analyzes the message and produces a result. When a message created by a control is sent, it is also said that an event was fired. There are various types of events sent by different controls. We will mention each when necessary. When you create a web-based application, you decide what controls are necessary for your application. When you select a control, you must also know what events that control can send. In most cases, if you don't care about an event, when it occurs, the computer may ignore the event or produce a default behavior. If you think that a certain event is important for your application and that you must take action when that event fires, you should write code to react appropriately.

You can use SCRIPT blocks anywhere in an HTML page. You can put them in both the BODY and HEAD sections. However, you will probably want to put all general-purpose scripting code in the HEAD section in order to keep all the code together. Keeping your code in the HEAD section ensures that all code is read and decoded before it is called from within the BODY section. One notable exception to this rule is that you may want to provide inline scripting code within forms to respond to the events of objects in your form. For example, you can embed scripting code to respond to a button click in a form:

The Form
Introduction
A form is the central object that manages the other controls. Although the controls can send their data to a script, a form can be used to collect the values typed or selected on the controls, gather them as if they constituted one control and make these values available to a validating file on a server. Creating a Form To create a form, you use the <form> tag. Because a form is a collection of controls and their values, the form must have an end that lets the browser know where the form closes. This is done with the </form> closing tag as follows:

<Input Type=Text> or <INPUT TYPE=TEXT> Characteristics of a Text Box By default, the text box control provides enough space to display a first name, a username, or a short e-mail address. If it is not enough, you can widen the text box. To increase the width of a text box, the <input> tag is equipped with an attribute called size. Therefore, to widen a text control, assign an appropriate numeric value to the size attribute. Like all HTML attributable tags (such as <body> or <font>), there is no rule on the order of attributes. Here is an example that creates a text box control:
<input type="text" size="40">

<FORM> </FORM>
Everything between the <FORM> and the </FORM> tags belong to the form and is called the body of the form. Almost anything can go in the body of the form. You can design it using any HTML tag and make it as attractive as you wish.

The value that displays in a text box is held by an attribute called value. To display text in the text box, assign a string to the value attribute. Here is an example:
<input type="text" value="James Fame Ndongo">

Forms Characteristics
Although the <form> and the </form> tags are enough to create a form, such a form can hardly communicate with a script. One of the most important characteristics you should set for a form is its name. The name allows a script to refer to the form and it can be used by files on the server. To set the name of a form, assign an appropriate string to the Name attribute of the <form> tag. Text box A text box is a rectangular object that receives or displays text. By default, a text box is intended for the user to type text in response to a request. To create a text box, use the <input> tag and specify the Type attribute as Text. The minimum syntax for creating a text box is: <input type=text> Because HTML is not case sensitive, you can create the control in all uppercase, all lowercase, or a mix of both. Therefore, the control can also be created with:

To retrieve the content of a text box, you can use the value attribute. To access it, you can type the name of the form that contains the text box, followed by a period, followed by the name of the text box, followed by a period, and followed by value. If you plan to use a text box in a script or code of any kind, give the control a name. This is done by assigning a string to the name attribute. Here is an example:
<input type="text" name="FirstName">

Events of a Text Box To use a text box, the use can click it or continuously press Tab until the caret is positioned in the text box. When this happens, the text box is said to have focus. When a text box receives focus, it fires an onFocus event. In most applications, a text box primarily appears empty to the user who can then enter one or more characters in it. To enter a character in a text box, the user usually presses a key on the keyboard. When this happens, the text box

fires an onKeyDown event. When the user releases the key, the control fires an onKeyUp event. In some cases, the user may press a key and hold it down. This causes the control to fire an onKeyPress event. When the user types a character in a text box or modifies its content such as putting space between two characters or deleting a character in it, the control fires an onChange event. This event indicates that the content of the text box is not the same it was when it first displayed to the user. When the user has finished using a control and either presses tab or clicks another control, the text box fires an onBlur event to indicate that it has lost focus. Practical Learning: Using Text Boxes 1. To use text boxes, change the file as follows:
<h2>Employment Application</h2> <form name="frmEmployees"> <table border="0" width="288"> <tr> <td width="80">First Name:</td> <td width="194"><input type="text" name="txtFirstName" size="10" onChange="form.txtFullName.value = form.txtFirstName.value + ' ' + form.txtLastName.value"></td> </tr> <tr> <td width="80">Last Name:</td> <td width="194"><input type="text" name="txtLastName" size="10" onChange="form.txtFullName.value = form.txtFirstName.value + ' ' + form.txtLastName.value"></td> </tr> <tr> <td width="80">Full Name:</td> <td width="194"><input type="text" name="txtFullName" size="20"></td> </tr> </table> </form>

2. Save the file and preview it in your browser

3. Type a name in the First Name text box, press Tab, type another name in the Last Name text box 4. Return to your text editor A Button
Creating Button a

A button is a rectangular window that the user clicks, as indicated by an application developer. What happens when the user clicks it depends. To create a button, use the <input> tag and specify the type of control by assigning the button value to the Type attribute. Here is an example: <input type="button"> The most visual properties of a button are its location and the text it displays. There are various ways you can set the location of a button on the page. Although HTML provides paragraph tags that can position the button, one of the best options you have is to use a table when designing your form. This will also be valid for all controls we will learn on this site.

Button Properties The text that a button displays lets the user know what the button is used for. The text on the button is sometimes called a caption. In HTML, this caption is the Value attribute of the <input type="button"> existing tag. To provide the button's caption, set the desired string to Value. Here is an example: <input type="button" value="Send Me Somewhere"> To know the caption that a button is displaying, you can access its value attribute. Another important property of a button is its name. This allows the browser to identify it. The name is set by assigning an appropriate name to the Name attribute of the <input> tag. To access a button on a form, type the name of the form, followed by a period, followed by the name of the button.

<td><input type="text" name="txtLastName" size="10"> <input type="button" value="Evaluate" name="btnEvaluate" onClick="form.txtFullName.value = form.txtLastName.value + ', ' + form.txtFirstName.value"> </td> </tr> <tr> <td width="80">Full Name:</td> <td><input type="text" name="txtFullName" size="24"></td> </tr> </table> </form>

2. Save the file and preview it in your browser 3. Type a name in the First Name text box. Type another name in the Last Name text box and click Evaluate. Here is an example:

Button Events
The most important and the most used event on a button results on clicking it. When the button is clicked, it fires an event called onClick. To process a script when the user clicks a button, you can assign the name of a function, as a string, to the onClick attribute of the button. Practical Learning: Using Button 1. To use a button, change the file as follows:
<h2>Employment Application</h2> <form name="frmEmployees"> <table border="0" width="320"> <tr> <td width="80">First Name:</td> <td><input type="text" name="txtFirstName" size="10"></td> </tr> <tr> <td width="80">Last Name:</td>

4. Return to your text editor The Submit Button Introductio n To send all of the information of a form to a script, HTML provides a special button called submit. Like the regular button, the submit button is a rectangular object that the user clicks.

To create a submit button, use the <input> tag but specify the type of control as submit to the type attribute. Here is an example: <input type="submit">
Submit

Submit Button Events


The most important and the most used event on a button results on clicking it. When the button is clicks, it fires the onClick event.

The Reset Button Introductio n


Most of the forms allow the user to fill out text controls and make selections from other controls. These actions change the values of those controls as set by the application developer. If in the middle of filling out a form the user decides to start over, HTML provides a special button that can reset all controls to their default states or values. This is programmatically done using a special button called Reset. To create a reset button, use the <input> tag and specify the type of control as Reset to the Type attribute. Here is an example: <input type="reset">
Reset

Unlike the regular button, the submit button has a built-in caption that automatically displays its role to the user. Characteristics of the Submit Button The default caption of the submit button is submit. If this caption doesn't apply to your scenario, you can change it to a more meaningful caption. To change the submit button's caption, set the desired string to the Value attribute of the <input type="submit"> existing tag. Here is an example: <input type="submit" value="Validate Application">
Validate Application

One of the most important properties of a submit button is its name. Even if you are creating a form for fun, the browser needs to identify the button among other controls. The name is set by assigning an appropriate name to the Name attribute of the <input> tag. The Submit button on a form is the main button the user would click the send the form's collected data to a script or another file. To make this happen, a form is equipped with an attribute called Action. This attribute is assigned an outside function, script, or server file that would receive the results of the form and take appropriate actions. To tell the form what to do when the user clicks the Submit button on a form, assign the desired (or an appropriate) string to the Action attribute of the <form> tag. In the following example, a form sends its result to an e-mail address:
<form action="mailto:custservice@functionx.com"> </form>

Unlike the regular button, the reset button has a built-in caption that automatically displays its role to the user.

Characteristics of the Reset Button


The default caption of the reset button is Reset. If this caption is not explicit enough for your application, you can change it. To change the caption of a reset button, set the desired string to the Value attribute of the <input type="reset"> existing tag. Here is an example:
<input type="reset" value="Start Over">
Start Over

HTML allows you to decide how you want the form to send its data away. The most two popular options you have are Post and Get.

The reset button is mainly configured to handle its business on the form and doesn't need to send any signal such as a result to a script. Therefore, its name is not as important as it is to other controls. If for some reason you need to refer

to the Reset button from a script, then you can give it a name. The name is given by assigning an appropriate string to the Name attribute of the <input type="reset"> existing tag.

<textarea cols="40" rows="10"></textarea>

Text Area: Introductio n


A text area is a large control that is a substitute to handle large paragraph where the text box cannot or should not be used. To create a text area, use the <TextArea> tag which must also be closed. Here is an example:
<textarea></textarea>

Password Text Boxes

Creating a Password Text Box


HTML provides a specific text designed for a form's password. This looks like a classic text box and is created the same. The main difference is that the text that the user types doesn't display the characters that are being entered. As the user types in the password text box, text appears as a series of asterisks or periods. Like the regular text box and many other controls, to create a password text box, use the <input> tag and specify the control type as password assigned to the type attribute. Here is an example: <input type="password"> Characteristics of the Password Text Box The size of the password text box is controlled by the size attribute of the <input> tag. To increase the width of the control, assign the desired numeric value to the size attribute. The text that is typed in the password text box is held by the value attribute. You can use this attribute to find out what password the user typed. If you plan to retrieve the password value in a script or code of any kind, give

Characteristics of the Text Area The dimensions of a text area are the main properties that set it apart from the text box control. The width of a text area is set using the COLS attribute of the <textarea> tag. Therefore, to increase the width of the text area, assign the desired numeric value to the cols attribute. The width is measured by the number of characters that can be displayed on one line of text. By default, a width of a text area is set to 20 characters. To change this, you can assign a higher value to the attribute: To change or increase this number, assign an appropriate numeric value to the rows attribute. You can specify either one of the COLS or the ROWS values. You can also specify both to control the dimensions of the text area. When using both attributes, there is no order of the attributes. Here is an example: If you are planning to access the text area from your code, you should give the control a name.

the control a name. This is done by assigning a name string to the name attribute. Here is an example:
<input type="password" name="Guarded">

when the user clicks the check box, selecting or deselecting it. Therefore, you can use the onClick event of the check box to find out whether the control has been selected or not; if so, you can decide what to do in response.

Radio Buttons Check Boxes


Creating a Check Box A check box is a small square box that allows the user to select an item or to deselect it. The user makes this decision by clicking in the small square box. By default, or depending on how the control is configured, the square box is white and empty. This indicates that it is false or off. When the user clicks it, a small check mark appears in the square box, indicating that it is true or on. To create a check box, use the <input> tag and specify the control type as checkbox, CheckBox, or CHECKBOX. Here is an example:
<input type="checkbox">

Introductio n A radio button is a small round and white circle that allows the user to select an item from a group. This is because a radio button is generally accompanied by others. From a group of items, represented each by a circle, when the user clicks one of them, none of the others is selected. To change the selection, the user must click another choice in the group. To create a radio button, use the <input> tag and specify the type attribute as radio. Here is an example:
<input type="radio">

A check box doesn't display what it is used for. Therefore, you should (always) add a label close to it to help the user know the role of this control. If using many check boxes in a group, the user is able to click or select as many different check boxes that the application designer allowed.

To make your radio buttons effective, you should always provide at least two radio buttons in a group. Characteristics of Radio Buttons One of the most important attributes to set on the radio button is the name. This attribute should be used even if you don't plane to use the radio button in a script, since many radio buttons can use the same name, this name will be helpful in determining what particular control has been selected. Therefore, the same value (string) for the Name attribute can be assigned to each radio button of the same group. The checked attribute, as applied to the check box, can be used in two circumstances, if you want one of the buttons in the group to be selected by default, assign a true value to its checked attribute. Radio Button

Characteristics of a Check Box


As described already, when the user clicks the check box, its value becomes on or true. You can programmatically set this state by using the checked attribute of this tag. If you assign it a true value, the check box becomes checked. Otherwise, it would be unchecked. Here is an example of using the tag:
<input type="checkbox" checked="true">

If you plan to use a check box in a script, you should give it a name. This is done by assigning a string to the Name attribute. Check Box Events The most popular and probably the most important event of a check box fires

Events Because it is first of all a button, the most fundamental event that a radio button can send to the browser is called onClick. This event fires when the user clicks or select a particular radio button. You can therefore use it to take action as a response.

item. There are two main ways to select a value in a combo box. The user can first press Tab a few times until the combo box receives focus. An alternative is to click the down pointing arrow. In both cases, when the combo box receives focus, it fires an onFocus event. If the user pressed Tab to give focus to the combo box, he or she can press Alt + the down arrow key to display the list of the control. Remember that the user can also click the arrow to display the list. To actually select an item from the list, the user can click it. When this is done, the combo box fires an onChange event to indicate that its value has changed. After using a combo box, the user can press Tab or click another control. In both cases, the combo box would fire an onBlur event to indicate that it has lost focus.

Combo Boxes
Introductio n Like a group of radio buttons, a combo box allows the user to select an item from a group, namely a list. A combo box has the shape as a text box, except that it is equipped with an arrow on the right side of the control. This arrow control allows the user to display a list of items that are hidden by the text side of the combo box. When the list displays, the user select one item from the list. Once the item has been selected, the list retracts back to its original text-like size. To create a combo box, use a tag called select. This tag has to be closed. After typing the <select> tag, create each item that is part of the control using the <option> tag. Each item uses its own <option> tag. After listing the items, make sure you close the select tag as </select>. Here is an example:
<select> <option>Small <option>Medium <option>Large <option>X-Large </select>

List Boxes
Creating a List Box Like radio buttons or a combo box, a list box displays a list of items that the user can select from. Unlike a combo box, a list box displays a taller list and can even display all of its items all the time. Like a combo box, a list box is created using the <select> tag. Like the combo box, each item of a list box is created using the <option> tag. To make the control a list box, the <select> tag is equipped with an attribute called size. This attribute accomplishes two purposes: it makes the control become a list box and it sets the vertical size of the list box. In other words, it decides on the number of items the list box can display at a time. Characteristics of a List Box A list box can be configured to allow the user to select one item. To select an item from the list, set the selected attribute of its <option> tag to true. Here is an example:

Characteristics of a Combo Box To select a default item from the combo box, use the selected attribute of the <options> tag. Events of a Combo Box Besides looking at a combo box to see its current value, the most expected action the user can make on a combo box is to click its arrow and select a new

<select size="4"> <option>Schwartz <option selected="true">Medou <option>Larson <option>Creans <option>Schultze <option>Greenberg </select>

The validation example that we will be examining does not contain anything new in the way of VBScript. We are simply using the elements that we have learned in the previous lessons in a new way. Before reading any further you may find if beneficial to ponder how you would validate an HTML form using the VBScript techniques that you have learned. Okay, are you through pondering? Let's look at an example to give you an idea of what is possible when it comes to validating forms.

Unlike a combo box, a list box can be configured to allow the user to select more than one item from the list. To allow this, include the multiple attribute in the <select> tag. Here is an example:
<select size="4" multiple> <option>Schwartz <option>Medou <option>Larson <option>Creans <option>Schultze <option>Greenberg </select>

Checking Form Input


This example is pretty simple. It has a single field in which the user can enter their age and a single command button that is used to submit their age to the server. A copy of this example can be found in exam_5a.htm.
<HTML> <HEAD> <TITLE>Working With VBScript: Example 5a</TITLE> <SCRIPT LANGUAGE="VBScript"> <!-- Instruct non-IE browsers to skip over VBScript modules. Option Explicit Sub cmdSubmit_OnClick ' Check to see if the user entered anything. If (Len(document.frmExample5a.txtAge.value) = 0) Then MsgBox "You must enter your age before submitting." Exit Sub End If ' Check to see if the user entered a number. If (Not(IsNumeric(document.frmExample5a.txtAge.value))) Then MsgBox "You must enter a number for your age." Exit Sub End If ' Check to see if the age entered is valid. If (document.frmExample5a.txtAge.value < 0) Or _ (document.frmExample5a.txtAge.value > 100) Then MsgBox "The age you entered is invalid." Exit Sub End If ' Data looks okay so submit it. MsgBox "Thanks for providing your age." document.frmExample5a.submit End Sub -->

List Box Events The most commonly used and the most important event of a list is called onChange. This event fires whenever the user makes a selection in the list box. This allows you to take appropriate actions.

Validating Your Forms


The process of validating forms involves checking the form to see if:

All of the required data is proved The data provided is valid

Meticulous data validation scripts can be tedious to code but are well worth their return in verifying the quality of the data.

</SCRIPT> </HEAD> <BODY> <H1>A VBScript Example on Variables</H1> <P> This example demonstrates validation techniques in VBScript. </P> <FORM NAME="frmExample5a"> <TABLE> <TR> <TD>Enter your age:</TD> <TD><INPUT TYPE="Text" NAME="txtAge" SIZE="2"> <TR> <TD><INPUT TYPE="Button" NAME="cmdSubmit" VALUE="Submit"></TD> <TD></TD> </TR> </TABLE> </FORM> </BODY> </HTML>

Our final check involves verifying that the age they entered seems reasonable for our environment. I have determined that no age less than 0 or greater than 100 is acceptable. Using an If..Then statement we can check the value of the input field against this criteria: ' Check to see if the age entered is valid. If (document.frmExample5a.txtAge.value < 0) Or _ (document.frmExample5a.txtAge.value > 100) Then MsgBox "The age you entered is invalid." Exit Sub End If That's it. While this example is by no means the most detailed validation script you will encounter it provides you with a basis of what is possible with VBScript. Submitting Your Forms Compared to validation, the process of submitting a form is simple. In our example we've used a normal HTML button with the Submit caption that is tied to an event procedure that both validates and at the same time submits the form. In Chapter 5, we've demonstrated how to use function MyButton_onSubmit, as an alternative. The code that we would have to add to our previous example to submit the form is shown below: ' Data looks okay so submit it. MsgBox "Thanks for providing your age." document.frmExample5a.submit The MsgBox statement lets the user know that their data has been processed. The form is then submitted by invoking the Submit method of the form object. As we saw in lesson 3 on objects, methods cause an object to perform a task. Here we are using the submit method of our form to cause the form to submit its data, just as if we had used a submit control.

How It Works
The heart of this validation script is found in the click event procedure for the cmdSubmit command button. We start by checking if the user entered anything at all into the field using VBScript's Len function. This function returns the length of a string. If the length is 0, the data is invalid. We inform the user and exit the submit procedure via the Exit Sub statement: ' Check to see if the user entered anything. If (Len(document.frmExample5a.txtAge.value) = 0) Then MsgBox "You must enter your age before submitting." Exit Sub End If Next we check to see if what the user entered is a numeric value. The VBScript function IsNumeric returns a true value when it is a number. If not, we tell the user and exit: ' Check to see if the user entered a number. If (Not(IsNumeric(document.frmExample5a.txtAge.value))) Then MsgBox "You must enter a number for your age." Exit Sub End If

ActiveX
ActiveX is a framework for defining reusable software components in a programming language independent way. Software applications can then be

composed from one or more of these components in order to provide their functionality.

Progress bars: comctl32.ocx

ActiveX controls
Active X controls, small program building blocks, can serve to create distributed applications working over the Internet through web browsers. Examples include customized applications for gathering data, viewing certain kinds of files, and displaying animation.

How Do I Script an ActiveX Control on a Web Page?


An easy way to get started with scripting is by using an HTML authoring tool like Microsoft ActiveX Control Pad. This topic shows how to use ActiveX Control Pad to script CIRC, an MFC control sample. The ActiveX Control Pad is an authoring tool that lets you add ActiveX controls and scripting (such as JScript and VB Script) to your HTML pages with point-and-click ease. The ActiveX Control Pad also includes the Microsoft HTML Layout Control, which supports windowless controls and provides new layout capabilities based on the HTML extensions proposed by the World Wide Web Consortium (W3C).

Notes
Introduction to ActiveX Controls at microsoft.com, accessed 18-Jan-2008 "Active X". 2009-02-24. "As a Microsoft product, Active X was specifically designed to work with Windows systems. ActiveX is not supported by Microsoft on other operating systems e.g. Mac OS X or GNU/Linux." In this chapter, we'll look at some of the ActiveX controls, which are essentially limited OCX controls, that Microsoft has developed or distributes for use with VBScript. The ability to use embedded ActiveX controls is one of the most powerful VBScript techniques. In fact, some people consider VBScript simply a means of making ActiveX controls work in Web pages. We will look at some of the most popular ActiveX controls and then go into more depth on three of them: grid controls, graph controls, and multimedia controls. Here are the ActiveX controls we'll review, along with their associated support files in Windows 95:

To install and run ActiveX Control Pad


The ActiveX Control Pad is freely available for downloading from the

authoring tools section in the MSDN Online Web Workshop at http://msdn.microsoft.com/workshop/misc/cpad/default.asp. Follow the online instructions for installation. To insert CIRC

3-D buttons: threed32.ocx 3-D frames and panels: threed32.ocx Grid controls: grid32.ocx Graph controls: graph32.ocx 3-D checkboxes: threed32.ocx AVI file controls: avifile.dll Multimedia controls: mci32.ocx Spin buttons: spin32.ocx 3-D option buttons: threed32.ocx Sliders: comctl32.ocx Keystate controls: keysta32.ocx Rich text controls: richtx32.ocx

1. Download the CIRC sample files from MSDN and build the DLL (Circ31.dll). 2. Start ActiveX Control Pad. It opens with a default HTML document, including head and body tags. 3. On the Edit menu, click Insert ActiveX Control. 4. In the Insert ActiveX Control dialog box, click the CIRC control to add it to the page. The control will be displayed in the Edit ActiveX Control window. You should see a rectangular control containing Circ31. Its properties can be set by changing values in the Properties window.

5. Close the Edit ActiveX Control window.


The OBJECT tag will be displayed on your HTML page, including the control's class ID and other parameters used to instantiate the control at run time. Now you are ready to script the control. To use VBScript to invoke properties and methods on CIRC 1.Start ActiveX Control Pad and open the file created in the procedure To Insert CIRC, if it is not already open. 2. On the Tools menu, click Options, and then click Script. 3. In the Script Options dialog box, select Visual Basic Scripting Edition as the Default Script Language and click OK. 4. From the Tools menu, click Script Wizard. Steps 5 and 6 are performed in the Script Wizard dialog box.

3.

In the Script Options dialog box, select JScript as the Default Script Language and click OK. 4. From the Tools menu, click Script Wizard. Steps 5 and 6 are performed in the Script Wizard dialog box.

5.

In the Select an Event list, click Window, and then click Load to add code to run when the control is loaded. 6. In the Insert Actions list, click AboutBox, and click Insert Action. The following code to invoke the AboutBox method is inserted into the HTML file:
<SCRIPT LANGUAGE="jscript" FOR="window" EVENT="onLoad()"> <!-Circ31.AboutBox() -->

5.

In the Select an Event list, click Window, and then click Load to add code to run when the control is loaded. 6. In the Insert Actions list, click AboutBox, and click Insert Action. The following code to invoke the AboutBox method is inserted into the HTML file:
<SCRIPT LANGUAGE="VBScript"> <!-Sub window_onLoad() call Circ31.AboutBox() end sub -->

7.Save the file and open it in a browser. You should see the About box displayed. Using an authoring tool, it is simple to add a control to a Web page and to use scripting to invoke its properties and methods. You can easily attach JScript or VBScript code to buttons on your HTML pages.

Active Scripting
Active Scripting (formerly known as ActiveX Scripting) is the technology used in Windows to implement component-based scripting support. It is based on COM (more precisely, OLE Automation) and allows installation of additional scripting engines in the form of COM modules. The Active Scripting technologies were first released in 1996, with the release of the Microsoft Internet Explorer 3.0 (August 1996) and Internet Information Services 3.0 products (December 1996). Usual applications of Active Scripting include Active Server Pages (ASP) server scripts, Internet Explorer, and Windows Script Host (WSH) scripts

7.Save the file and open it in a browser. You should see the About box displayed.

To use JScript to invoke properties and methods on CIRC


1.Start ActiveX Control Pad and open the file created in the procedure To Insert CIRC, if it is not already open. 2. On the Tools menu, click Options, and then click Script.

automating routine tasks, including use for login scripts, Registry manipulation, and the like.

valid submission. Below is the JavaScript code to perform this basic check to see if a given HTML input is empty or not. JavaScript Code: // If the length of the element's string is 0 then display helper message function validate_form(elem){ if(elem.value.length == 0){ alert('Please Enter a Value'); elem.focus(); return false; } return true; } The function notEmpty will check to see that the HTML input that we send it has something in it. elem is a HTML text input that we send this function. JavaScriptstrings have built in properties, one of which is the length property which returns the length of the string. The chunk of code elem.value will grab the string inside the input and by adding on length elem.value.length we can see how long the string is. As long as elem.value.length isn't 0 then it's not empty and we return true, otherwise we send an alert to the user with a helperMsg to inform them of their error and return false.

UNIT III JAVA SCRIPT Form Validation:


The idea behind JavaScript form validation is to provide a method to check the user entered information before they can even submit it. JavaScript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it. In this lesson we will be reviewing some basic form validation, showing you how to check for the following:

If a text input is empty or not If a text input is all numbers If a text input is all letters If a text input is all alphanumeric characters (numbers & letters) If a text input has the correct number of characters in it (useful when restricting the length of a username and/or password) If a selection has been made from an HTML select input (the drop down selector) If an email address is valid How to check all above when the user has completed filling out the form

Checking for Non-Empty


This has to be the most common type of form validation. You want to be sure that your visitors enter data into the HTML fields you have "required" for a

JavaScript Code: // If the element's string matches the regular expression it is all numbers function isNumeric(elem){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert('Numbers Only Please'); elem.focus(); return false; } } What we're doing here is using JavaScript existing framework to have it do all the hard work for us. Inside each string is a function called match that you can use to see if the string matches a certain regular expression. We accessed this function like so: elem.value.match(expressionhere). We wanted to see if the input's string was all numbers so we made a regular expression to check for numbers [0-9] and stored it as numericExpression. We then used the match function with our regular expression. If it is numeric then match will return true, making our if statement pass the test and our function isNumeric will also return true. However, if the expression fails because there is a letter or other character in our input's string then we'll display our helperMsg and return false. Working Example: <script type='text/javascript'> function isNumeric(elem){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert('Numbers Only Please'); elem.focus(); return false; } }

Working Example: <script type="text/javascript"> function validate_form(elem){ if(elem.value.length == 0){ alert('Please Enter a Value'); elem.focus(); return false; } return true; } </script> <form action="submit.htm" onsubmit="return validate_form(document.getElementById('req1'))" method="post"> Required Field: <input type='text' id='req1'/> <input type="submit" value="Chick Field"> </form>

Checking for All Numbers


If someone is entering a credit card, phone number, zip code, similar information you want to be able to ensure that the input is all numbers. The quickest way to check if an input's string value is all numbers is to use a regular expression /^[0-9]+$/ that will only match if the string is all numbers and is at least one character long.

</script> <form action="submit.htm" onsubmit="return isNumeric (document.getElementById('numbers'))" method="post"> Numbers Only: <input type='text' id='numbers'/> <input type="submit" value="Chick Field"> </form>

}else{ alert('Letters Only Please'); elem.focus(); return false; } } Working Example: <script type='text/javascript'> function isAlphabet(elem){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert('Letters Only Please'); elem.focus(); return false; } } </script> <form action="submit.htm" onsubmit="return isAlphabet(document.getElementById('letters'))" method="post"> Letters Only: <input type='text' id='letters'/> <input type="submit" value="Chick Field"> </form>

Checking for All Letters


This function will be identical to isNumeric except for the change to the regular expression we use inside the match function. Instead of checking for numbers we will want to check for all letters. If we wanted to see if a string contained only letters we need to specify an expression that allows for both lowercase and uppercase letters: /^[a-zA-Z]+$/. JavaScript Code: // If the element's string matches the regular expression it is all letters function isAlphabet(elem){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true;

Restricting the Length


Being able to restrict the number of characters a user can enter into a field is one of the best ways to prevent bad data. For example, if you know that the zip code field should only be 5 numbers you know that 2 numbers is not sufficient. Below we have created a lengthRestriction function that takes a text field and two numbers. The first number is the minimum number of characters and the second is the maximum number of a characters the input can be. If you just want to specify an exact number then send the same number for both minimum and maximum. JavaScript Code: function lengthRestriction(elem, min, max){ var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } Here's an example of this function for a field that requires 6 to 8 characters for a valid username. Working Example: <script type='text/javascript'> function lengthRestriction(elem, min, max){ var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false;

Checking for Numbers and Letters


By combining both the isAlphabet and isNumeric functions into one we can check to see if a text input contains only letters and numbers. JavaScript Code: // If the element's string matches the regular expression it is numbers and letters function isAlphanumeric(elem){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(Enter Alphanumeric Values); elem.focus(); return false; } }

} } </script> <form action="submit.htm" onsubmit="return lengthRestriction(document.getElementById('restrict'), 6, 8)" method="post"> Username(6-8 characters): <input type='text' id='restrict'/> <input type='submit' value='Check Field' /> </form>

} } Working Example: <script type='text/javascript'> function madeSelection(elem){ if(elem.value == "Please Choose"){ alert('Please Choose Something'); elem.focus(); return false; }else{ return true; } } </script> <form action="submit.htm" onsubmit="return madeSelection(document.getElementById('selection'))" method="post"> Selection: <select id='selection'> <option value="Please Choose">Please Choose</option> <option value="CA">CA</option> <option value="WI">WI</option> <option value="XX">XX</option> </select> <input type='submit' value='Check Field' /> </form>

Selection Made
To be sure that someone has actually selected a choice from an HTML select input you can use a simple trick of making the first option as helpful prompt to the user and a red flag to you for your validation code. By making the first option of your select input something like "Please Choose" you can spur the user to both make a selection and allow you to check to see if the default option "Please Choose" is still selected when the submit the form.
JavaScript Code: function madeSelection(elem){ if(elem.value == "Please Choose"){ alert('Please Choose Something'); elem.focus(); return false; }else{ return true;

Email Validation
And for our grand finale we will be showing you how to check to see if a user's email address is valid. Every email is made up for 5 parts:

} Working Example: <script type='text/javascript'> function emailValidator(elem){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9] {2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert('Not a Valid Email'); elem.focus(); return false; } } </script> <form action="submit.htm" onsubmit="return emailValidator(document.getElementById('emailer'))" method="post"> Email: <input type='text' id='emailer'/> <input type='submit' value='Check Field' /> </form>

1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores 2. The at symbol @ 3. A combination of letters, numbers, hyphens, and/or periods 4. A period 5. The top level domain (com, net, org, us, gov, ...) Valid Examples:

bobby.jo@filltank.net jack+jill@hill.com the-stand@steven.king.com

Invalid Examples:

@deleted.net - no characters before the @ free!dom@bravehe.art - invalid character ! shoes@need_shining.com - underscores are not allowed in the domain name

The regular expression to check for all of this is a little overkill and beyond the scope of this tutorial to explain thoroughly. However, test it out and you'll see that it gets the job done. JavaScript Code: function emailValidator(elem){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9] {2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert('Not a Valid Email'); elem.focus(); return false; }

Validating a Form - All at Once


If you've made it this far I commend you, but we're not done yet! The final step is to be able to perform all of these validation steps when the user is ready to submit their data. Each form has a JavaScript event called onSubmit that is triggered when its submit button is clicked. If this even returns 0 or false then a form cannot be submitted, and if it returns 1 or true it will always be submitted. Wouldn't it be perfect if we could somehow make an if statement that said "If the form is valid submit it (1) else don't submit it (0)"? Well with a master formValidator function we can do just that. formValidator will be somewhat like a list of checks that we want to do before a form is submitted. But before we can decide what we want to check for, we need to have our form!
} } } } return false;

} }

To check for completion we will ensure no fields are empty and that the SELECT field has a selection. Here are the starting pieces of our master validation function formValidator.
HTML & JavaScript Code:
<script type='text/javascript'> function formValidator(){ // Make quick references to our fields var firstname = document.getElementById('firstname'); var addr = document.getElementById('addr'); var zip = document.getElementById('zip'); var state = document.getElementById('state'); var username = document.getElementById('username'); var email = document.getElementById('email'); // Check each input in the order that it appears in the form! if(isAlphabet(firstname, "Please enter only letters for your name")){ if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){ if(isNumeric(zip, "Please enter a valid zip code")){ if(madeSelection(state, "Please Choose a State")){ if(lengthRestriction(username, 6, 8)){ if(emailValidator(email, "Please enter a valid email address")){ return true;

} function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); // set the focus to this input return false; } return true; } function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false;

} } function lengthRestriction(elem, min, max){ var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } </script> <form onsubmit='return formValidator()' > First Name: <input type='text' id='firstname' /><br /> Address: <input type='text' id='addr' /><br /> Zip Code: <input type='text' id='zip' /><br /> State: <select id='state'> <option>Please Choose</option> <option>AL</option> <option>CA</option> <option>TX</option> <option>WI</option> </select><br />

Username(6-8 characters): <input type='text' id='username' /><br /> Email: <input type='text' id='email' /><br /> <input type='submit' value='Check Form' /> </form>

Beginner's Guide to SSI (server side includes)


Don't worry, SSI doesn't require a rocket-science degree to understand and use. It is, however, a highly useful feature that lets you do incredibly time saving tasks such as include the contents of an external file across multiple pages on your site, or access and display server specific information such as the current server time, visitor's IP address, etc. In this tutorial I'll introduce new comers to the wonderful world of SSI! SSI is short for Server Side Includes, by the way.

Does my server support SSI?


The first thing that needs to be settled is whether your server supports SSI and have it enabled. SSI is a Linux/Apache specific feature, so if you're on a Windows server for example, you'll need to look for the Windows equivalent of SSI (sorry, not a Window's guy). To test if your server supports SSI then, you can run a simple test, by inserting the below code inside a webpage, and saving the page with a .shtml extension (the most common extension configured to parse SSI by default): test.shtml source:
<!--#echo var="DATE_LOCAL" -->

<!--#include virtual="/includes/navbar.txt"--> <!--#include virtual="../navbar.txt"-->

With the first code, I'm telling the server to look for "navbar.txt" inside the "includes" directory that's directly beneath the root HTML directory (ie: http://www.mysite.com/includes), while in the second code, I'm simply telling it to look in the parent directory of the page that's including "navbar.txt" As shown, you're also not limited to just including .htm files, but other static text files such as .txt. You cannot, however, include .cgi files using this syntax without additional configuration to your server. Just FYI, both the left menu and copyright footer on this page and across the site are dynamically included using SSI using two external files. To update the copyright notice for example, all I have to do is make one simple modification to one of these files, and the changes are reflected across the entire site.

When you run test.shtml in your browser, you should see the current date plus time of your server displayed: Saturday, 15-Jan-2011 07:18:26 MST

Echoing server information such as user IP, current date etc using SSI
Another common and practical usage of SSI is to display basic information about your server or your visitors, such as the last modified date of the webpage, current server time, visitor IP address etc. These are all tasks that client side languages such as JavaScript cannot accomplish, but can be done using the #echo command of SSI.. Here's a quick overview of some of variables you can use with SSI's #echo to display useful information: DATE_GMT DATE_LOCAL DOCUMENT_NAME DOCUMENT_URI LAST_MODIFIED HTTP_REFERER REMOTE_ADDR #flashmod The current server date, in Greenwich mean time. Format using #config. The current server date. Format using #config. The file name of the current document. The virtual path of the current document. The last modified date of the document. Format using #config. URL of the document the client derived from to get to current document. IP address of the visitor. Command to display last modified date/time of

Using SSI to include the contents of an external file


The most common usage of SSI is to include the contents of an external file onto a page or across multiple pages on your site. Modify the external file, and all pages that have this file embedded is also updated with the modified information. For a site that uses the same header, navigational menu, or footer across pages, for example, this can save you countless time and energy. The syntax to embed the contents of an external file onto the current page is:
<!--#include file="external.htm"--> <!--#include virtual="/external.htm"-->

Which one to use depends on where "external.htm" is located. The first command assumes that the file is located in the same directory as the document containing it while the second syntax uses an absolute reference to "external.htm" starting from your root HTML directory. Typically you'll want to turn to the second syntax, as the external files to include most likely will be in a central directory while the pages including them are scattered across different directories. Here are a couple of more examples of the second syntax:

a document or file on the server. Format using #config. #fsize Command to display file size of a document or file. Format using #config.

Index page last modified: <!--#flastmod virtual="/index.html"-->

Sample output: greenday.mp3 last modified Thursday, 06-Jan-2005 05:35:27 EST.

To echo something using SSI, the syntax is:


<!--#echo var="VARIABLE HERE" -->

Echoing visitor IP address


This is also a commonly requested question and answer- how to display the user's IP address:
Your IP: <!--#echo var="REMOTE_ADDR" -->

Lets see how to use these variables exactly.

Echo current server date and time


To display the current server date and time, use either the "DATE_GMT" or "DATE_LOCAL" variable. In its simplest form:
<!--#echo var="DATE_LOCAL" -->

Output: Your IP: 117.207.130.212

Displaying file size of a document


Finally, you can display the file size of any document on your server using #echo, by using a different command called #fsize.
This document's file size: <!--#fsize file="current.shtml" --> The file size of main index page: <!--#fsize virtual="/index.shtml" -->

Output: Saturday, 15-Jan-2011 07:28:47 MST Not bad eh for one simple line of code.

Echo last modified date of current document or file


It's very useful at times to show the last modified date of a web page:
This document last modified: <!--#echo var="LAST_MODIFIED" -->

Sample output: This document's file size: 8.4K

Interesting Uses of SSI


The interesting thing to note about using the output commands of SSI is that they can be embedded anywhere inside your HTML source, even in unexpected places to do interesting things. For example, you can use SSI echo to populate a JavaScript variable with the visitor's IP address, then continue to use JavaScript to react accordingly:
<script type="text/javascript"> var userIP="<!--#echo var="REMOTE_ADDR" -->" if (userIP=="list of bad IPs to check") alert("You are not allowed on this site.") </script>

Output: This document last modified: Saturday, 04-Mar-2006 01:41:24 MST

Echo last modified date of any document or file


You can also display the last modified date of any document or file on your server besides the present, by using another command called #flastmod instead of #echo:
greenday.mp3 last modified: <!--#flastmod file="grenday.mp3"-->

Another unconventional usage is to pass the current server time to the JavaScript Date object, then use JavaScript to display the current live time of your server:
var currentime="<!--#echo var="DATE_LOCAL" -->" var serverdate=new Date(currenttime) //rest of script

%e %H %I %j %m %M %n %p %r %R %S %t %T %U %w %W %x %X %y %Y %Z

day of month - 1 to 31 hour - 00 to 23 hour - 01 to 12 day of year - 001 to 366 month of year - 01 to 12 minute - 00 to 59 insert a newline character string containing AM or PM time as %I:%M:%S %p time as %H:%M second - 00 to 59 insert a tab character time as %H:%M:%S week number of year (Sunday is the first day of the week) - 00 to 53 day of week - Sunday=0 week number of year (Monday is the first day of the week) - 00 to 53 Country-specific date format Country-specific time format year within century - 00 to 99 year as CCYY (4 digits) timezone name

25 15 03 361 12 09 PM 06:08:05 PM 15:09 02 15:21:07 52 0 51 12/25/05 04:50:29 05 2005 PST

Using #config to customize time format and more


On the previous page I showed you SSI's ability to output various server information, such as the size of a file, current date and time etc. This is all great stuff, but a question that quickly follows is "Can I customize the format of the output such as of the date and time?" Sorry, got to learn to just be content! Just kidding. Yes, it's certainly possible, thanks to another SSI command called #config. Take a look at this:
<!--#config timefmt="%m/%d/%y" --> <!--#echo var="DATE_LOCAL" -->

Output: 01/15/11 Instead of a long string containing both the date and time, I've used #config to pound things into exactly the format I want. Lets see now the various parameters of the #config command at your disposal:

CODE %a %A %b %B %c %d %D

PURPOSE OF CODE abbreviated weekday name full weekday name abbreviated month name full month name locale's appropriate date and time day of month - 01 to 31 date as %m/%d/%y

Sample output Sun Sunday Jan January Sun Dec 28 04:45:57 2005 25 12/25/05

Here are a couple more examples:


<!--#config timefmt="%A %d %B, %Y" --> <!--#echo var="DATE_LOCAL" -->

Output: Saturday 15 January, 2011


<!--#config timefmt="%D %r"--> This document last modified: <!--#echo var="LAST_MODIFIED" -->

on a feature without paying more, so to be safe, you should check with them first.

Enabling SSI on regular html pages


Now, the above requires that your webpages be named with a .shtml extension in order for SSI to be enabled for that page. If you're going to be using SSI across the board, you may want to consider just turning on SSI for regular .html and .htm pages, so you don't have to rename your files or follow the .shtml convention. To do this, add the below code to your .htaccess file:
AddHandler server-parsed .html AddHandler server-parsed .htm

Output: This document last modified: 03/04/06 01:41:24 AM

Formatting file size with #config


So far on this page I've only used the #config command to format time related output. But you can also use this command on file size output:
<!--#config sizefmt="abbrev"--> <!--#fsize file="current.shtml" --> <!--#config sizefmt="bytes"--> <!--#fsize file="current.shtml" -->

Viola, SSI should now be enabled for regular HTML pages as well!

What's a cookie?
A cookie is a small piece of information stored by the web browser on the client machine in a text (.txt) file which can be retrieved later. A script/program either on server side or client side may request the web browser to store a cookie. Cookie information is stored as a name value pairs. JavaScript provides document.cookie property for manipulation of a clientside cookie. One can set the cookie property at any time. Cookies can be very useful for State Maintenance/Persistence across different pages of the site, for

The first code tells the server to display the file size in abbreviated form, rounded to the nearest kilobytes. The second example obviously displays the size in bytes instead.

Manually enabling SSI on your server


If you're on a Linux+Apache server that probably supports SSI but just doesn't have it enabled, you can try manually turning it on using the magical little file called .htaccess. Simply create an empty txt file called .htaccess, and add the below to it:
AddType text/html .shtml AddHandler server-parsed .shtml Options Indexes FollowSymLinks Includes

HTTP is a state less protocol. In english, it means cookies can be used for "remembering" certain data specific to the user (such as User ID) as he browses different pages of the site. Session variables used in server side scripts such as ASP make use of cookies for this purpose. To allow user-side customization of web information, to serve a personalized site, as done by Yahoo and few others. A cookie can be sent back only to the server which created it. Thus, allowing a two way communication of a cookie. Many web servers use this to store user preferences, user ID on the user machine; which are sent back to them when user revisits the same site. This information can then be used by the web server to enhance and personalize the user experience. The cookies are stored and sent by the web-browser, provided that it is cookie enabled. Usually, cookies

Then, upload this file to the root HTML directory of your server account, enabling SSI across the entire site for any web page with a .shtml extension. To isolate SSI ability to just a specific sub directory, upload this file to that directory instead. Now, assuming this works, you should now make sure your web host allows you to manually turn on SSI. Some hosts may not like the idea of you turning

are pretty safe and most sites use them widely. Moreover, most sites will not work as desired if you disable cookies.

4.

bSecure - A boolean value (true/false), if this cookie is meant for communication over a secure channel, for HTTPS cookies only. This function creates a cookie string from the given arguments (by URL encoding name=value attributes), and sets the cookie as
document.cookie = szCookieText; //constructed cookie string function getCookie(szName) - To read the cookie set by setCokie(...)

How do I use cookies?


As you must have noticed by now, the important steps in cookie manipulation are Create A Cookie - Create or set a cookie on user machine having

cookie name, cookie value and the time when cookie should get deleted automatically (EXPIRES atribute, this is optional). If this is not specified the cookie is called a session cookie and it expires (gets deleted) when user's session ends, i.e. when the browser is closed. The additional information that can be optionally stored in the cookie includes (1)Path, (2)Domain, (3)Secure. Secure is used only over a secure communication channel ( currently only HTTPS). Read The Cookie - Read the stored cookie and extract its value. This requires only cookie name. Remember that you can only read the cookie which is created by your script/program. Delete The Cookie - This may not be always done, as expires attribute takes care of it. To delete a cookie set/create a cookie with the exactly same PATH (if any) and NAME values, and an EXPIRES value which is in the past. The JavaScript code here lets you manipulate cookies by using three function to do above mentioned tasks. For creating a cookie, for reading a cookie and for deleting a cookie. The cookie functions are provided in a reusable .js file (named as cookies.js) which also contains function documentation. The function prototypes and usage function

function. The only argument which it takes is the cookie name szName, which is set by the previous function. This function returns the cookie value read, which can be parsed if necessary, to get the required data. This function simply parses document.cooke for the given cookie name, and returns the extracted cookie value in the original format (by URL decoding the value). function deleteCookie(szName) - You can use this function optionally to delete the cookie. It takes only one parameter cookie name, szName and deletes the cookie immediately. This function simply sets the same cookie with an expires attribute which is in the past, thus deleting it immediately irrespective of the original expires attribute. You can include this file in your HTML file(s), to create and read cookies easily by calling these functions without any modification. As an example, consider creating and reading a cookie that is used in this page, using these functions //for creating a cookie <script type="text/javascript"> <!-var today = new Date(); var nextMonth = new Date(today.getYear(), today.getMonth()+1, today.getDate()); setCookie("technofundoDemoCookie", "Manish", nextMonth); // --> </script> This will set a cookie named 'technofundoDemoCookie' with value 'Manish' on

setCookie(szName, szValue [,szExpires] [,szPath] [,szDomain] [,bSecure]) - To create/set a cookie. It requires at least two arguments szName and szValue, and 4 optional arguments 1. szExpires - A Date object specifying the date on which the cookie expires. 2. szPath - A string argument specifying path, / is the common value. 3. szDomain - A string argument specifying the domain attribute for this cookie.

the user machine which expires one month after its creation. It uses only 3 arguments of the available 6 ones. //for reading the cookie <script type="text/javascript"> <!-var szName = getCookie("technofundoDemoCookie"); // --> </script> In this code snippet, the variable szName will contain the value of the cookie named 'technofundoDemoCookie' which has been set earlier. This variable can be later used as required. //for deleting the cookie <script type="text/javascript"> <!-deleteCookie('technofundoDemoCookie'); // --> </script> It simply calls the deleteCookie() function with the cookie name 'technofundoDemoCookie' to delete the cookie. In the end Although cookies are very useful for all these reasons and perhaps more, here are few things you should know.
The browser or user can delete cookies before its expires. Many people can share one machine and one person can use multiple

Frames and Windows:


On of the most important objects in JavaScript is the Window object. One of its primary children, or properties, is the Frames array. The Frames array is used to reference the Window objects of the frames in a frame set. Both of these object allow you to target content to windows and frames in the user's Web browsing session, as well as do Window object level processing of documents. The materials in this section address the use of JavaScript to move information between frames and windows as well as how to open and close windows using JavaScript. We will start with frames. They seem more complicated at first, but are actually easier to work with than windows when dealing with multiple document view ports (frames or windows) during a browsing session.

Frames
A frame is a window within a window. Using frames allows you to divide a browser window into a collection of panes. Each pane can then be used to display a separate document. As far as JavaScript is concerned, each frame can be treated as a separate window. In fact, each frame has its own Window object. JavaScript establishes relationships between the Window objects of frames, creating a hierarchy of Window objects. Each frame is stored as an element in the frames[] array of the Window object of the parent window for that frame. The contents of each element of the frames[] array is a Window object for the frame pane in question. Frames are created in a special HTML document called a frameset document. Frameset documents have their own DTD that is separate from the XHTML and HTML document DTDs. You may recall when we first mentioned DTDs for XHTML, we said there were three: transitional, strict, and frameset.

machines, so cookies are not always reliable completely. Do not rely only on cookies for state maintenance/persistence, support it with server side as well. Do not store sensitive information in cookies. Do respect user privacy.

The frameset document has no body element, instead it has a frameset element, which is delimited by <frameset> tags. A typical frameset document might look as follows:
<html> <head> <title>A simple frames document</title> </head> <frameset cols="200,*"> <frame name="frame1" src="document1.html" /> <frame name="frame2" src="document2.html" /> </frameset> </html>

As we stated early on, the Window object is the global object, so if each frame has its own Window object, how do we address the other frames?

parent and top


The Window object has some properties specifically designed to address the situation of having a hierarchical arrangement of windows. These are top and parent.
window.parent refers to the Window object of the parent window. Thus, in

the above coding snippet, if you wanted to use some code in frame1 to change something in frame2, you could address it with the following:
window.parent.frame2.someElement. window.top is a reference to the Window object of the top window element

The <frameset> tag defines how the frames are to be laid out on the screen. It has two attributes to do this, cols, which specifies how many columns to split the screen into, and rows, which specifies how many rows to split the screen into. Each specifies that number by a listing of the width of each column or height of each row to be created. This size can be specified as a numberic value, representing pixels, as a percentage of the screen, or using the wild card (an asterisk - *) to signifies to use whatever space is left over. For the above document, there are three window objects. There is the top-level window that the frameset document has been loaded into. There are also two frames, each with its own window object, that are children of the top-level window. From the top-level window, the two other windows are contained within its frames[] array. Thus, from the top level they could be addressed by their index positions, window.frames[0] and window.frames[1], or by their name attributes, window.frame1 and window.frame2. Unfortunately, you normally are not referring to the frames from within the top-level window, but rather, within the frames themselves. That is to say, within the documents that have been loaded into those frames. For instance, one frame may contain a menu that performs certain actions on the document in the other window when you click on the options provided. In fact, any code within the documents within the frame panes thinks that the Window object is the Window object for that pane, not the parent Window object for the entire frame set.

in the window hierarchy. Thus if you have multiple levels of nested frames, you can get to the top of the frameset hierarchy. Otherwise, you would have to repeat the parent property for each level we wanted to step out. This can get tedious quickly:
window.parent.parent.parent.otherframe.someElement

In our example above, since there is only one level of nesting, window.top and window.parent are synonymous. Of course, if you want to address a frame that is multiple levels down in the hierarchy, you still have to specify the name or frames[] array position of each intermediate Window object on the way down:
window.parent.fLeft.fBottom.someElement window.parent.frames[0].frames[2].someElement

The advantage of being able to address between frames like this goes beyond the simple ability to get the scripts to talk to other frames. It also allows you to better structure your code by modularizing your scripts. For instance, by putting all your common scripts that are used by all pages in your top-level frameset document, you then only need to include them once, in one place, and all pages know where they are. Since object tree elements can

be passed to variables, you can make the scripts generic, by passing along the name of the frame the code is actually supposed to apply to.
function doSomething(frameName) { frameName.status = 'Are you talking to me?'; } [ ... ] <input type="button" value="Click Me" onclick="doSomething(window.parent.frame2);" />

Since the windows cannot be associated through HTML code (there is no HTML tag for "other window"), you need to do something within JavaScript to associate them. The way windows can be associated through JavaScript is by using JavaScript code in one window to open another window. Windows opened by other windows can be used to create a hierarchy of parent-child relationships that can then be walked by the code in the different windows. This relationship between windows bears a strong resemblance to the relationships between frames. The only real difference is that JavaScript is a little stricter about what can happen between windows. Opening a New Window You open a new window with the window.open( ); method. It takes four parameters. The first one is required, though it can be an empty string. The parameters are:

Clearing Frames
Another useful thing you can do with JavaScript is create a framebuster, which prevents a document from loading into another frame. The code for it is as follows:
if (window.location.href != window.top.location.href) { window.top.location.replace(window.location.href); }

In other words, if the URL of the current document is not the same as the URL as the top level in the window hierarchy, then replace the URL of the top-level Window object with that of the current document. If you are at the top level, then the top property will point to the current Window object and the two values will be the same. You can do the same thing in the other direction if you want to make sure that a document always occurs in a frame set.
if (window.location.href == window.top.location.href) { window.top.location.replace('mainframe.html'); }

the URL of the page to be opened the name of the window to open the page in the properties of the window a boolean that specifies whether to replace the old document with the new document in the history list or not
// open a document called 'thisdoc.html' // in a window named 'win02' window.open('thisdoc.html', 'win02'); // open 'win02' with nothing in it window.open('', 'win02');

Inline Frames
Newer browsers also allow the <iframe> tag to define an inline frame. The same rules for addressing frames applies to inline frames as to regular frames. The only different is that the top-level window contains a normal HTML document instead of a frameset document.

If you specify the name of a window that already exists, then the browser opens the new document in the specified window rather than opening a new window. The last parameter only serves any function when putting a new document in a current named window. Note that opening a new window will open that window in the foreground, but opening a new document in an existing window will not bring that window to the foreground. If you want to do that you must also give the window focus. The easiest way to do this is provide the document in the new window with a script that executes on loading with the line self.focus( );

Working with Other Windows


JavaScript also allows you to write code that works between windows.

The third parameter allows you to specify the display properties of the new window. It is a collection of comma separated values. These values are keyword=value pairs. If the possible values for a property are "yes" and "no", then you can just provide the keyword if you want its value to be "yes". There must be no spaces inside the string. If you specify any properties, all yes/no properties not specified default to no and have to be explicitly declared. The properties available to you are: Property Values Description height integer The external height of the window. Takes an integer that represents the size of the window in pixels. To avoid malicious code in hidden windows you cannt make the window any smaller than the height of the title bar plus the window frame. You also cannot create a window without a title bar. width integer The external width of the window. Takes an integer that represents the size of the window in pixels. To avoid malicious code in hidden windows, you cannot set the width to below 100 pixels. You can, but the browser will ignore you. copyHisto yes|no Copy the history object from the current window to ry the new window. directories yes|no Show directory buttons. location yes|no Show the location bar. menubar yes|no Show the menu bar. status yes|no Show the status bar. toolbar yes|no Show the toolbar. resizeable yes|no Is the user allowed to resize the window. Note that in some browsers, even if you select no, the user can still maximize the window, they just can't resize it by dragging on its frame. scrollable yes|no Is the window scrollable. If no, then they will not even be able to scroll down with the mouse, so make sure it all fits on the screen. top integer Specifies how far from the top of the screen to position the window, in pixels. Note that the browser will not let you position something entirely off the

left

screen. integer Specifies how for from the left of the screen to position the window, in pixels. Note that the browser will not let you position something entirely off the screen.

Scripting Between Windows


Once you have named a window, you can just use that name whenever you want to refer to that window, right? Wrong. JavaScript falls down on this front. Sometimes you can refer to the window by name. Other times you cannot. For instance, the following will not work:
//-- bad code -window.open('', 'win02'); win02.document.write(somevar);

This is because the name you have assigned is actually a property of the new window, not of the current window. So if we can't refer to them by name, then how do we refer to them? Well, when the window.open method opens a new window, it returns as a value a reference to the window object of that new window. Thus, by assigning that reference to a variable you can then refer to that window from the window that opened it. The following code will work:
//-- good code -Win_02 = window.open('', 'win02'); Win_02.document.write(somevar);

Going in the other direction, from the parent back to the child, is a little easier. The Window object has an opener property which is a reference back to the window that opened the current window. Windows opened by the user have an opener property with a value of null.
// a reference to a property of the parent window window.opener[get_val];

Within a window, we can address all child windows, and all child windows of the parent window.

window.resizeTo(w,h)

Closing a Window
You can close a window with JavaScript as well.
// close the current window window.close( ); // close a child window windowname.close( ); // close the parent window window.opener.close( );

Resizes the window to the specified size in pixels. The first number is width. The second number is height.
window.resizeBy(w,h)

Resizes the window by the specified number of pixels.


window.moveTo(w,h)

Move the top left-hand corner of the window to the specified position in the window. The first number is pixels from the left hand side of the screen. The second number is number of pixels from the top.
window.moveBy(w,h)

You cannot use JavaScript to close a window containing a document from a different server, or opened by a different document without the browser asking for user confirmation. Except for the parent window, you cannot use JavaScript to close a user opened window. If you want to make sure that the window is actually open before you try to close it, you can test for the following:
// if // if test to see if window exists (typeof(windowName) != "undefined") { } test to see if a window is still open (!(windowName.closed)) { }

Move the top left-hand corner of the window by the specified amount in pixels in the window. // resize the current window to 200 pixels wide by 100 high window.resizeTo(200, 100); // add 100 pixels to the width of the window window.resizeBy(100,0); // move the window to a position // - 100 pixels over from the left hand side of the screen // - 50 pixels down from the top of the screen window.moveTo(100, 50): // move the window back up 25 pixels window.moveBy(0, -25);

The first will test to see if the window exists. A window, or any variable, that does not exist, will have a type of undefined. The second tests fdr whether the window.closed property has been set to true. If it is true, then the window has already been closed, the object has just not been cleaned up yet.

MIME Types:
MIME (Multipurpose Internet Mail Extensions) is an Internet standard for describes message content types. IME messages can contain text, images, audio, video, and other applicationspecific data.

Moving and Sizing Windows


The Window object also has methods to move and resize the window. These can be useful in certain applications of DHTML. This can be done with the following properties.

Official MIME info is provided by the Internet Engineering Task Force (IETF) in the following documents:

Type text: Human-readable text and source code


RFC-822 Standard for ARPA Internet text messages RFC-2045 MIME Part 1: Format of Internet Message Bodies RFC-2046 MIME Part 2: Media Types RFC-2047 MIME Part 3: Header Extensions for Non-ASCII Text RFC-2048 MIME Part 4: Registration Procedures RFC-2049 MIME Part 5: Conformance Criteria and Examples

Different applications support different MIME types. Type application: Multipurpose files

text/cmd: commands; subtype resident in Gecko browsers like FireFox 3.5 text/css: Cascading Style Sheets; Defined in RFC 2318 text/csv: Comma-separated values; Defined in RFC 4180 text/html: HTML; Defined in RFC 2854 text/javascript (Obsolete): JavaScript; Defined in and obsoleted by RFC 4329 in order to discourage its usage in favor of application/javascript. However, text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support text/plain: Textual data; Defined in RFC 2046 and RFC 3676 text/xml: Extensible Markup Language; Defined in RFC 3023

application/atom+xml: Atom feeds application/EDI-X12: EDI X12 data; Defined in RFC 1767 application/EDIFACT: EDI EDIFACT data; Defined in RFC 1767 application/json: JavaScript Object Notation JSON; Defined in RFC 4627 application/javascript: JavaScript; Defined in RFC 4329 but not accepted in IE 8 or earlier application/postscript: PostScript; Defined in RFC 2046 application/xhtml+xml: XHTML; Defined by RFC 3236 application/xml-dtd: DTD files; Defined by RFC 3023

Plugins:
Syntax document.plugins document.plugins[index ] The plugins property is an array that contains all the embedded objects and plug-ins that appear within the HTML document from using the tag. The plugins property length contains the number of items in the array. The index number ranges from zero to length - 1. The plugins[] array property accesses the same data as the document.embeds[] array property. Example:

Type audio: Audio


audio/basic: mulaw audio at 8 kHz, 1 channel; Defined in RFC 2046 audio/mp4: MP4 audio audio/mpeg: MP3 or other MPEG audio; Defined in RFC 3003

Type image

image/gif: GIF image; Defined in RFC 2045 and RFC 2046 image/jpeg: JPEG JFIF image; Defined in RFC 2045 and RFC 2046 image/png: Portable Network Graphics; Registered,[7] Defined in RFC 2083

Type message

message/http

<html> <h2>Learn Shapes</h2> <h2>A Circle</h2> <embed src="circle.gif"> <h2>A Square</h2> <embed src="square.gif"> <script language="JavaScript"> <!-document.write(document.plugins.length," embedded objects."); --> </script> </html>

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more. There are three main areas where PHP scripts are used.
Server-side scripting. This is the most traditional and main target field

for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs.

UNIT IV PHP
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode." What can PHP do?

PHP can be used on all major operating systems, including Linux, many Unix variants, Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers, PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor. So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content. One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

<h3>strpos() must have returned non-false</h3> <p>You are using Internet Explorer</p> <?php } else { ?> <h3>strpos() must have returned false</h3> <p>You are not using Internet Explorer</p> <?php } ?>

Adabas D dBase FilePro (read-only) Hyperwave IBM DB2 Informix InterBase FrontBase mSQL Direct MS-SQL MySQL ODBC Oracle (OCI7 and OCI8) Ovrimos PostgreSQL SQLite Solid Sybase Velocis Unix dbm

Basic syntax:
Escaping from HTML When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see PHP embedded in HTML documents, as in this example. <p>This is going to be ignored.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored.</p> You can also use more advanced structures: Example #1 Advanced escaping <?php if ($expression) { ?> <strong>This is true.</strong> <?php } else { ?> <strong>This is false.</strong> <?php } ?>

We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block: Example #3 Mixing both HTML and PHP modes <?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) { ?>

This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag. The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print(). There are four different pairs of opening and closing tags which can be used in PHP. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended. Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards. Example #2 PHP Opening and Closing Tags 1. <?php echo 'if you want to serve XHTML or XML documents, do it like thi s'; ?> 2. <script language="php"> echo 'some editors (like FrontPage) don\'t like processing instructions'; </script> 3. <? echo 'this is the simplest, an SGML processing instruction'; ?> <?= expression ?> This is a shortcut for "<? echo expression ?>" 4. <% echo 'You may optionally use ASP-style tags'; %> <%= $variable; # This is a shortcut for "<% echo . . ." %> While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two. Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.

ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive. Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.

Instruction separation:
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.
<?php echo 'This is a test'; ?> <?php echo 'This is a test' ?> <?php echo 'We omitted the last closing tag';

Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

Comments:
PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:
<?php echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */

echo 'This is yet another test'; echo 'One Final Test'; # This is a one-line shellstyle comment ?>

And finally two special types: resource NULL This manual also introduces some pseudo-types for readability reasons: mixed number callback And the pseudo-variable $.... Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons. The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used. Note: To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:
<?php $a_bool = TRUE; // a boolean $a_str = "foo"; // a string $a_str2 = 'foo'; // a string $an_int = 12; // an integer echo gettype($a_bool); // prints out: boolean echo gettype($a_str); // prints out: string // If this is an integer, increment it by four if (is_int($an_int)) { $an_int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($a_bool)) { echo "String: $a_bool";

The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.
<h1>This is an <?php # echo 'simple';?> example.</h1> <p>The header above will say 'This is an example'.</p>

'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.
<?php /* echo 'This is a test'; /* This comment will cause a problem */ */ ?>

Types:
PHP supports eight primitive types. Four scalar types: boolean integer float (floating-point number, aka double) string Two compound types: array object

} ?>

To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it. Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various type-related comparisons.

if ($show_separators) { echo "<hr>\n"; } ?>

Converting to boolean To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument. When converting to boolean, the following values are considered FALSE:

Booleans:
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE. Note: The boolean type was introduced in PHP 4. Syntax To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php $foo = True; // assign the value TRUE to $foo ?>

the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables) SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource). Warning -1 is considered TRUE, like any other non-zero (whether negative or positive) number!
<?php var_dump((bool) var_dump((bool) var_dump((bool) var_dump((bool) var_dump((bool) var_dump((bool) var_dump((bool) ?> ""); 1); -2); "foo"); array(12)); array()); "false"); // // // // // // // bool(false) bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)

Typically, some kind of operator which returns a boolean value, and the value is passed 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>\n"; } // ...because instead, this can be used:

Integers:
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

Syntax Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +). To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. Example #1 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) ?> Formally, the structure for integer literals is: decimal hexadecimal octal integer : [1-9][0-9]* |0 : 0[xX][0-9a-fA-F]+ : 0[0-7]+ : [+-]?decimal | [+-]?hexadecimal | [+-]?octal

Integer overflow If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead. Example #3 Integer overflow on a 32-bit system <?php $large_number = 2147483647; var_dump($large_number); $large_number = 2147483648; var_dump($large_number); $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); ?>

// int(2147483647) // float(2147483648)

// float(50000000000)

Example #4 Integer overflow on a 64-bit system <?php $large_number = 9223372036854775807; var_dump($large_number); // int(9223372036854775807) $large_number = 9223372036854775808; var_dump($large_number); // float(9.2233720368548E+18) $million = 1000000; $large_number = 50000000000000 * $million; var_dump($large_number); // float(5.0E+19) ?> There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.
<?php var_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3) var_dump(round(25/7)); // float(4) ?>

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5. Warning : If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored. Example #2 Octal weirdness
<?php var_dump(01090); // 010 octal = 8 decimal ?>

Converting to integer To explicitly convert a value to integer , use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function. From booleans FALSE will yield 0 (zero), and TRUE will yield 1 (one). From floating point numbers When converting from float to integer , the number will be rounded towards zero. If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens! Warning Never cast an unknown fraction to integer , as this can sometimes lead to unexpected results.
<?php echo (int) ( (0.1+0.7) * 10 ); // echoes 7! ?>

LNUM : [0-9]+ DNUM :([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM : [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM}) The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format). Floating point precision Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error progragation must be considered when several operations are compounded. Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118.... So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available. Converting to float For information on converting string s to float , see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float . See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float .

Floating point numbers:


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

Strings:
A string is series of characters, therefore, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies

Formally:

that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality. Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running. Syntax A string literal can be specified in four different ways:

echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?>

Double quoted If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters: Escaped characters Meaning linefeed (LF or 0x0A (10) in ASCII) carriage return (CR or 0x0D (13) in ASCII) horizontal tab (HT or 0x09 (9) in ASCII) vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5) form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5) backslash dollar sign double-quote the sequence of characters matching the regular expression is a \[0-7]{1,3} character in octal notation \x[0-9A-Fa-f] the sequence of characters matching the regular expression is a {1,2} character in hexadecimal notation Sequence \n \r \t \v \f \\ \$ \" As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed. The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

single quoted double quoted heredoc syntax nowdoc syntax (since PHP 5.3.0)

Single quoted The simplest way to specify a string is to enclose it in single quotes (the character '). To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning. Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline

Heredoc
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must

contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. Warning It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline. If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line. Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables. Example #1 Invalid example
<?php class foo { public $bar = <<<EOT bar EOT; } ?>

<?php var_dump(array(<<<EOD foobar! EOD )); ?>

As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax: Example #3 Using Heredoc to initialize static values
<?php // Static variables function foo() { static $bar = <<<LABEL Nothing in here... LABEL; } // Class properties/constants class foo { const BAR = <<<FOOBAR Constant example FOOBAR; public $baz = <<<FOOBAR Property example FOOBAR; } ?>

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. It is also possible to use the Heredoc syntax to pass data to function arguments: Example #2 Heredoc in arguments example

PHP 5.3.0 also introduces the possibility for Heredocs to use double quotes in declarings: Example #4 Using double quotes in Heredoc
<?php echo <<<"FOOBAR" Hello World! FOOBAR; ?>

Note: Heredoc support was added in PHP 4.

Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier. Example #5 Nowdoc string quoting example
<?php $str = <<<'EOD' Example of string spanning multiple lines using nowdoc syntax. EOD; /* More complex example, with variables. */ class foo { public $foo; public $bar; function foo() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<'EOT' My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 EOT; ?>

My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 Note: Unlike heredocs, nowdocs can be used in any static data context. Nowdoc support was added in PHP 5.3.0. Variable parsing When a string is specified in double quotes or with heredoc, variables are parsed within it. There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort. The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression. Simple syntax If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name. <?php $beer = 'Heineken'; echo "$beer's taste is great"; // works; "'" is an invalid character for variable na mes echo "He drank some $beers"; // won't work; 's' is a valid character for variabl e names but the variable is "$beer" echo "He drank some ${beer}s"; // works echo "He drank some {$beer}s"; // works ?>

String access and modification by character


Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array

The above example will output:

brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character. Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose. Warning : Writing to an out of range offset pads the string with spaces. Noninteger types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte. Example #9 Some string examples <?php // Get the first character of a string $str = 'This is a test.'; $first = $str[0]; // Get the third character of a string $third = $str[2]; // Get the last character of a string. $str = 'This is still a test.'; $last = $str[strlen($str)-1]; // Modify the last character of a string $str = 'Look at the sea'; $str[strlen($str)-1] = 'e'; ?> Note: Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL. Useful functions and operators Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information. There are a number of useful functions for string manipulation.

String Functions For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.
addcslashes Quote string with slashes in a C style addslashes Quote string with slashes bin2hex Convert binary data into hexadecimal representation chop Alias of rtrim chr Return a specific character chunk_split Split a string into smaller chunks convert_cyr_string Convert from one Cyrillic character set to another convert_uudecode Decode a uuencoded string convert_uuencode Uuencode a string count_chars Return information about characters used in a string crc32 Calculates the crc32 polynomial of a string crypt One-way string hashing echo Output one or more strings explode Split a string by string fprintf Write a formatted string to a stream get_html_translation_table Returns the translation table used by htmlspecialchars and htmlentities hebrev Convert logical Hebrew text to visual text hebrevc Convert logical Hebrew text to visual text with newline conversion html_entity_decode Convert all HTML entities to their applicable characters htmlentities Convert all applicable characters to HTML entities htmlspecialchars_decode Convert special HTML entities back to characters htmlspecialchars Convert special characters to HTML entities implode Join array elements with a string join Alias of implode lcfirst Make a string's first character lowercase levenshtein Calculate Levenshtein distance between two strings localeconv Get numeric formatting information ltrim Strip whitespace (or other characters) from the beginning of a string md5_file Calculates the md5 hash of a given file md5 Calculate the md5 hash of a string metaphone Calculate the metaphone key of a string money_format Formats a number as a currency string

nl_langinfo Query language and locale information nl2br Inserts HTML line breaks before all newlines in a string number_format Format a number with grouped thousands ord Return ASCII value of character parse_str Parses the string into variables print Output a string printf Output a formatted string quoted_printable_decode Convert a quoted-printable string to an 8 bit string quoted_printable_encode Convert a 8 bit string to a quoted-printable string quotemeta Quote meta characters rtrim Strip whitespace (or other characters) from the end of a string setlocale Set locale information sha1_file Calculate the sha1 hash of a file sha1 Calculate the sha1 hash of a string similar_text Calculate the similarity between two strings soundex Calculate the soundex key of a string sprintf Return a formatted string sscanf Parses input from a string according to a format str_getcsv Parse a CSV string into an array str_ireplace Case-insensitive version of str_replace. str_pad Pad a string to a certain length with another string str_repeat Repeat a string str_replace Replace all occurrences of the search string with the replacement string str_rot13 Perform the rot13 transform on a string str_shuffle Randomly shuffles a string str_split Convert a string to an array str_word_count Return information about words used in a string strcasecmp Binary safe case-insensitive string comparison strchr Alias of strstr strcmp Binary safe string comparison strcoll Locale based string comparison strcspn Find length of initial segment not matching mask strip_tags Strip HTML and PHP tags from a string stripcslashes Un-quote string quoted with addcslashes stripos Find position of first occurrence of a case-insensitive string stripslashes Un-quotes a quoted string stristr Case-insensitive strstr strlen Get string length

strnatcasecmp Case insensitive string comparisons using a "natural order" algorithm strnatcmp String comparisons using a "natural order" algorithm strncasecmp Binary safe case-insensitive string comparison of the first n characters strncmp Binary safe string comparison of the first n characters strpbrk Search a string for any of a set of characters strpos Find position of first occurrence of a string strrchr Find the last occurrence of a character in a string strrev Reverse a string strripos Find position of last occurrence of a case-insensitive string in a string strrpos Find position of last occurrence of a char in a string strspn Finds the length of the first segment of a string consisting entirely of characters contained within a given mask. strstr Find first occurrence of a string strtok Tokenize string strtolower Make a string lowercase strtoupper Make a string uppercase strtr Translate certain characters substr_compare Binary safe comparison of two strings from an offset, up to length characters substr_count Count the number of substring occurrences substr_replace Replace text within a portion of a string substr Return part of a string trim Strip whitespace (or other characters) from the beginning and end of a string ucfirst Make a string's first character uppercase ucwords Uppercase the first character of each word in a string vfprintf Write a formatted string to a stream vprintf Output a formatted string vsprintf Return a formatted string wordwrap Wraps a string to a given number of characters

String conversion to numbers When a string is evaluated in a numeric context, the resulting value and type are determined as follows. If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits. <?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?> For more information on this conversion, see the Unix manual page for strtod(3). To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on: <?php echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n"; ?> Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

Syntax Specifying with array() An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs. array( key => value , ... ) // key may only be an integer or string // value may be any value of any type
<?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices. If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?>

Arrays:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Warning : Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0. Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the

empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets. Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square bracket syntax


An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it. <?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> Note: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero). Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?> The above example will output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )

Useful functions There are quite a few useful functions for working with arrays. See the array functions section. Note: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function. <?php $a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* will produce an array that would have been defined as $a = array(1 => 'one', 3 => 'three'); and NOT $a = array(1 => 'one', 2 =>'three'); */ $b = array_values($a); // Now $b is array(0 => 'one', 1 =>'three') ?> The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array. Converting to array For any of the types: integer , float , string , boolean and resource , converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array) $scalarValue is exactly the same as array($scalarValue). If an object is converted to an array , the result is an array whose elements are the object 's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:
<?php class A { private $A; // This will become '\0A\0A' }

class B extends A { private $A; // This will become '\0B\0A' public $AA; // This will become 'AA' } var_dump((array) new B()); ?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. Converting NULL to an array results in an empty array . Array Functions
array_change_key_case Changes all keys in an array array_chunk Split an array into chunks array_combine Creates an array by using one array for keys and another for its values array_count_values Counts all the values of an array array_diff_assoc Computes the difference of arrays with additional index check array_diff_key Computes the difference of arrays using keys for comparison array_diff_uassoc Computes the difference of arrays with additional index check which is performed by a user supplied callback function array_diff_ukey Computes the difference of arrays using a callback function on the keys for comparison array_diff Computes the difference of arrays array_fill_keys Fill an array with values, specifying keys array_fill Fill an array with values array_filter Filters elements of an array using a callback function array_flip Exchanges all keys with their associated values in an array array_intersect_assoc Computes the intersection of arrays with additional index check array_intersect_key Computes the intersection of arrays using keys for comparison array_intersect_uassoc Computes the intersection of arrays with additional index check, compares indexes by a callback function array_intersect_ukey Computes the intersection of arrays using a callback function on the keys for comparison array_intersect Computes the intersection of arrays array_key_exists Checks if the given key or index exists in the array

array_keys Return all the keys of an array array_map Applies the callback to the elements of the given arrays array_merge_recursive Merge two or more arrays recursively array_merge Merge one or more arrays array_multisort Sort multiple or multi-dimensional arrays array_pad Pad array to the specified length with a value array_pop Pop the element off the end of array array_product Calculate the product of values in an array array_push Push one or more elements onto the end of array array_rand Pick one or more random entries out of an array array_reduce Iteratively reduce the array to a single value using a callback function array_replace_recursive Replaces elements from passed arrays into the first array recursively array_replace Replaces elements from passed arrays into the first array array_reverse Return an array with elements in reverse order array_search Searches the array for a given value and returns the corresponding key if successful array_shift Shift an element off the beginning of array array_slice Extract a slice of the array array_splice Remove a portion of the array and replace it with something else array_sum Calculate the sum of values in an array array_udiff_assoc Computes the difference of arrays with additional index check, compares data by a callback function array_udiff_uassoc Computes the difference of arrays with additional index check, compares data and indexes by a callback function array_udiff Computes the difference of arrays by using a callback function for data comparison array_uintersect_assoc Computes the intersection of arrays with additional index check, compares data by a callback function array_uintersect_uassoc Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions array_uintersect Computes the intersection of arrays, compares data by a callback function array_unique Removes duplicate values from an array array_unshift Prepend one or more elements to the beginning of an array array_values Return all the values of an array array_walk_recursive Apply a user function recursively to every member of an array array_walk Apply a user function to every member of an array

array Create an array arsort Sort an array in reverse order and maintain index association asort Sort an array and maintain index association compact Create array containing variables and their values count Count all elements in an array, or properties in an object current Return the current element in an array each Return the current key and value pair from an array and advance the array cursor end Set the internal pointer of an array to its last element extract Import variables into the current symbol table from an array in_array Checks if a value exists in an array key Fetch a key from an array krsort Sort an array by key in reverse order ksort Sort an array by key list Assign variables as if they were an array natcasesort Sort an array using a case insensitive "natural order" algorithm natsort Sort an array using a "natural order" algorithm next Advance the internal array pointer of an array pos Alias of current prev Rewind the internal array pointer range Create an array containing a range of elements reset Set the internal pointer of an array to its first element rsort Sort an array in reverse order shuffle Shuffle an array sizeof Alias of count sort Sort an array uasort Sort an array with a user-defined comparison function and maintain index association uksort Sort an array by keys using a user-defined comparison function usort Sort an array by values using a user-defined comparison function

Objects:
Object Initialization To create a new object, use the new statement to instantiate a class:
<?php class foo { function do_foo() {

echo "Doing foo.";

} $bar = new foo; $bar->do_foo(); ?>

Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.

NULL:
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL. Note: The null type was introduced in PHP 4. A variable is considered to be null if:

For a full discussion, see the Classes and Objects chapter. Converting to object If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.
<?php $obj = (object) 'ciao'; echo $obj->scalar; // outputs 'ciao' ?>

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; ?>

Resources:
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types. Note: The resource type was introduced in PHP 4 Converting to resource As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense. Freeing resources Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

See also the functions is_null() and unset(). Casting to NULL Casting a variable to null will remove the variable and unset its value.

Type Juggling:
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer. An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the

result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is. <?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> If the last two examples above seem odd, see String conversion to numbers. To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function. To test any of the examples in this section, use the var_dump() function. Note: The behaviour of an automatic conversion to array is currently undefined. Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:
<?php $a = 'car'; // $a is a string $a[0] = 'b'; // $a is still a string echo $a; // bar ?>

The casts allowed are:


(int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1 Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
<?php $foo = (int) $bar; $foo = ( int ) $bar; ?>

Casting literal strings and variables to binary strings:


<?php $binary = (binary) $string; $binary = b"binary string"; ?>

Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.
<?php $foo = 10; // $foo $str = "$foo"; // $str $fst = (string) $foo; // $fst // This prints out that "they if ($fst === $str) { echo "they are the same"; } ?> is an integer is a string is also a string are the same"

Type Casting:
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
<?php $foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is a boolean ?>

Variables:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive. Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. <?php $var = 'Bob'; $Var = 'Joe'; echo "$var, $Var"; // outputs "Bob, Joe" $4site = 'not yet'; // invalid; starts with a number $_4site = 'not yet'; // valid; starts with an underscore $tyte = 'mansikka'; // valid; '' is (Extended) ASCII 228. ?> By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice: <?php $foo = 'Bob'; // Assign the value 'Bob' to $foo $bar = &$foo; // Reference $foo via $bar. $bar = "My name is $bar"; // Alter $bar... echo $bar; echo $foo; // $foo is altered too. ?>

Predefined Variables PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Variable scope
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. Any variable used inside a function is by default limited to the local function scope. For example:
<?php $a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); ?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword First, an example use of global: Example #1 Using global

<?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?>

{ // Most predefined variables aren't "super" and require // 'global' to be available to the functions local scope. global $HTTP_POST_VARS; echo $HTTP_POST_VARS['name']; // Superglobals are available in any scope and do // not require 'global'. Superglobals are available // as of PHP 4.1.0, and HTTP_POST_VARS is now // deemed deprecated. echo $_POST['name']; } ?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Using static variables


Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example: Example #4 Example demonstrating need for static variables
<?php function test() { $a = 0; echo $a; $a++; } ?>

Example #2 Using $GLOBALS instead of global


<?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals: Example #3 Example demonstrating superglobals and scope <?php function test_global()

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static: Example #5 Example use of static variables
<?php function test() { static $a = 0; echo $a;

} ?>

$a++;

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:
<?php echo "$a ${$a}"; ?>

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it. Note: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error. Example #7 Declaring static variables <?php function foo(){ static $int = 0; // correct static $int = 1+2; // wrong (as it is an expression) static $int = sqrt(121); // wrong (as it is an expression too) $int++; echo $int; } ?>

Produces the exact same output as:


<?php echo "$a $hello"; ?>

i.e. they both produce: hello world. In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: $ {$a[1]} for the first case and ${$a}[1] for the second.

Note: Static declarations are resolved in compile-time.

Variables From External Sources:


HTML Forms (GET and POST)
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example: Example #1 A simple HTML form <form action="foo.php" method="post"> Name: <input type="text" name="username" /><br /> Email: <input type="text" name="email" /><br /> <input type="submit" name="submit" value="Submit me!" /> </form> Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

Variable variables
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
<?php $a = 'hello'; ?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
<?php $$a = 'world'; ?>

Example #2 Accessing data from a simple POST HTML form <?php // Available since PHP 4.1.0 echo $_POST['username']; echo $_REQUEST['username']; import_request_variables('p', 'p_'); echo $p_username; // As of PHP 5.0.0, these long predefined variables can be // disabled with the register_long_arrays directive. echo $HTTP_POST_VARS['username']; // Available if the PHP directive register_globals = on. As of // PHP 4.2.0 the default value of register_globals = off. // Using/relying on this method is not preferred. echo $username; ?> Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php? id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables(). Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0 Note: Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"]. As shown, before PHP 4.2.0 the default value for register_globals was on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly. Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.

PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input.

HTTP Cookies
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples. If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example: <?php setcookie("MyCookie[foo]", 'Testing 1', time()+3600); setcookie("MyCookie[bar]", 'Testing 2', time()+3600); ?> That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first. Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. Example #4 A setcookie() example
<?php if (isset($_COOKIE['count'])) { $count = $_COOKIE['count'] + 1; } else { $count = 1; } setcookie('count', $count, time()+3600);

setcookie("Cart[$count]", $item, time()+3600); ?>

Constants:
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* Example #1 Valid and invalid constant names
<?php // Valid constant names define("FOO", "something"); define("FOO2", "something else"); define("FOO_BAR", "something more"); // Invalid constant names define("2FOO", "something"); // This is valid, but should be avoided: // PHP may one day provide a magical constant // that will break your script define("__FOO__", "something"); ?>

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). If you simply want to check if a constant is set, use the defined() function. These are the differences between constants and variables:

Constants do not have a dollar sign ($) before them; Constants may only be defined using the define() function, not by simple assignment; Constants may be defined and accessed anywhere without regard to variable scoping rules; Constants may not be redefined or undefined once they have been set; and Constants may only evaluate to scalar values.

Example #1 Defining Constants <?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice. ?>

Example #2 Defining Constants using the const keyword


<?php // Works as of PHP 5.3.0 const CONSTANT = 'Hello World'; echo CONSTANT; ?>

Syntax
Only scalar data ( boolean , integer , float and string ) can be contained in constants. It is possible to define constants as a resource , but it should be avoided, as it can cause unexpected results. You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all defined constants.

Note: As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops or if statements.

Magic constants
PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in. There are seven magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows: Name __LINE__ Description The current line number of the file. The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always __FILE__ contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances. The directory of the file. If used inside an include, the directory of the included file is returned. This is __DIR__ equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.) The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it __FUNCTION__ was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was __CLASS__ declared (case-sensitive). In PHP 4 its value is always lowercased. The class method name. (Added in PHP 5.0.0) The __METHOD__ method name is returned as it was declared (casesensitive). __NAMESPACE__ The name of the current namespace (casesensitive). This constant is defined in compile-time

Name

Description (Added in PHP 5.3.0).

Expressions:
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value". The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant). After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen. Slightly more complex examples for expressions are functions. For instance, consider the following function:
<?php function foo () { return 5; } ?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something. Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators.

The following example should help you understand pre- and post-increment and expressions in general a bit better: <?php function double($i) { return $i*2; } $b = $a = 5; /* assign the value five into the variable $a and $b */ $c = $a++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ ?> Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement. There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
<?php $first ? $second : $third ?>

Operators:

Operator Precedence Arithmetic Operators Assignment Operators Bitwise Operators Comparison Operators Error Control Operators Execution Operators Incrementing/Decrementing Operators Logical Operators String Operators Array Operators Type Operators

Operator Precedence The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used. The following table lists the precedence of operators with the highestprecedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in. Operator Precedence Associativity Operators Additional Information non-associative clone new clone and new left [ array() non-associative ++ -increment/decrement ~ - (int) (float) (string) (array) right types (object) (bool) @ non-associative instanceof types right ! logical left */% arithmetic

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

Operator Precedence Associativity Operators Additional Information left +-. arithmetic and string left << >> bitwise non-associative < <= > >= <> comparison non-associative == != === !== comparison left & bitwise and references left ^ bitwise left | bitwise left && logical left || logical left ?: ternary = += -= *= /= .= %= &= |= ^= right assignment <<= >>= => left and logical left xor logical left or logical left , many uses Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.

divisible, in which case an integer value will be returned. Operands of modulus are converted to integers (by stripping the decimal part) before processing. Note: Remainder $a % $b is negative for negative $a.

Math Functions
abs acos acosh asin asinh atan2 atan atanh base_convert bindec ceil cos cosh decbin dechex decoct deg2rad exp expm1 - Absolute value - Arc cosine - Inverse hyperbolic cosine - Arc sine - Inverse hyperbolic sine - Arc tangent of two variables - Arc tangent - Inverse hyperbolic tangent - Convert a number between arbitrary bases - Binary to decimal - Round fractions up - Cosine - Hyperbolic cosine - Decimal to binary - Decimal to hexadecimal - Decimal to octal - Converts the number in degrees to the radian equivalent - Calculates the exponent of e - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero - Round fractions down - Returns the floating point remainder (modulo) of the division of the arguments - Show largest possible random value - Hexadecimal to decimal

Arithmetic Operators:
Remember basic arithmetic from school? These work just like those. Arithmetic Operators Name Result Negation Opposite of $a. Addition Sum of $a and $b. Subtraction Difference of $a and $b. Multiplication Product of $a and $b. Division Quotient of $a and $b. Modulus Remainder of $a divided by $b.

Example -$a $a + $b $a - $b $a * $b $a / $b $a % $b

floor fmod getrandmax hexdec

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly

hypot is_finite is_infinite is_nan lcg_value log10 log1p

log max min mt_getrandmax mt_rand mt_srand octdec pi pow rad2deg rand round sin sinh sqrt srand tan

- Calculate the length of the hypotenuse of a right - angle triangle - Finds whether a value is a legal finite number - Finds whether a value is infinite - Finds whether a value is not a number - Combined linear congruential generator - Base - 10 logarithm - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero - Natural logarithm - Find highest value - Find lowest value - Show largest possible random value - Generate a better random value - Seed the better random number generator - Octal to decimal - Get value of pi - Exponential expression - Converts the radian number to the equivalent number in degrees - Generate a random integer - Rounds a float - Sine - Hyperbolic sine - Square root - Seed the random number generator - Tangent - Hyperbolic tangent

Assignment Operators:
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to"). The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things: <?php $a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4. ?> For arrays , assigning a value to a named key is performed using the "=>" operator. The precedence of this operator is the same as other assignment operators. In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: <?php $a = 3; $a += 5; // sets $a to 8, as if we had said:$a=$a+5; $b = "Hello "; $b .= "There!"; //sets $b to "Hello There!", just like $b = $b . "There!"; ?>

Bitwise Operators:
Bitwise operators allow evaluation and manipulation of specific bits within an integer. Bitwise Operators Example Name Result $a & $b And Bits that are set in both $a and $b are set. $a | $b Or (inclusive or) Bits that are set in either $a or $b are set. $a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both

tanh

Example ~ $a Not

Name

$a << $b Shift left $a >> $b Shift right

Bitwise Operators Result are set. Bits that are set in $a are not set, and vice versa. Shift the bits of $a $b steps to the left (each step means "multiply by two") Shift the bits of $a $b steps to the right (each step means "divide by two")

$result = $value | $test; printf($format, $result, $value, '|', $test); } echo "\n Bitwise Exclusive OR (XOR) \n"; foreach ($values as $value) { $result = $value ^ $test; printf($format, $result, $value, '^', $test); } ?>

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved. Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

The above example will output:


--------result --------Bitwise AND ( 0 = 0000) = ( 1 = 0001) = ( 0 = 0000) = ( 4 = 0100) = ( 0 = 0000) = --------value --------( ( ( ( ( 0 1 2 4 8 = = = = = 0000) 0001) 0010) 0100) 1000) -- --------op test -- --------& & & & & | | | | | ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 = = = = = = = = = = = = = = = 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101) 0101)

Example #1 Bitwise AND, OR and XOR operations on integers


<?php $format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)' . ' %3$s (%4$2d = %4$04b)' . "\n"; echo <<<EOH --------- --------- -- --------result value op test --------- --------- -- --------EOH; $values = array(0, 1, 2, 4, 8); $test = 1 + 4; echo "\n Bitwise AND \n"; foreach ($values as $value) { $result = $value & $test; printf($format, $result, $value, '&', $test); } echo "\n Bitwise Inclusive OR \n"; foreach ($values as $value) {

Bitwise Inclusive OR ( 5 = 0101) = ( 0 = 0000) ( 5 = 0101) = ( 1 = 0001) ( 7 = 0111) = ( 2 = 0010) ( 5 = 0101) = ( 4 = 0100) (13 = 1101) = ( 8 = 1000)

Bitwise Exclusive OR (XOR) ( 5 = 0101) = ( 0 = 0000) ^ ( 4 = 0100) = ( 1 = 0001) ^ ( 7 = 0111) = ( 2 = 0010) ^ ( 1 = 0001) = ( 4 = 0100) ^ (13 = 1101) = ( 8 = 1000) ^

Comparison Operators:
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators Example Name Result $a == $b Equal TRUE if $a is equal to $b. $a === TRUE if $a is equal to $b, and they are of the Identical $b same type. (introduced in PHP 4) $a != $b Not equal TRUE if $a is not equal to $b. $a <> $b Not equal TRUE if $a is not equal to $b. TRUE if $a is not equal to $b, or they are not of $a !== $b Not identical the same type. (introduced in PHP 4) $a < $b Less than TRUE if $a is strictly less than $b. $a > $b Greater than TRUE if $a is strictly greater than $b. Less than or equal $a <= $b TRUE if $a is less than or equal to $b. to Greater than or $a >= $b TRUE if $a is greater than or equal to $b. equal to If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value. <?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true var_dump("10" == "1e1"); // 10 == 10 -> true var_dump(100 == "1e2"); // 100 == 100 -> true switch ("a") { case 0: echo "0"; break; case "a": // never reached because "a" is already matched with 0 echo "a"; break; } ?> For various types, comparison is done according to the following table (in order).

Comparison with Various Types Type of Type of Operand Operand Result 1 2 null or string Convert NULL to "", numerical or lexical comparison string bool or anything Convert to bool , FALSE < TRUE null Built-in classes can define its own comparison, different classes are uncomparable, same class - compare object object properties the same way as arrays (PHP 4), PHP 5 has its own explanation string , string , resource resource Translate strings and resources to numbers, usual math or or number number Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, array array otherwise - compare value by value (see following example) array anything array is always greater object anything object is always greater

Ternary Operator:
Another conditional operator is the "?:" (or ternary) operator. The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Example #3 Non-obvious Ternary Behaviour <?php // on first glance, the following appears to output 'true' echo (true?'true':false?'t':'f'); // however, the actual output of the above is 't' // this is because ternary expressions are evaluated from left to right // the following is a more obvious version of the same code as above echo ((true ? 'true' : false) ? 't' : 'f'); // here, you can see that the first expression is evaluated to 'true', which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression. ?>

Execution Operators:
PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().
<?php $output = `ls -al`; echo "<pre>$output</pre>"; ?>

Note: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

Error Control Operators:


PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it. <?php /* Intentional file error */ $my_file = @file ('non_existent_file') or die ("Failed opening file: error was '$php_errormsg'"); // this works for any expression, not just functions: $value = @$cache[$key]; // will not issue a notice if the index $key doesn't exist. ?> Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

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. Example Name ++$a Pre-increment $a++ Post-increment --$a Pre-decrement $a-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>Postincrement</h3>"; $a = 5; echo "Should be 5: " . $a++ . "<br />\n"; echo "Should be 6: " . $a . "<br />\n"; echo "<h3>Preincrement</h3>"; $a = 5; echo "Should be 6: " . ++$a . "<br />\n"; echo "Should be 6: " . $a . "<br />\n"; echo "<h3>Postdecrement</h3>"; $a = 5;

echo echo echo $a = echo echo ?>

"Should be 5: " . $a-- . "<br />\n"; "Should be 4: " . $a . "<br />\n"; "<h3>Predecrement</h3>"; 5; "Should be 4: " . --$a . "<br />\n"; "Should be 4: " . $a . "<br />\n";

Logical Operators Example Name Result $a && $b And TRUE if both $a and $b are TRUE. $a || $b Or 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.

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Example #1 Arithmetic Operations on Character Variables
<?php $i = 'W'; for ($n=0; $n<6; $n++) { echo ++$i . "\n"; } ?>

Example #1 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" // The result of the expression (false || true) is assigned to $e // Acts like: ($e = (false || true)) $e = false || true; // The constant false is assigned to $f and then true is ignored // Acts like: (($f = false) or true) $f = false or true; var_dump($e, $f); // "&&" has a greater precedence than "and" // The result of the expression (true && false) is assigned to $g // Acts like: ($g = (true && false)) $g = true && false; // The constant true is assigned to $h and then false is ignored // Acts like: (($h = true) and false) $h = true and false; var_dump($g, $h); ?> The above example will output something similar to:
bool(true) bool(false) bool(false) bool(true)

The above example will output:


X Y Z AA AB AC

Incrementing or decrementing booleans has no effect.

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

String Operators:
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information. <?php $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; // now $a contains "Hello World!" ?>

When executed, this script will print the following:


Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" }

Array Operators:
Example Name $a + $b Union $a == $b Equality Result Union of $a and $b. TRUE if $a and $b have the same key/value pairs. TRUE if $a and $b have the same key/value pairs in the same order and of the same types. TRUE if $a is not equal to $b. TRUE if $a is not equal to $b. TRUE if $a is not identical to $b.

Elements of arrays are equal for the comparison if they have the same key and value. Array Functions See also is_array(), explode(), implode(), split(), preg_split(), and unset().

$a === $b Identity $a != $b $a <> $b $a !== $b Inequality Inequality Non-identity

Type Operators:
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class: Example #1 Using instanceof with classes
<?php class MyClass { } class NotMyClass { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof NotMyClass); ?>

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. <?php $a = array("a" => "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); $c = $a + $b; // Union of $a and $b echo "Union of \$a and \$b: \n"; var_dump($c); $c = $b + $a; // Union of $b and $a echo "Union of \$b and \$a: \n"; var_dump($c); ?>

The above example will output:


bool(true) bool(false)

instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class: Example #2 Using instanceof with inherited classes
<?php class ParentClass { } class MyClass extends ParentClass { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof ParentClass); ?>

break continue switch return goto

If:
The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:
if (expr) statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section. The following example would display a is bigger than b if $a is bigger than $b:
<?php if ($a > $b) echo "a is bigger than b"; ?>

The above example will output: bool(true) bool(true) The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.

Control Structures

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:
<?php if ($a > $b) { echo "a is bigger than b"; $b = $a; } ?>

if else elseif/else if Alternative syntax for control structures while do-while for foreach

else:
Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. PHP features an else structure that is similar to that of C:
if (expr) statement1 else statement2

For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:
<?php if ($a > echo } elseif echo } else { echo } ?> $b) { "a is bigger than b"; ($a == $b) { "a is equal to b"; "a is smaller than b";

For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:
<?php if ($a echo } else echo } ?> > $b) { "a is greater than b"; { "a is NOT greater than b";

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

elseif/else if:
elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.
if expression1 statement1 elseif expression2 statement2 elseif expression3 statement3 . . . else statement n

Alternative syntax for control structures:


PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
<?php if ($a == 5): ?> A is equal to 5 <?php endif; ?>

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5. The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format:

<?php if ($a == 5): echo "a equals 5"; echo "..."; elseif ($a == 6): echo "a equals 6"; echo "!!!"; else: echo "a is neither 5 nor 6"; endif; ?>

While:
while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:
while (expr) statement

<?php /* example 1 */ $i = 1; while ($i <= 10) { echo $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 */ $i = 1; while ($i <= 10): echo $i; $i++; endwhile; ?>

do-while:
do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). There is just one syntax for do-while loops:
do statement while (expr)

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:
while (expr): statement ... endwhile;

Example:
<?php $i = 0; do { echo $i; } while ($i > 0); ?>

The following examples are identical, and both print the numbers 1 through 10:

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:
<?php do { if ($i < 5) { echo "i is not big enough"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } echo "i is ok"; /* process i */ } while (0); ?>

end the loop using a conditional break statement instead of using the for truth expression. Consider the following examples. All of them display the numbers 1 through 10:
<?php /* example 1 */ for ($i = 1; $i <= 10; $i++) { echo $i; } /* example 2 */ for ($i = 1; ; $i++) { if ($i > 10) { break; } echo $i; } /* example 3 */ $i = 1; for (; ; ) { if ($i > 10) { break; } echo $i; $i++; } /* example 4 */ for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); ?>

For:
for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3) statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop. In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends. At the end of each iteration, expr3 is evaluated (executed). Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions. PHP also supports the alternate "colon syntax" for for loops.
for (expr1; expr2; expr3): statement ... endfor;

Its a common thing to many users to iterate though arrays like in the example below.
<?php $people = Array( Array('name' => 'Kalle', 'salt' => 856412), Array('name' => 'Pierre', 'salt' => 215863) ); for($i = 0, $size = sizeof($people); $i < $size; ++$i) { $people[$i]['salt'] = rand(000000, 999999); } ?>

array pointer. Don't rely on the array pointer during or after the foreach without resetting it. As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value. <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?> This is possible only if iterated array can be referenced (i.e. is variable).

Foreach:
PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:
foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement

Break:
break ends execution of the current for, foreach, while, do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. <?php $arr = array('one', 'two', 'three', 'four', 'stop', 'five'); while (list(, $val) = each($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br />\n"; } /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />\n";

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element). The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop. Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop. Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the

break 2; /* Exit the switch and the while. */ default: break; } } ?>

Switch:
The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2. Note: Note that switch/case does loose comparision. The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement: Example #1 switch structure
<?php if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } ?>

Continue:
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue. continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. <?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n"; } ?> One can expect the result to be : 0 1 3 4 but this script will output : 2

Example #2 switch structure allows usage of strings


<?php switch ($i) {

} ?>

case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break;

echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; endswitch; ?>

Return:
If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file. If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended. Note: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case. Note: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return() with parentheses but with no arguments will result in a parse error. Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
<?php switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; } ?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type. The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.
<?php switch ($i): case 0: echo "i equals 0"; break; case 1:

Goto:
The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multilevel break. Example #1 goto loop example
<?php for($i=0,$j=50; $i<100; $i++) { while($j--) { if($j==17) goto end; } } echo "i = $i"; end: echo 'j hit 17'; ?>

User-defined functions Creating a function:


How to you build functions in PHP? Thats easy enough heres how you do that, formally speaking: A function may be defined using syntax such as the following: function function_name([argument_list]) { [statements] [return return_value;] } Any valid PHP code may appear inside a function, even other functions and class definitions. Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*. Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below. When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

The above example will output:


j hit 17

UNIT-IV PHP Functions:


Example #2 Conditional functions


<?php $makefoo = true; /* We can't call foo() from here since it doesn't exist yet, but we can call bar() */ bar(); if ($makefoo) { function foo() { echo "I don't exist until program execution reaches me

User-defined functions Function arguments Returning values Variable functions Internal (built-in) functions Anonymous functions

.\n"; } } /* Now we can safely call foo() since $makefoo evaluated to true */ if ($makefoo) foo(); function bar() { echo "I exist immediately upon program start.\n"; } ?>

Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

Example #4 Recursive functions


<?php function recursion($a) { if ($a < 20) { echo "$a\n"; recursion($a + 1); } } ?>

Example #3 Functions within functions


<?php function foo() { function bar() { echo "I don't exist until foo() is called.\n"; } } /* We can't call bar() yet since it doesn't exist. */ foo(); /* Now we can call bar(), foo()'s processesing has made it accessible. */ bar(); ?>

Function arguments
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions. Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Example #1 Passing arrays to functions <?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } ?>

Making arguments be passed by reference By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition: Example #2 Passing function parameters by reference <?php function add_some_extra(&$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' ?> Default argument values A function may define C++-style default values for scalar arguments as follows: Example #3 Use of default parameters in functions
<?php function makecoffee($type = "cappuccino") { return "Making a cup of $type.\n"; } echo makecoffee(); echo makecoffee(null); echo makecoffee("espresso"); ?>

Making a cup of espresso.

PHP also allows the use of array s and the special type NULL as default values, for example: Example #4 Using non-scalar types as default values <?php function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker; return "Making a cup of ".join(", ", $types)." with $device.\n"; } echo makecoffee(); echo makecoffee(array("cappuccino", "lavazza"), "teapot"); ?> The default value must be a constant expression, not (for example) a variable, a class member or a function call. Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet: Example #5 Incorrect usage of default function arguments <?php function makeyogurt($type = "acidophilus", $flavour) { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt("raspberry"); // won't work as expected ?> The above example will output: Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/phptest/functest.html on line 41 Making a bowl of raspberry . Now, compare the above with this:

The above example will output:


Making a cup of cappuccino. Making a cup of .

Example #6 Correct usage of default function arguments <?php function makeyogurt($flavour, $type = "acidophilus") { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt("raspberry"); // works as expected ?> The above example will output: Making a bowl of acidophilus raspberry. Note: As of PHP 5, default values may be passed by reference.

} ?>

The above example will output:


Number of arguments: 3 Argument 0 is: 1 Argument 1 is: 2 Argument 2 is: 3

Returning values
Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return() for more information. Note: If the return() is omitted the value NULL will be returned. Example #1 Use of return()
<?php function square($num) { return $num * $num; } echo square(4); // outputs '16'. ?>

Variable-length argument lists


PHP 4 and above has support for variable-length argument lists in user-defined functions. This is really quite easy, using the following functions. func_num_args() - Returns the number of arguments passed to the function func_get_arg() - Return an item from the argument list and func_get_args() - Returns an array comprising a function's argument list No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.

Example #1 func_get_args() example <?php foo(1, 2, 3); function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br />\n"; $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "<br />\n"; }

A function can not return multiple values, but similar results can be obtained by returning an array. Example #2 Returning an array to get multiple values
<?php function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); ?>

To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable: Example #3 Returning a reference from a function
<?php function &returns_reference() { return $someref; } $newref =& returns_reference(); ?>

Example #1 Variable function example


<?php function foo() { echo "In foo()<br />\n"; } function bar($arg = '') { echo "In bar(); argument was '$arg'.<br />\n"; } // This is a wrapper function around echo function echoit($string) { echo $string; } $func = 'foo'; $func(); // This calls foo() $func = 'bar'; $func('test'); // This calls bar() $func = 'echoit'; $func('test'); // This calls echoit() ?>

Variable functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

An object method can also be called with the variable functions syntax. Example #2 Variable method example <?php class Foo { function Variable() { $name = 'Bar'; $this->$name(); // This calls the Bar() method } function Bar() { echo "This is Bar"; } } $foo = new Foo(); $funcname = "Variable";

call_user_func() Call a user function given by the first parameter


Parameters function The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter. Additionally class methods of an object instance may be called by passing array($objectinstance, $methodname) to this parameter. parameter Zero or more parameters to be passed to the function. function_exists() Return TRUE if the given function has been defined

$foo->$funcname(); // This calls $foo->Variable() ?>

Example #1 Anonymous function example


<?php echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // outputs helloWorld ?> Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon: Example #2 Anonymous function variable assignment example <?php $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); $greet('PHP'); ?> Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example: Example #3 Closures and scoping

Internal (built-in) functions


PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to set up PHP. Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code. Note: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return NULL but this is just a convention, and cannot be relied upon.

Anonymous functions
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

<?php // A basic shopping cart which contains a list of added products // and the quantity of each product. Includes a method which // calculates the total price of the items in the cart using a // closure as a callback. class Cart {

const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95; protected $products = array(); public function add($product, $quantity) { $this->products[$product] = $quantity; } public function getQuantity($product) { return isset($this->products[$product]) ? $this->products[$product] : FALSE; } public function getTotal($tax) { $total = 0.00; $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2); } } $my_cart = new Cart; // Add some items to the cart $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); // Print the total with a 5% sales tax. print $my_cart->getTotal(0.05) . "\n"; // The result is 54.29 ?>

Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon. Note: Anonymous functions are available since PHP 5.3.0.

Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.

Classes and Objects


Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model. Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting. PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. The Basics Class Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*. A class may contain its own constants, variables (called "properties"), and functions (called "methods"). Example #1 Simple Class definition

<?php class SimpleClass { // property declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; } } ?>

$a = new A(); $a->foo(); // Note: the next line will issue a warning if E_STRICT is enabled. A::foo(); $b = new B(); $b->bar(); // Note: the next line will issue a warning if E_STRICT is enabled. B::bar(); ?> The above example will output:
$this $this $this $this is is is is defined (A) not defined. defined (B) not defined.

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). Example #2 Some examples of the $this pseudo-variable <?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } class B { function bar() { // Note: the next line will issue a warning if E_STRICT is enabled. A::foo(); } }

new To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement). Example #3 Creating an instance
<?php $instance = new SimpleClass(); // This can also be done with a variable: $className = 'Foo'; $instance = new $className(); // Foo() ?>

In the class context, it is possible to create a new object by new self and new parent. When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example #4 Object Assignment <?php $instance = new SimpleClass(); $assigned = $instance; $reference =& $instance; $instance->var = '$assigned will have this value'; $instance = null; // $instance and $reference become null var_dump($instance); var_dump($reference); var_dump($assigned); ?> The above example will output:
NULL NULL object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" }

// Redefine the parent method function displayVar() { echo "Extending class\n"; parent::displayVar(); } } $extended = new ExtendClass(); $extended->displayVar(); ?>

The above example will output:


Extending class a default value

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. Note: In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning. If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public. Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property. See Static Keyword for more information.

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::. When overriding methods, the parameter signature should remain the same or PHP will generate an E_STRICT level error. This does not apply to the constructor, which allows overriding with different parameters. Example #5 Simple Class Inheritance
<?php class ExtendClass extends SimpleClass {

The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). Example #1 property declarations
<?php class SimpleClass { // invalid property declarations: public $var1 = 'hello ' . 'world'; public $var2 = <<<EOD hello world EOD; public $var3 = 1+2; public $var4 = self::myStaticMethod(); public $var5 = $myVar; // valid property declarations: public $var6 = myConstant; public $var7 = array(true, false); // This is allowed only in PHP 5.3.0 and later. public $var8 = <<<'EOD' hello world EOD; } ?>

class_exists() get_called_class() get_class_methods() get_class_vars() get_class() get_declared_classes() get_declared_interfaces() get_object_vars() get_parent_class() interface_exists() is_a() is_subclass_of() method_exists() property_exists()

Checks if the class has been defined the "Late Static Binding" class name Gets the class methods' names Get the default properties of the class Returns the name of the class of an object Returns an array with the name of the defined classes Returns an array of all declared interfaces Gets the properties of the given object Retrieves the parent class name for object or class Checks if the interface has been defined Checks if the object is of this class or has this class as one of its parents Checks if the object has this class as one of its parents Checks if the class method exists Checks if the object or class has a property

Note: There are some nice functions to handle classes and objects. Classes/Object Functions
call_user_method_array() call_user_method() class_alias() Call a user method given with an array of parameters [deprecated] Call a user method on an specific object [deprecated] Creates an alias for a class

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.

Its also possible for interfaces to have constants. Look at the interface documentation for examples. As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static). Example #1 Defining and using a constant
<?php class MyClass { const constant = 'constant value'; function showConstant() { echo self::constant . "\n"; }

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error. Note: Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block and would result in a fatal error. From 5.3.0+ exceptions thrown in the __autoload function can be caught in the catch block, with 1 provision. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class. Note: Autoloading is not available if using PHP in CLI interactive mode. Note: If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the userinput in such functions or at least verify the input in __autoload().

} echo MyClass::constant . "\n"; $classname = "MyClass"; echo $classname::constant . "\n"; // As of PHP 5.3.0 $class = new MyClass(); $class->showConstant(); echo $class::constant."\n"; // As of PHP 5.3.0 ?>

Example #1 Autoload example This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
<?php function __autoload($class_name) { require_once $class_name . '.php'; } $obj = new MyClass1(); $obj2 = new MyClass2(); ?>

Example #2 Static data example


<?php class foo { // As of PHP 5.3.0 const bar = <<<'EOT' bar EOT; } ?>

Unlike heredocs, nowdocs can be used in any static data context.

Example #2 Autoload other example This example attempts to load the interface ITest.
<?php function __autoload($name) { var_dump($name); } class Foo implements ITest {

Autoloading Classes
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

} /* string(5) "ITest" Fatal error: Interface 'ITest' not found in ... */ ?>

$obj = new SubClass(); ?>

unserialize() Creates a PHP value from a stored representation spl_autoload() Default implementation for __autoload() spl_autoload_register() Register given function as __autoload() implementation

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics. Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.

Constructors and Destructors Constructor


void __construct ([ mixed $args [, $... ]] ) PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. Example #1 using new unified constructors
<?php class BaseClass { function __construct() { print "In BaseClass constructor\n"; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); print "In SubClass constructor\n"; } } $obj = new BaseClass();

Destructor
void __destruct ( 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 or when the object is explicitly destroyed or in any order in shutdown sequence. Example #2 Destructor Example <?php class MyDestructableClass { function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "\n"; } } $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 call parent::__destruct() in the destructor body.

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing. 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.

Visibility
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member. Property Visibility Class properties must be defined as public, private, or protected. If declared using var without an explicit visibility keyword, the property will be defined as public. Example #1 Property declaration <?php // Define MyClass 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(); 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 ?> Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning. Method Visibility Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. Example #2 Method Declaration

<?php /** * Define MyClass */ class MyClass { // Declare a public constructor public function __construct() { } // Declare a public method public function MyPublic() { } // Declare a protected method protected function MyProtected() { } // Declare a private method private function MyPrivate() { } // This is public function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } $myclass = new MyClass; $myclass->MyPublic(); // Works $myclass->MyProtected(); // Fatal Error $myclass->MyPrivate(); // Fatal Error $myclass->Foo(); // Public, Protected and Private work // Define MyClass2 class MyClass2 extends MyClass { // This is public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // Fatal Error } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // Works

$myclass2->Foo2(); // Public and Protected work, not Private class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublic\n"; } private function testPrivate() { echo "Bar::testPrivate\n"; } } class Foo extends Bar { public function testPublic() { echo "Foo::testPublic\n"; } private function testPrivate() { echo "Foo::testPrivate\n"; } } $myFoo = new foo(); $myFoo->test(); // Bar::testPrivate // Foo::testPublic ?>

Visibility from other objects


Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects. Example #3 Accessing private members of the same object type <?php class Test {

private $foo; public function __construct($foo) { $this->foo = $foo; } private function bar() { echo 'Accessed the private method.'; } public function baz(Test $other) { // We can change the private property: $other->foo = 'hello'; var_dump($other->foo); // We can also call the private method: $other->bar(); } } $test = new Test('test'); $test->baz(new Test('other')); ?> The above example will output:
string(5) "hello" Accessed the private method.

This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality. Example #1 Inheritance Example
<?php class foo { public function printItem($string) { echo 'Foo: ' . $string . PHP_EOL; } public function printPHP() { echo 'PHP is great.' . PHP_EOL; } } class bar extends foo { public function printItem($string) { echo 'Bar: ' . $string . PHP_EOL; } } $foo = new foo(); $bar = new bar(); $foo->printItem('baz'); // Output: 'Foo: baz' $foo->printPHP(); // Output: 'PHP is great' $bar->printItem('baz'); // Output: 'Bar: baz' $bar->printPHP(); // Output: 'PHP is great' ?>

Object Inheritance
Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another. For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

Scope Resolution Operator (::)


The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class. When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static). Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew! Example #1 :: from outside the class definition
<?php class MyClass { const CONST_VALUE = 'A constant value'; } $classname = 'MyClass'; echo $classname::CONST_VALUE; // As of PHP 5.3.0 echo MyClass::CONST_VALUE; ?>

Example #3 Calling a parent's method


<?php class MyClass { protected function myFunc() { echo "MyClass::myFunc()\n"; } } class OtherClass extends MyClass { // Override parent's definition public function myFunc() { // But still call the parent function parent::myFunc(); echo "OtherClass::myFunc()\n"; } } $class = new OtherClass(); $class->myFunc(); ?>

Two special keywords self and parent are used to access properties or methods from inside the class definition. Example #2 :: from inside the class definition
<?php class OtherClass extends MyClass { public static $my_static = 'static var'; public static function doubleColon() { echo parent::CONST_VALUE . "\n"; echo self::$my_static . "\n"; }

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

} $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.

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 can not be a keyword (e.g. self, parent and static). Example #1 Static property example <?php class Foo { public static $my_static = 'foo'; public function staticValue() { return self::$my_static; } } class Bar extends Foo { public function fooStatic() { return parent::$my_static; } } print Foo::$my_static . "\n"; $foo = new Foo(); print $foo->staticValue() . "\n"; print $foo->my_static . "\n"; // Undefined "Property" my_static print $foo::$my_static . "\n"; $classname = 'Foo'; print $classname::$my_static . "\n"; // As of PHP 5.3.0 print Bar::$my_static . "\n"; $bar = new Bar(); print $bar->fooStatic() . "\n"; ?> Example #2 Static method example
<?php class Foo { public static function aStaticMethod() { // ... }

} Foo::aStaticMethod(); $classname = 'Foo'; $classname::aStaticMethod(); // As of PHP 5.3.0 ?>

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. 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 #1 Abstract class 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"; } } class ConcreteClass2 extends AbstractClass

} $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue('FOO_') ."\n"; $class2 = new ConcreteClass2; $class2->printOut(); echo $class2->prefixValue('FOO_') ."\n"; ?>

public function getValue() { return "ConcreteClass2"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass2"; }

implements
To implement an interface, the implements operator is used. All methods in the interface must 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. Note: Interfaces can be extended like classes using the extends operator. Note: The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

The above example will output:


ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2

Constants
Its possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits it.

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.

Examples
Example #1 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) {

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.

$this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } 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; } } ?> Example #2 Extendable Interfaces
<?php interface a { public function foo(); } interface b extends a { public function baz(Baz $baz); } // This will work class c implements b { public function foo() { } public function baz(Baz $baz) {

} } // This will not work and result in a fatal error class d implements b { public function foo() { } public function baz(Foo $foo) { } } ?>

Example #3 Multiple interface inheritance


<?php interface a { public function foo(); } interface b { public function bar(); } interface c extends a, b { public function baz(); } class d implements c { public function foo() { } public function bar() { } public function baz() { } } ?>

Example #4 Interfaces with constants

<?php interface a { const b = 'Interface constant'; } // Prints: Interface constant echo a::b; // This will however not work because its not allowe // to override constants. class b implements a { const b = 'Class constant'; } ?>

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. Changelog Version Description Added __callStatic(). Added warning to enforce public 5.3.0 visibility and non-static declaration. 5.1.0 Added __isset() and __unset(). Property overloading void __set ( string $name , mixed $value ) mixed __get ( string $name ) bool __isset ( string $name ) 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 should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is 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;

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. instanceof operator is used to determine whether a PHP variable is an instantiated object of a certain class. Type Hinting: Functions are now able to force parameters to be objects or arrays.

Overloading
Overloading in PHP provides means to dynamically "create" properties 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 properties 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 properties" 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.

Example #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods <?php class PropertyTest { /** Location for overloaded data. */ private $data = array(); /** Overloading not used on declared properties. */ public $declared = 1; /** 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"; $obj = new PropertyTest; $obj->a = 1; echo $obj->a . "\n\n"; 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"; ?>

The above example will output:


Setting 'a' to '1' Getting 'a' 1 Is 'a' set? bool(true) Unsetting 'a' Is 'a' set? bool(false) 1 Let's experiment with the private property named 'hidden': Privates are visible inside the class, so __get() not used... 2 Privates not visible outside of class, so __get() is used... Getting 'hidden'

Notice: Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

Calling static method 'runTest' in static context

Method overloading mixed __call ( string $name , array $arguments ) 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. Example #2 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 */ public static function __callStatic($name, $arguments) // Note: value of $name is case sensitive. echo "Calling static method '$name' " . implode(', ', $arguments). "\n";

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 #1 Simple Object Iteration
<?php class MyClass { public $var1 = 'value 1'; public $var2 = 'value 2'; public $var3 = 'value 3'; protected $protected = 'protected var'; private $private = 'private var'; function iterateVisible() { echo "MyClass::iterateVisible:\n"; foreach($this as $key => $value) { print "$key => $value\n"; } } } $class = new MyClass(); foreach($class as $key => $value) { print "$key => $value\n"; } echo "\n"; $class->iterateVisible(); ?>

The above example will output:


var1 => value 1 var2 => value 2 var3 => value 3

} $obj = new MethodTest; $obj->runTest('in object context'); MethodTest::runTest('in static context'); 3.0 ?> // As of PHP 5.

The above example will output:


Calling object method 'runTest' in object context

MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected var private => private var

As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated. Example #2 Object Iteration implementing Iterator
<?php class MyIterator implements Iterator { private $var = array(); public function __construct($array) { if (is_array($array)) { $this->var = $array; } } public function rewind() { echo "rewinding\n"; reset($this->var); } public function current() { $var = current($this->var); echo "current: $var\n"; return $var; } public function key() { $var = key($this->var); echo "key: $var\n"; return $var; } public function next() { $var = next($this->var); echo "next: $var\n"; return $var; } public function valid() { $var = $this->current() !== false; echo "valid: {$var}\n"; return $var; } } $values = array(1,2,3); $it = new MyIterator($values);

foreach ($it as $a => $b) { print "$a: $b\n"; } ?>

The above example will output:


rewinding current: 1 valid: 1 current: 1 key: 0 0: 1 next: 2 current: 2 valid: 1 current: 2 key: 1 1: 2 next: 3 current: 3 valid: 1 current: 3 key: 2 2: 3 next: current: valid:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface. Example #3 Object Iteration implementing IteratorAggregate <?php class MyCollection implements IteratorAggregate { private $items = array(); private $count = 0; // Required definition of interface IteratorAggregate public function getIterator() { return new MyIterator($this->items); }

public function add($value) { $this->items[$this->count++] = $value; } } $coll = new MyCollection(); $coll->add('value 1'); $coll->add('value 2'); $coll->add('value 3'); foreach ($coll as $key => $val) { echo "key/value: [$key -> $val]\n\n"; } ?> The above example will output:
rewinding current: value 1 valid: 1 current: value 1 key: 0 key/value: [0 -> value 1] next: value 2 current: value 2 valid: 1 current: value 2 key: 1 key/value: [1 -> value 2] next: value 3 current: value 3 valid: 1 current: value 3 key: 2 key/value: [2 -> value 3] next: current: valid:

__clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. Caution PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality. __sleep and __wakeup serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued. Note: It is not possible for __sleep to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface. The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely. Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have. The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks. Example #1 Sleep and wakeup <?php class Connection { protected $link; private $server, $username, $password, $db; public function __construct($server, $username, $password, $db)

Magic Methods
The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and

{ $this->server = $server; $this->username = $username; $this->password = $password; $this->db = $db; $this->connect(); } private function connect() { $this->link = mysql_connect($this->server, $this->username, $this>password); mysql_select_db($this->db, $this->link); } public function __sleep() { return array('server', 'username', 'password', 'db'); } public function __wakeup() { $this->connect(); } } ?> __toString The __toString method allows a class to decide how it will react when it is converted to a string. Example #2 Simple example
<?php // Declare a simple class class TestClass { public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo;

} } $class = new TestClass('Hello'); echo $class; ?>

The above example will output:


Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print(). Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString method to string would cause E_RECOVERABLE_ERROR. __invoke The __invoke method is called when a script tries to call an object as a function. Note: This feature is available since PHP 5.3.0. Example #3 Using __invoke
<?php class CallableClass { function __invoke($x) { var_dump($x); } } $obj = new CallableClass; $obj(5); var_dump(is_callable($obj)); ?>

The above example will output:


int(5) bool(true)

__set_state This static method is called for classes exported by var_export() since PHP 5.1.0. The only parameter of this method is an array containing exported properties in the form array('property' => value, ...). Example #4 Using __set_state (since PHP 5.1.0) <?php class A { public $var1; public $var2; public static function __set_state($an_array) // As of PHP 5.1.0 { $obj = new A; $obj->var1 = $an_array['var1']; $obj->var2 = $an_array['var2']; return $obj; } } $a = new A; $a->var1 = 5; $a->var2 = 'foo'; eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array( // 'var1' => 5, // 'var2' => 'foo', // )); var_dump($b); ?> The above example will output:
object(A)#2 (2) { ["var1"]=> int(5) ["var2"]=> string(3) "foo" }

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 #1 Final methods example <?php class BaseClass { public function test() { echo "BaseClass::test() called\n"; } final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } } class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called\n"; } } // Results in Fatal error: Cannot override final method BaseClass::more // Testing() ?> Example #2 Final class example <?php final class BaseClass { public function test() { echo "BaseClass::test() called\n"; } // Here it doesn't matter if you specify the function as final or not final public function moreTesting() { echo "BaseClass::moreTesting() called\n"; } } class ChildClass extends BaseClass { } // Results in Fatal error: Class ChildClass may not inherit from final class// (Ba

seClass) ?> Note: Properties cannot be declared final, only classes and methods may be declared as final.

} public function __clone() { $this->instance = ++self::$instances; }

Object Cloning
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy. An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
$copy_of_object = clone $object;

} class MyCloneable { public $object1; public $object2;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed. Example #1 Cloning an object
<?php class SubObject { static $instances = 0; public $instance; public function __construct() { $this->instance = ++self::$instances;

} $obj = new MyCloneable(); $obj->object1 = new SubObject(); $obj->object2 = new SubObject(); $obj2 = clone $obj; print("Original Object:\n"); print_r($obj); print("Cloned Object:\n"); print_r($obj2); ?>

function __clone() { // Force a copy of this->object, otherwise // it will point to same object. $this->object1 = clone $this->object1; }

The above example will output:


Original Object: MyCloneable Object ( [object1] => SubObject Object ( [instance] => 1 ) [object2] => SubObject Object ( [instance] => 2 ) ) Cloned Object:

MyCloneable Object ( [object1] => SubObject Object ( [instance] => 3 ) [object2] => SubObject Object ( [instance] => 2 ) )

echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n"; echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n"; echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n"; echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n"; } class Flag { public $flag; function Flag($flag = true) { $this->flag = $flag; } } class OtherFlag { public $flag; function OtherFlag($flag = true) { $this->flag = $flag; } } $o = new Flag(); $p = new Flag(); $q = $o; $r = new OtherFlag(); echo "Two instances of the same class\n"; compareObjects($o, $p); echo "\nTwo references to the same instance\n"; compareObjects($o, $q); echo "\nInstances of two different classes\n"; compareObjects($o, $r); ?> The above example will output:
Two instances of the same class o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : FALSE o1 !== o2 : TRUE

Comparing Objects
In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language). When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. On the other hand, when using the identity operator ( ===), object variables are identical if and only if they refer to the same instance of the same class. An example will clarify these rules. Example #1 Example of object comparison in PHP 5 <?php function bool2str($bool) { if ($bool === false) { return 'FALSE'; } else { return 'TRUE'; } } function compareObjects(&$o1, &$o2) {

Two references to the same instance o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Instances of two different classes o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE

$d->foo = 2; echo $c->foo."\n"; $e = new A; function foo($obj) { // ($obj) = ($e) = <id> $obj->foo = 2; } foo($e); echo $e->foo."\n"; ?>

Note: Extensions can define own rules for their objects comparison.

Objects and references


One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples. A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. Example #1 References and Objects <?php class A { public $foo = 1; } $a = new A; $b = $a; // $a and $b are copies of the same identifier // ($a) = ($b) = <id> $b->foo = 2; echo $a->foo."\n"; $c = new A; $d = &$c; // $c and $d are references // ($c,$d) = <id>

The above example will output:


2 2 2

Dealing with Forms:


One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts.

HTML Forms (GET and POST)


When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example: Example #1 A simple HTML form <form action="foo.php" method="post"> Name: <input type="text" name="username" /><br /> Email: <input type="text" name="email" /><br /> <input type="submit" name="submit" value="Submit me!" /> </form> Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

Example #2 Accessing data from a simple POST HTML form <?php // Available since PHP 4.1.0 echo $_POST['username']; echo $_REQUEST['username']; import_request_variables('p', 'p_'); echo $p_username; // As of PHP 5.0.0, these long predefined variables can be // disabled with the register_long_arrays directive. echo $HTTP_POST_VARS['username']; // Available if the PHP directive register_globals = on. As of // PHP 4.2.0 the default value of register_globals = off. // Using/relying on this method is not preferred. echo $username; ?> Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php? id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables(). Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0 Note: Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"]. As shown, before PHP 4.2.0 the default value for register_globals was on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly. Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase. PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this

feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data: Example #3 More complex form variables <?php if ($_POST) { echo '<pre>'; echo htmlspecialchars(print_r($_POST, true)); echo '</pre>'; } ?> <form action="" method="post"> Name: <input type="text" name="personal[name]" /><br /> Email: <input type="text" name="personal[email]" /><br /> Beer: <br /> <select multiple name="beer[]"> <option value="warthog">Warthog</option> <option value="guinness">Guinness</option> <option value="stuttgarter">Stuttgarter Schwabenbru</option> </select><br /> <input type="submit" value="submit me!" /> </form> IMAGE SUBMIT variable names When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type="image" src="image.gif" name="sub" />

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically. Here is an example HTML form: Example #4 A simple HTML form

<form action="action.php" method="post"> <p>Your name: <input type="text" name="name" /></p> <p>Your age: <input type="text" name="age" /></p> <p><input type="submit" /></p> </form>

The first key difference in XForms is how the form is sent to the client. XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example. Example #9 A simple XForms search form
<h:html xmlns:h="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/2002/xforms"> <h:head> <h:title>Search</h:title> <model> <submission action="http://example.com/search" method="post" id="s"/> </model> </h:head> <h:body> <h:p> <input ref="q"><label>Find</label></input> <submit submission="s"><label>Go</label></submit> </h:p> </h:body> </h:html>

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this: Example #5 Printing data from our form
Hi <?php echo htmlspecialchars($_POST['name']); ?>. You are <?php echo (int)$_POST['age']; ?> years old.

A sample output of this script may be:


Hi Joe. You are 22 years old.

Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.

The above form displays a text input box (named q), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action. Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-wwwform-urlencoded, in the XForms world however, this information is sent as XML formatted data. If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser. If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it

Dealing with XForms:


XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.

as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.

authentication methods are supported. See the header() function for more information. Note: Superglobals, such as $_SERVER, became available in PHP 4.1.0.

Example #10 Using an XForm to populate $_POST


<h:html xmlns:h="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/2002/xforms"> <h:head> <h:title>Search</h:title> <model> <submission action="http://example.com/search" method="urlencoded-post" id="s"/> </model> </h:head> <h:body> <h:p> <input ref="q"><label>Find</label></input> <submit submission="s"><label>Go</label></submit> </h:p> </h:body> </h:html>

An example script fragment which would force client authentication on a page is as follows: Example #6 Basic HTTP Authentication example <?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password. </p>"; } ?> Example #7 Digest HTTP Authentication example This example shows you how to implement a simple Digest HTTP authentication script. For more information read the RFC 2617.

Note: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.

HTTP authentication with PHP:


The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0)

<?php $realm = 'Restricted area'; //user => password $users = array('admin' => 'mypass', 'guest' => 'guest'); if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$realm. '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"'); die('Text to send if user hits Cancel button'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']]))

die('Wrong Credentials!'); // generate the valid response $A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]); $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']); $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'. $data['qop'].':'.$A2); if ($data['response'] != $valid_response) die('Wrong Credentials!'); // ok, valid username & password echo 'Your are logged in as: ' . $data['username']; // function to parse the http auth header function http_digest_parse($txt) { // protect against missing data $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'usernam e'=>1, 'uri'=>1, 'response'=>1); $data = array(); $keys = implode('|', array_keys($needed_parts)); preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matc hes, PREG_SET_ORDER); foreach ($matches as $m) { $data[$m[1]] = $m[3] ? $m[3] : $m[4]; unset($needed_parts[$m[1]]); } return $needed_parts ? false : $data; } ?> Note: Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be commaseparated as seen in the digest example above. Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now. As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externallyauthenticated user. So, you can use $_SERVER['REMOTE_USER']. Note: PHP uses the presence of an AuthType directive to determine whether external authentication is in effect. Note, however, that the above does not prevent someone who controls a nonauthenticated URL from stealing passwords from authenticated URLs on the same server. Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button. Example #8 HTTP Authentication example forcing a new name/password <?php function authenticate() { header('WWW-Authenticate: Basic realm="Test Authentication System"'); header('HTTP/1.0 401 Unauthorized'); echo "You must enter a valid login ID and password to access this resource\ n"; exit; } if (!isset($_SERVER['PHP_AUTH_USER']) || ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP _AUTH_USER'])) { authenticate(); } else { echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER'

]) . "<br />"; echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']); echo "<form action='' method='post'>\n"; echo "<input type='hidden' name='SeenBefore' value='1' />\n"; echo "<input type='hidden' name='OldAuth' value=\"" . htmlspecialchars($_ SERVER['PHP_AUTH_USER']) . "\" />\n"; echo "<input type='submit' value='Re Authenticate' />\n"; echo "</form></p>\n"; } ?> This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however. Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked. Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); Note: IIS Note: For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).

output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers. Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name. Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security. $HTTP_COOKIE_VARS is also set in earlier versions of PHP when the track_vars configuration variable is set. (This setting is always on since PHP 4.0.3.)

setcookie
setcookie Send a cookie
Description bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST. Parameters All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead.

Cookies
PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any

See Netscape cookie specification for specifics on how each setcookie() parameter works name The name of the cookie. value The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename'] expire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). Note: You may notice the expire parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally. expire is compared to the client's time which can differ from server's time. path The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in. domain The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. secure

The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details.

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]). httponly When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers). Added in PHP 5.2.0. TRUE or FALSE Return Values If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie. Examples Some examples follow how to send cookies: Example #1 setcookie() send example
<?php $value = 'something from somewhere'; setcookie("TestCookie", $value); setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */ setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); ?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded

and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples:
<?php // Print an individual cookie echo $_COOKIE["TestCookie"]; echo $HTTP_COOKIE_VARS["TestCookie"]; // Another way to debug/test is to view all cookies print_r($_COOKIE); ?>

} ?>

The above example will output:


three : cookiethree two : cookietwo one : cookieone

Changelog Version Description 5.2.0 The httponly parameter was added. Note: You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files. Note: If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TestCookie will exist. It's recommended to use $_COOKIE. Common Pitfalls:

Example #2 setcookie() delete example When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:
<?php // set the expiration date to one hour ago setcookie ("TestCookie", "", time() - 3600); setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", " .example.com", 1); ?>

Example #3 setcookie() and arrays You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:
<?php // set the cookies setcookie("cookie[three]", "cookiethree"); setcookie("cookie[two]", "cookietwo"); setcookie("cookie[one]", "cookieone"); // after the page reloads, print them out if (isset($_COOKIE['cookie'])) { foreach ($_COOKIE['cookie'] as $name => $value) { echo "$name : $value <br />\n"; }

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);. Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past. Because setting a cookie with a value of FALSE will try to delete the cookie, you should not use boolean values. Instead, use 0 for FALSE and 1 for TRUE.

Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.

POST method uploads Error Messages Explained Common Pitfalls Uploading multiple files PUT method support

Multiple calls to setcookie() are performed in the order called.

POST method uploads


This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded. PHP is capable of receiving file uploads from any RFC-1867 compliant browser. PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details. Example #1 File Upload Form A file upload screen can be built by creating a special form which looks something like this:
<!-- The data encoding type, enctype, MUST be specified as below --> <form enctype="multipart/form-data" action="__URL__" method="POST"> <!-- MAX_FILE_SIZE must precede the file input field --> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> <!-- Name of input element determines name in $_FILES array --> Send this file: <input name="userfile" type="file" /> <input type="submit" value="Send File" /> </form>

setrawcookie
setrawcookie Send a cookie without urlencoding the cookie value Description bool setrawcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser. Parameters For parameter information, see the setcookie() documentation. Return Values Returns TRUE on success or FALSE on failure. Changelog Version Description 5.2.0 The httponly parameter was added.

Sessions
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

The __URL__ in the above example should be replaced, and point to a PHP file. The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed.

Handling file uploads

Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled. Note: Be sure your file upload form has attribute enctype="multipart/formdata" otherwise the file upload will not work. The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information. The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name. $_FILES['userfile']['name'] The original name of the file on the client machine. $_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted. $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload. This element was added in PHP 4.2.0

Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well. Example #2 Validating file uploads See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form. <?php // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be // used instead of $_FILES. $uploaddir = '/var/www/uploads/'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); echo '<pre>'; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } echo 'Here is some more debugging info:'; print_r($_FILES); print "</pre>"; ?> The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none. The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed. Example #3 Uploading array of files PHP supports HTML array feature even with files. <form action="" method="post" enctype="multipart/form-data"> <p>Pictures: <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="submit" value="Send" /> </p> </form> <?php foreach ($_FILES["pictures"]["error"] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = $_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name, "data/$name"); } } ?> File upload progress bar can be implemented by apc.rfc1867.

UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini. UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded. UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded. UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0. UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0. Note: These became PHP constants in PHP 4.3.0.

Error Messages Explained


Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error']. UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.

Common Pitfalls
The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the php.ini file. The default is 2 megabytes.

If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough. If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough. Note: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running. Warning max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded. If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough. Not validating which file you operate on may mean that users can access sensitive information in other directories. Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature. Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly. A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).

use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes: Example #1 Uploading multiple files <form action="file-upload.php" method="post" enctype="multipart/form-data"> Send these files:<br /> <input name="userfile[]" type="file" /><br /> <input name="userfile[]" type="file" /><br /> <input type="submit" value="Send files" /> </form> When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files. For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth. $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.

PUT method support


PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this: PUT /path/filename.html HTTP/1.1 This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite

Uploading multiple files


Multiple files can be uploaded using different name for input. It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to

any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <VirtualHost> block. A line like this would do the trick: Script PUT /put.php This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have. With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include(), include_once(), require() and require_once() statements (since PHP 5.2.0, allow_url_include must be enabled for these). See List of Supported Protocols/Wrappers for more information about the protocols supported by PHP. Note: In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option --enable-url-fopenwrapper. Note: The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include(), include_once(), require(), require_once(), and the imagecreatefromXXX functions in the GD and Image Functions extension. For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Example #1 Saving HTTP PUT files


<?php /* PUT data comes in on the stdin stream */ $putdata = fopen("php://input", "r"); /* Open a file for writing */ $fp = fopen("myputfile.ext", "w"); /* Read the data 1 KB at a time and write to the file */ while ($data = fread($putdata, 1024)) fwrite($fp, $data); /* Close the streams */ fclose($fp); fclose($putdata); ?>

Example #2 Getting the title of a remote page


<?php $file = fopen ("http://www.example.com/", "r"); if (!$file) { echo "<p>Unable to open remote file.\n"; exit; } while (!feof ($file)) { $line = fgets ($file, 1024); /* This only works if the title and its tags are on one line */ if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) { $title = $out[1]; break; } } fclose($file); ?>

Using remote files

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail. To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.) Example #3 Storing data on a remote server
<?php $file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w"); if (!$file) { echo "<p>Unable to open remote file for writing.\n"; exit; } /* Write the data here. */ fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n"); fclose ($file); ?> Note: You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().

You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache httpd.conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted. Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache httpd.conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called. One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.

Connection handling:
Internally in PHP a connection status is maintained. There are 3 possible states: 0 - NORMAL 1 - ABORTED 2 - TIMEOUT

Persistent Database Connections:


Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers. Why? This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages. The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist. The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server. The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. If persistent connections don't have any added functionality, what are they good for? The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause

the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child. Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections. Warning There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere). An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior! See also fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), oci_pconnect(), pfsockopen(), pg_pconnect(), and sybase_pconnect().

MySQL

These functions allow you to access MySQL database servers. More information about MySQL can be found at http://www.mysql.com/.

Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime. Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect() and mysql_pconnect() functions. The following constants are defined: MySQL client constants Constant MYSQL_CLIENT_COMPRESS Description Use compression protocol

MYSQL_CLIENT_IGNORE_SPACE Allow space after function names MYSQL_CLIENT_INTERACTIVE Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection. Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5.

MYSQL_CLIENT_SSL

<?php // Connecting, selecting database $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error()); echo 'Connected successfully'; mysql_select_db('my_database') or die('Could not select database'); // Performing SQL query $query = 'SELECT * FROM my_table'; $result = mysql_query($query) or die('Query failed:'. mysql_error()); // Printing results in HTML echo "<table>\n"; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "\t<tr>\n"; foreach ($line as $col_value) { echo "\t\t<td>$col_value</td>\n"; } echo "\t</tr>\n"; } echo "</table>\n"; // Free resultset mysql_free_result($result); // Closing connection mysql_close($link); ?>

The function mysql_fetch_array() uses a constant for the different types of result arrays. The following constants are defined: MySQL fetch constants Constant Description Columns are returned into the array having the fieldname as the MYSQL_ASSOC array index. Columns are returned into the array having both a numerical index MYSQL_BOTH and the fieldname as the array index. Columns are returned into the array having a numerical index to the MYSQL_NUM fields. This index starts with 0, the first field in the result. This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database. Example #1 MySQL extension overview example

mysql_connect
mysql_connect Open a connection to a MySQL Server

Description
resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] ) Opens or reuses a connection to a MySQL server.

Return Values
Returns a MySQL link identifier on success or FALSE on failure.

mysql_create_db
mysql_create_db Create a MySQL database

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

Description
bool mysql_create_db ( string $database_name [, resource $link_identifier ] ) mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.

Return Values
Returns TRUE on success or FALSE on failure.

Return Values
Returns TRUE on success or FALSE on failure. mysql_create_db() alternative example The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue an sql CREATE DATABASE statement instead.
<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } $sql = 'CREATE DATABASE my_db'; if (mysql_query($sql, $link)) { echo "Database my_db created successfully\n"; } else { echo 'Error creating database: ' . mysql_error() . "\n"; } ?>

mysql_error
mysql_error Returns the text of the error message from previous MySQL operation

Description
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.

Return Values
Returns the error text from the last MySQL function, or '' (empty string) if no error occurred. mysql_error() example
<?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("nonexistentdb", $link); echo mysql_errno($link) . ": " . mysql_error($link). "\n"; mysql_select_db("kossu", $link); mysql_query("SELECT * FROM nonexistenttable", $link); echo mysql_errno($link) . ": " . mysql_error($link) . "\n"; ?>

The above example will output something similar to:


Database my_db created successfully.

mysql_close
mysql_close Close MySQL connection

Description
bool mysql_close ([ resource $link_identifier ] )

The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist

Return Values
Returns TRUE on success or FALSE on failure. mysql_select_db() example
<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Not connected : ' . mysql_error()); } // make foo the current db $db_selected = mysql_select_db('foo', $link); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); } ?>

mysql_fetch_row
mysql_fetch_row Get a result row as an enumerated array Description
array mysql_fetch_row ( resource $result ) Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

Return Values
Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows. Fetching one row with mysql_fetch_row()
<?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_row($result); echo $row[0]; // 42 echo $row[1]; // the email value ?>

mysql_num_rows
mysql_num_rows Get number of rows in result

Description
int mysql_num_rows ( resource $result ) Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Return Values
The number of rows in a result set on success or FALSE on failure.

mysql_select_db
mysql_select_db Select a MySQL database

MySQL Functions
Note: Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE. mysql_affected_rows Get number of affected rows in previous MySQL operation

Description
bool mysql_select_db ( string $database_name [, resource $link_identifier ] ) Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

mysql_client_encoding Returns the name of the character set mysql_close Close MySQL connection mysql_connect Open a connection to a MySQL Server mysql_create_db Create a MySQL database mysql_data_seek Move internal result pointer mysql_db_name Get result data mysql_db_query Send a MySQL query mysql_drop_db Drop (delete) a MySQL database mysql_errno Returns the numerical value of the error message from previous MySQL operation mysql_error Returns the text of the error message from previous MySQL operation mysql_escape_string Escapes a string for use in a mysql_query mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both mysql_fetch_assoc Fetch a result row as an associative array mysql_fetch_field Get column information from a result and return as an object mysql_fetch_lengths Get the length of each output in a result mysql_fetch_object Fetch a result row as an object mysql_fetch_row Get a result row as an enumerated array mysql_field_flags Get the flags associated with the specified field in a result mysql_field_len Returns the length of the specified field mysql_field_name Get the name of the specified field in a result mysql_field_seek Set result pointer to a specified field offset mysql_field_table Get name of the table the specified field is in mysql_field_type Get the type of the specified field in a result mysql_free_result Free result memory mysql_get_client_info Get MySQL client info mysql_get_host_info Get MySQL host info mysql_get_proto_info Get MySQL protocol info mysql_get_server_info Get MySQL server info mysql_info Get information about the most recent query mysql_insert_id Get the ID generated in the last query mysql_list_dbs List databases available on a MySQL server mysql_list_fields List MySQL table fields mysql_list_processes List MySQL processes mysql_list_tables List tables in a MySQL database mysql_num_fields Get number of fields in result mysql_num_rows Get number of rows in result

mysql_pconnect Open a persistent connection to a MySQL server mysql_ping Ping a server connection or reconnect if there is no connection mysql_query Send a MySQL query mysql_real_escape_string Escapes special characters in a string for use in an SQL statement mysql_result Get result data mysql_select_db Select a MySQL database mysql_set_charset Sets the client character set mysql_stat Get current system status mysql_tablename Get table name of field mysql_thread_id Return the current thread ID mysql_unbuffered_query Send an SQL query to MySQL without fetching and buffering the result rows.

Vous aimerez peut-être aussi