You are on page 1of 114

1.

INTRODUCTION TO PHP

1.1 History of PHP, Apache Web Server, MySQL and Open Source PHP: PHP is a powerful tool for making dynamic and interactive Web pages.Hypertext Preprocessor is a scripting language that is embedded in HTML. PHP scripting code is frequently used to connect web pages to MySQL databases to create dynamic web sites. Some popular examples of PHP driven web sites would be blogs, message boards, and Wikis. PHP files are actually plain text files; they can be created in TextPad or any other Plain Text Editor. In a text editor set the Save As type to text and save the file with a .php extension. Note: You must type the .php yourself. PHP files can also be created with Dreamweaver MX 2004. PHP is "open source" and therefore free. We use the Apache Server to work with PHP files in the classroom. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP

PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software PHP is free to download and use

What is a PHP File?


PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"

SARASWATI ZEROX & PRINT

PH-02765-222990

Why PHP?

PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side

Apache: is a popular web server that many ISP's and individuals use to host web pages. When you install Apache on your system your machine becomes a web server. Pages stored on your system in a "special folder" are accessible on the Internet via the machine's IP address. In order for pages to be viewed on the Internet, the files must be stored in a special directory; this directory is usually called htdocs, public_html, or www. If you use a web host, you probably upload your files to a directory with one of these names. If someone else wants to access your web pages, they must know the IP Address of your MySQL: is a relational database system. MySQL uses "Structured Query Language" which is the most common database language. It is the most popular "open source" database in the World. MySQL content can be managed via a command line or a web interface. MySQL is "open source" and therefore free. We use the Apache Server to work with MySQL files in the classroom machine, i.e., 179.199.9.100. Apache is "open source" and therefore free. What is MySQL?

MySQL is a database server


SARASWATI ZEROX & PRINT PH-02765-222990

MySQL is ideal for both small and large applications MySQL supports standard SQL MySQL compiles on a number of platforms MySQL is free to download and use

1.2 Relationship between Apache, MySQL and PHP (AMP Module) 1.3 PHP configuration in IIS Start>controlpanel>administrativetools>Internet Information Service. Expand the + buttons on the left side area if any and Right click the label saying default web site. You will get a list of items in the menu and then go to properties section. In the property section select go to Home Directory tab ( at the top ) and click the button Configuration.

SARASWATI ZEROX & PRINT

PH-02765-222990

Here we are trying to tell IIS to execute php.exe script for all file extensions of PHP. Once we click the configuration button we will get one window with existing file extension and corresponding executable applications.

Here we have to add our required application to the list so we have to click the Add button to add our php extension. After clicking Add button we will get an window to inter the path and extension. We can enter the path details by using the browse button. In the extension field we will enter .php ( dot php ).

SARASWATI ZEROX & PRINT

PH-02765-222990

Click OK and you will see the executable path added to the list for the .php extension.

Now select the script and executables on the execute permissions.Click OK and to close the main property window click OK again.That'sall.This will configure IIS to run PHP with php file extensions. 1.4 Apache Web server

SARASWATI ZEROX & PRINT

PH-02765-222990

2 - BASICS OF PHP
2.1 PHP structure and syntax <?php ?> 2.2 Creating the PHP pages <?php echo "Hello World"; ?> 2.3 Rules of PHP syntax A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with <? and end with ?>. For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form. A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

SARASWATI ZEROX & PRINT

PH-02765-222990

<?php //This a comment; /*This is a; Comment; Block;*/ ?> 2.4 Integrating HTML with PHP Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser: <html> <body> <?php echo "Hello World"; ?> </body> </html> Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World". Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed. 2.5 Constants, Variables : static and global variable Constants A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the
SARASWATI ZEROX & PRINT PH-02765-222990

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. Example 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"); ?> Variables in PHP Variables are used for storing values, like text strings, numbers or arrays. When a variable is declared, it can be used over and over again in your script. All variables in PHP start with a $ sign symbol.The correct way of declaring a variable in PHP: $var_name=value; New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work. Let's try creating a variable containing a string, and a variable containing a number:

SARASWATI ZEROX & PRINT

PH-02765-222990

<?php $txt="Hello World!"; $x=16; ?> Use of Static Variable:: <?php


$a = 1; ?>

<?php function test() { $a = 0; echo $a; $a++; } ?> Use of Global Variable:: <?php $a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); ?> <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum();

SARASWATI ZEROX & PRINT

PH-02765-222990

echo $b; ?> Naming Rules for Variables


A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)

PHP is a Loosely Typed Language In PHP, a variable does not need to be declared before adding a value to it. In the example above, you see that you do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP, the variable is declared automatically when you use it. 2.7 Conditional Structure & Looping Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false
SARASWATI ZEROX & PRINT PH-02765-222990

if...elseif....else statement - use this statement to select one of several blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed

The if Statement Use the if statement to execute some code only if a specified condition is true. Syntax if (condition) code to be executed if condition is true;

The following example will output "Have a nice weekend!" if the current day is Friday: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html> Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition is true. The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if a condition is false. Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false;
SARASWATI ZEROX & PRINT PH-02765-222990

Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html> If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces: <html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html> The if...elseif....else Statement Use the if....elseif...else statement to select one of several blocks of code to be executed.
SARASWATI ZEROX & PRINT PH-02765-222990

Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

SARASWATI ZEROX & PRINT

PH-02765-222990

<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> The PHP Switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
SARASWATI ZEROX & PRINT PH-02765-222990

variable length argument PHP support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions. 1. func_get_arg(position) - It returns the value of the specified argument provided in the function call operation. "position" is the position index of the specified argument. The position index of the first argument is 0. For example, if "func_get_arg(2)" is used in a function, it will return the value of the 3rd argument. 2. func_num_args() - It returns the total number of arguments provided in the function call operation. For example, if "func_num_args()" returns 1, you know that there is only 1 argument provided by calling code. 3. func_get_args() - It creats and returns an array which contains values of all arguments provided in the function call operation. For example, if "$args = func_get_args()" is used in a function, $args will be array containing all arguments. With all these 3 functions, we say that PHP supports variablelength argument lists with some basic rules:

The function call can provide more arguments than the number of argument variables defined in the function statement. You can pass arguments to a function that has no argument variable defined.

To help us understand how use variable-length argument list feature, I wrote this tutorial example: <?php function f2c($fahrenheit) { $celsius = (func_get_arg(0) - 32.0) / 1.8; return $celsius; } print("\n Calling a function that uses func_get_arg():\n"); if (f2c(20.0)<0.0) print(" It's cold here!\n");
SARASWATI ZEROX & PRINT PH-02765-222990

function myMax() { $max = NULL; if (func_num_args()>0) $max = func_get_arg(0); for ($i=1; $i<func_num_args(); $i++) { if ($max < func_get_arg($i)) $max = func_get_arg($i); } return $max; } print("\n print(" print(" print(" print(" Calling a function that uses func_num_args():\n"); ".myMax()."\n"); ".myMax(3)."\n"); ".myMax(3, 1, 4)."\n"); ".myMax(3, 1, 4, 1, 5, 9, 2, 6, 5)."\n");

function myMin() { $list = func_get_args(); $min = NULL; if (count($list)>0) $min = $list[0]; for ($i=1; $i<count($list); $i++) { if ($min > $list[$i]) $min = $list[$i]; } return $min; } print("\n print(" print(" print(" print(" ?> Calling a function that uses func_get_args():\n"); ".myMin()."\n"); ".myMin(5)."\n"); ".myMin(5, 6, 2)."\n"); ".myMin(5, 6, 2, 9, 5, 1, 4, 1, 3)."\n");

If you run this sample script, you should get: Calling a function that uses func_get_arg(): It's cold here! Calling a function that uses func_num_args(): 3 4
SARASWATI ZEROX & PRINT PH-02765-222990

9 Calling a function that uses func_get_args(): 5 2 1

3 - WORKING WITH FUNCTIONS

SARASWATI ZEROX & PRINT

PH-02765-222990

3.1 Variable Function : gettype, settype, isset, unset, strval, floatval, intval, print_r

gettype:This function returns the type of variable.


Return Type :- string Description string gettype ($var ) Returns the type of the PHP variable Return Values Possibles values for the returned string are:
var.

"boolean" "integer" "double" (for historical reasons "double" is returned in case of a float, and not simply "float") "string" "array" "object" "resource" "NULL" "unknown type"

Example 6:<?php $x="welcome"; $y=56; $z=56.34; echo gettype($x); echo "<br>"; echo gettype($y);

SARASWATI ZEROX & PRINT

PH-02765-222990

echo "<br>"; echo gettype($z); ?> Output : string integer double

settype ::This function returns convert variable datatype.


Return Type :- bool Description bool settype ($var , string Set the type of variable Parameters var The variable being converted. type Possibles values of
type

$type

var

to

type.

are:

"boolean" (or, since PHP 4.2.0, "bool") "integer" (or, since PHP 4.2.0, "int") "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double") "string" "array" "object" "null" (since PHP 4.2.0)

SARASWATI ZEROX & PRINT

PH-02765-222990

Return Values Returns TRUE on success or FALSE on failure. Example 7:<?php $x="welcome"; $y=56; $z=56.34; settype($x,"integer"); echo gettype($x); echo "<br>"; settype($y,"boolean"); echo gettype($y); echo "<br>"; settype($z,"double"); echo gettype($z); ?> Output : integer boolean double

isset:
This function check whether variable exists or not. Return True if variable exists otherwise return False. Note : - isset function is very usefull for check $_Post['btnsubmit'], $_Get['btnsubmit'] etc variable. Return Type:- bool Description bool isset ($var) Determine if a variable is set and is not NULL. If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has

SARASWATI ZEROX & PRINT

PH-02765-222990

been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant. If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered. Parameters var The variable to be checked. var Another variable .. Return Values Returns TRUE if otherwise.
var

exists and has value other than

NULL, FALSE

Example 2:<?php $var = 30; if (isset($var)) { echo "Varible is exist"; } else { echo "Varible is not exist"; } ?> Output :Varible is exist

unset:
SARASWATI ZEROX & PRINT PH-02765-222990

This function destroy variables. Note :- You can use unset function to destroy session varaibles. Return Type :- void Description void unset ($var) unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called. Parameters var The variable to be unset. var Another variable ..

<?php function foo() { static $bar; $bar++; echo "Before unset: $bar, "; unset($bar); $bar = 23; echo "after unset: $bar\n"; }

SARASWATI ZEROX & PRINT

PH-02765-222990

foo(); foo(); foo(); ?> The above example will output: Before unset: 1, after unset: 23 Before unset: 2, after unset: 23 Before unset: 3, after unset: 23

Example 3:<?php $var = 30; echo $var; unset($var); echo $var; ?> Output :30

strval:
string.

Get string value of a variable or Converts a value to a

Description string strval ($var ) Get the string value of a variable. This function performs no formatting on the returned value. converts any scalar value (string, integer, or double) to a string. Resource pointers passed to this function are converted to a string such as "Resource ID #1". If conversion of an array or object is attempted, the function only returns the type name of the value being converted (array and object, respectively).
SARASWATI ZEROX & PRINT PH-02765-222990

Note Due to PHP's dynamic typing, use of strval() is almost never required. In most contexts where a scalar value should be a string, the value will simply act like a string. For example: $double = 2.2; $string = "I am a string "; // The value of $double is used as a string - no explicit conversion is required print $string . $double; // Displays: I am a string 2.2

Parameters var The variable that is being converted to a string. var may be any scalar type or an object that implements the __toString method. You cannot use strval() on arrays Return Values The string value of
var.

Example : strval() example <?php $value = 1.223; print strval ($value); ?>

floatval:

Get float value of a variable

Description float floatval ($var ) Gets the float value of


var.

SARASWATI ZEROX & PRINT

PH-02765-222990

Parameters var May be any scalar type. floatval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1. Return Values The float value of the given variable. Empty arrays return 0, non-empty arrays return 1. Example: floatval() Example <?php $var = '122.34343The'; $float_value_of_var = floatval($var); echo $float_value_of_var; // 122.34343 ?>

intval:
This function returns the integer value of the variable. Return Type :- int Description int intval ($var) Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1. Parameters var The scalar value being converted to an integer base The base for the conversion

SARASWATI ZEROX & PRINT

PH-02765-222990

Return Values The integer value of var on success, or 0 on failure. Empty arrays and objects return 0, non-empty arrays and objects return 1. The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807. Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply. Example 5:<?php echo intval(45.67); echo "<br>"; echo intval(-67.45); ?> Output : 45 -67

print_r:This function display information about variable.


Return Type :- bool Description mixed print_r ($expression) print_r() displays information about a variable in a way that's readable by humans. Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.

SARASWATI ZEROX & PRINT

PH-02765-222990

Parameters expression The expression to be printed. return If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it. Return Values If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects. When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.

Example 4:<?php $my_array = array(5,6,7,8); print_r($my_array); ?> Output :Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 ) Example: print_r() example <?php $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r ($a); ?> The above example will output:

SARASWATI ZEROX & PRINT

PH-02765-222990

Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) )

3.2 String Function : chr, ord, strtolower, strtoupper, strlen, ltrim, rtrim, trim, substr, strcmp, strcasecmp, strops, strrpos, strstr, stristr, str_replace, strrev, echo, print

chr

Return a specific character )

Description string chr ( int

$ascii

Returns a one-character string containing the character specified by ascii. This function complements ord(). Parameters ascii The ascii code. Return Values Returns the specified character. Example: chr() example <?php $str = "The string ends in escape: ";
SARASWATI ZEROX & PRINT PH-02765-222990

$str = chr(65); /* add an escape character at the end of $str */ echo $str; /* Often this is more useful */ $str = sprintf("The string ends in escape: %c", 27); ?>

ord

Return ASCII value of character )

Description int ord ( string

$string

Returns the ASCII value of the first character of string. This function complements chr(). Parameters string A character. Return Values Returns the ASCII value as an integer. Example: ord() example <?php $str="A"; $a=ord($str); echo $a; ?>

strtolower

Make a string lowercase )

Description string strtolower ( string

$str

SARASWATI ZEROX & PRINT

PH-02765-222990

Returns string with all alphabetic characters converted to lowercase. Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A () will not be converted. Parameters str The input string. Return Values Returns the lowercased string. Example: strtolower() example <?php $str = "Mary Had A Little Lamb and She LOVED It So"; $str = strtolower($str); echo $str; // Prints mary had a little lamb and she loved it so ?>

strtoupper

Make a string uppercase )

Description string strtoupper ( string

$string

Returns string with all alphabetic characters converted to uppercase. Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a () will not be converted. Parameters string The input string.

SARASWATI ZEROX & PRINT

PH-02765-222990

Return Values Returns the uppercased string. Example: strtoupper() example <?php $str = "Mary Had A Little Lamb and She LOVED It So"; $str = strtoupper($str); echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED I T SO ?>

strlen

Get string length )


string

Description int strlen ( string

$string

Returns the length of the given Parameters string

The string being measured for length. Return Values The length of the
string

on success, and 0 if the

string

is empty.

Example: A strlen() example <?php $str = 'abcdef'; echo strlen($str); // 6 $str = ' ab cd '; echo strlen($str); // 7 ?>

ltrim Strip whitespace (or other characters) from the


beginning of a string

SARASWATI ZEROX & PRINT

PH-02765-222990

Description string ltrim ( string

$str

[, string

$charlist

])

Strip whitespace (or other characters) from the beginning of a string. Parameters str The input string. charlist You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. Return Values This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NUL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Example: Usage example of ltrim() <?php $text = "\t\tThese are a few words :) ... "; $binary = "\x09Example string\x0A"; $hello = "Hello World"; var_dump($text, $binary, $hello);

SARASWATI ZEROX & PRINT

PH-02765-222990

print "\n"; $trimmed = ltrim($text); var_dump($trimmed); $trimmed = ltrim($text, " \t."); var_dump($trimmed); $trimmed = ltrim($hello, "Hdle"); var_dump($trimmed); // trim the ASCII control characters at the beginning of $binary // (from 0 to 31 inclusive) $clean = ltrim($binary, "\x00..\x1F"); var_dump($clean); ?> The above example will output: string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(30) "These are a few words :) ... " string(30) "These are a few words :) ... " string(7) "o World" string(15) "Example string"

rtrim
of a string

Strip whitespace (or other characters) from the end

Description string rtrim ( string

$str

[, string

$charlist

])

This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.


SARASWATI ZEROX & PRINT PH-02765-222990

"\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NUL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters str The input string. charlist You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. Return Values Returns the modified string. Example: Usage example of rtrim() <?php $text = "\t\tThese are a few words :) ... "; $binary = "\x09Example string\x0A"; $hello = "Hello World"; var_dump($text, $binary, $hello); print "\n"; $trimmed = rtrim($text); var_dump($trimmed); $trimmed = rtrim($text, " \t."); var_dump($trimmed);

SARASWATI ZEROX & PRINT

PH-02765-222990

$trimmed = rtrim($hello, "Hdle"); var_dump($trimmed); // trim the ASCII control characters at the end of $binary // (from 0 to 31 inclusive) $clean = rtrim($binary, "\x00..\x1F"); var_dump($clean); ?> The above example will output: string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(30) " These are a few words :) ..." string(26) " These are a few words :)" string(9) "Hello Wor" string(15) " Example string"

trim

Strip whitespace (or other characters) from the beginning and end of a string Description string trim ( string [, string ])

$str

$charlist

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NUL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab.

SARASWATI ZEROX & PRINT

PH-02765-222990

Parameters str The string that will be trimmed. charlist Optionally, the stripped characters can also be specified using the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. Return Values The trimmed string. Example: Usage example of trim() <?php $text = "\t\tThese are a few words :) ... "; $binary = "\x09Example string\x0A"; $hello = "Hello World"; var_dump($text, $binary, $hello); print "\n"; $trimmed = trim($text); var_dump($trimmed); $trimmed = trim($text, " \t."); var_dump($trimmed); $trimmed = trim($hello, "Hdle"); var_dump($trimmed); // trim the ASCII control characters at the beginning and end of $binary // (from 0 to 31 inclusive)
SARASWATI ZEROX & PRINT PH-02765-222990

$clean = trim($binary, "\x00..\x1F"); var_dump($clean); ?> The above example will output: string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(28) "These are a few words :) ..." string(24) "These are a few words :)" string(5) "o Wor" string(14) "Example string" Example: Trimming array values with trim() <?php function trim_value(&$value) { $value = trim($value); } $fruit = array('apple','banana ', ' cranberry '); var_dump($fruit); array_walk($fruit, 'trim_value'); var_dump($fruit); ?> The above example will output: array(3) { [0]=> string(5) "apple" [1]=> string(7) "banana " [2]=> string(11) " cranberry " }
SARASWATI ZEROX & PRINT PH-02765-222990

array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(9) "cranberry" }

substr

Return part of a string , int [, int ])


length

Description string substr ( string

$string string

$start

$length start

Returns the portion of parameters. Parameters string

specified by the

and

The input string. Must be one character or longer. start If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. If start is negative, the returned string will start at the start'th character from the end of string. If string is less than or equal to will be returned. length If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If length is given and is negative, then that many characters will be omitted from the end of string (after the
SARASWATI ZEROX & PRINT PH-02765-222990
start

characters long,

FALSE

start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned. If length is given and is 0, FALSE or NULL an empty string will be returned. If length is omitted, the substring starting from start until the end of the string will be returned. Return Values Returns the extracted part of string, or empty string. Example: Using a negative start <?php $rest = substr("abcdef", -1); // returns "f" $rest = substr("abcdef", -2); // returns "ef" $rest = substr("abcdef", -3, 1); // returns "d" ?> Example: Using a negative length <?php $rest = $rest = $rest = $rest = ?> substr("abcdef", substr("abcdef", substr("abcdef", substr("abcdef", 0, -1); // returns "abcde" 2, -1); // returns "cde" 4, -4); // returns false -3, -1); // returns "de"
FALSE

on failure or an

strcmp

Binary safe string comparison , string )

Description int strcmp ( string

$str1

$str2

Note that this comparison is case sensitive.

SARASWATI ZEROX & PRINT

PH-02765-222990

<?php $str1 = 'a'; $str2 = 'b'; var_dump(strcmp($str1, $str2)); //int(-1) ?>

strcasecmp
comparison

Binary safe case-insensitive string

Description int strcasecmp ( string

$str1

, string

$str2

Binary safe case-insensitive string comparison. Return Values Returns < 0 if str1 is less than str2, and 0 if they are equal. Examples Example: strcasecmp() example <?php
$var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo '$var1 is equal to $var2 in a case-insensitive string comparison'; } ?> str2;

> 0 if

str1

is greater than

strpos

Find position of first occurrence of a string , [, int =0])

Description int strpos ( string

$haystack

$needle

$offset

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos() before PHP 5, this function can take a full string as the needle parameter and the entire string will be used. Parameters haystack

SARASWATI ZEROX & PRINT

PH-02765-222990

The string to search in needle If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. offset The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the beginning of haystack. Return Values Returns the position as an integer. If strpos() will return boolean FALSE. Example: Using === <?php $mystring = 'abc'; $findme = 'a'; $pos = strpos($mystring, $findme); // Note our use of ===. Simply == would not work as expecte d // because the position of 'a' was the 0th (first) character. if ($pos === false) { echo "The string '$findme' was not found in the string '$myst ring'"; } else { echo "The string '$findme' was found in the string '$mystring '"; echo " and exists at position $pos"; } ?> Example: Using !== <?php $mystring = 'abc'; $findme = 'a';
needle

is not found,

SARASWATI ZEROX & PRINT

PH-02765-222990

$pos = strpos($mystring, $findme); // The !== operator can also be used. Using != would not work as expected // because the position of 'a' is 0. The statement (0 != false) ev aluates // to false. if ($pos !== false) { echo "The string '$findme' was found in the string '$mystrin g'"; echo " and exists at position $pos"; } else { echo "The string '$findme' was not found in the string '$mys tring'"; } ?> Example: Using an offset <?php // We can search for the character, ignoring anything before the offset $newstring = 'abcdef abcdef'; $pos = strpos($newstring, 'a', 1); // $pos = 7, not 0 ?>

strrpos

Find the position of the last occurrence of a substring in a string Description int strrpos ( string , string [, int =0])
needle

$haystack

$needle

$offset

Returns the numeric position of the last occurrence of the haystack string. Parameters haystack The string to search in.

in

SARASWATI ZEROX & PRINT

PH-02765-222990

needle If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. The needle can only be a single character in PHP 4. offset May be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string. Return Values Returns the position where the needle exists. Returns the needle was not found. Example: Checking if a needle is in the haystack It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference: <?php $pos = strrpos($mystring, "b"); if ($pos === false) { // note: three equal signs // not found... } ?> Example: Searching with offsets <?php $foo = "0123456789a123456789b123456789c"; var_dump(strrpos($foo, '7', -5)); // Starts looking backwards fiv e positions // from the end. Result: int(17) var_dump(strrpos($foo, '7', 20)); // Starts searching 20 position
FALSE

if

SARASWATI ZEROX & PRINT

PH-02765-222990

s into the // string. Result: int(27) var_dump(strrpos($foo, '7', 28)); // Result: bool(false) ?>

strstr

Find first occurrence of a string , [, bool = false

Description string strstr ( string ])

$haystack

$needle

$before_needle

Returns part of haystack string from the first occurrence of to the end of haystack. Note:

needle

This function is case-sensitive. For case-insensitive searches, use stristr(). Parameters haystack The input string. needle If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. before_needle If TRUE, strstr() returns the part of the first occurrence of the needle. Return Values Returns the portion of string, or Example: strstr() example <?php $email = 'name@example.com';
SARASWATI ZEROX & PRINT PH-02765-222990
FALSE haystack

before the

if

needle

is not found.

$domain = strstr($email, '@'); echo $domain; // prints @example.com $user = strstr($email, '@', true); // As of PHP 5.3.0 echo $user; // prints name ?>

stristr

Case-insensitive strstr() , mixed [, bool

Description string stristr ( string = false ] ) Returns all of end. Parameters haystack
haystack

$haystack

$needle

$before_needle

from the first occurrence of

needle

to the

The string to search in needle If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. before_needle If TRUE, stristr() returns the part of the first occurrence of the needle. needle and
haystack haystack

before the

are examined in a case-insensitive manner.

Return Values Returns the matched substring. If FALSE. Example: stristr() example <?php $email = 'USER@EXAMPLE.com'; echo stristr($email, 'e'); // outputs ER@EXAMPLE.com
SARASWATI ZEROX & PRINT PH-02765-222990
needle

is not found, returns

echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US ?> Example: Testing if a string is found or not <?php $string = 'Hello World!'; if(stristr($string, 'earth') === FALSE) { echo '"earth" not found in string'; } // outputs: "earth" not found in string ?> Example: Using a non "string" needle <?php $string = 'APPLE'; echo stristr($string, 97); // 97 = lowercase a // outputs: APPLE ?>

str_replace Replace all occurrences of the search string


with the replacement string Description str_replace (
$search ,$replace

$subject)

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. Parameters If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. If search or to last.
replace

are arrays, their elements are processed first

SARASWATI ZEROX & PRINT

PH-02765-222990

search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles. replace The replacement value that replaces found search values. An array may be used to designate multiple replacements. subject The string or array being searched and replaced on, otherwise known as the haystack. If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well. Return Values This function returns a string or an array with the replaced values. <?php $a="hello"; echo str_replace("he","hi",$a); ?> Example: Basic str_replace() examples <?php // Provides: <body text='black'> $bodytag = str_replace("%body%", "black", "<body text='%bo dy%'>"); // Provides: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP ");
SARASWATI ZEROX & PRINT PH-02765-222990

// Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every d ay."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); // Provides: 2 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count; ?>

strrev

Reverse a string )

Description string strrev ( string Returns


string,

$string

reversed.

Parameters string The string to be reversed. Return Values Returns the reversed string.

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

echo

Output one or more strings


PH-02765-222990

SARASWATI ZEROX & PRINT

Description void echo ( string

$arg1

[, string

$...

])

Outputs all parameters. echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses. echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled. Parameters arg1 The parameter to output. Return Values No value is returned.

print

Output a string )

Description int print ( string Outputs


arg.

$arg

SARASWATI ZEROX & PRINT

PH-02765-222990

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list. Parameters arg The input data. Return Values Returns 1, always.

3.3 Math Function : abs, ceil, floor, round, fmod, min, max, pow, sqrt, rand

abs

Absolute value

Description abs ($number ) Returns the absolute value of Parameters number The numeric value to process Return Values The absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer). Example: abs() example <?php $abs = abs(-4.2); // $abs = 4.2; (double/float) $abs2 = abs(5); // $abs2 = 5; (integer) $abs3 = abs(-5); // $abs3 = 5; (integer) ?>
number.

SARASWATI ZEROX & PRINT

PH-02765-222990

ceil

Round fractions up

Description fceil ( $value ) Returns the next highest integer value by rounding up necessary. Parameters value The value to round Return Values value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer. Example: ceil() example <?php echo ceil(4.3); // 5 echo ceil(9.999); // 10 echo ceil(-3.14); // -3 ?>
value

if

floor

Round fractions down

Description floor ($value ) Returns the next lowest integer value by rounding down necessary. Parameters value The numeric value to round
value

if

SARASWATI ZEROX & PRINT

PH-02765-222990

Return Values value rounded to the next lowest integer. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer. Example: floor() example <?php echo floor(4.3); // 4 echo floor(9.999); // 9 echo floor(-3.14); // -4 ?>

round

Rounds a float =

Description round ( $val [, int $precision = 0 [, int PHP_ROUND_HALF_UP ]] )

$mode

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default). Note: PHP doesn't handle strings like "12,300.2" correctly by default

Parameters val The value to round precision The optional number of decimal digits to round to. mode One of PHP_ROUND_HALF_UP, or PHP_ROUND_HALF_ODD.
PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN,

SARASWATI ZEROX & PRINT

PH-02765-222990

Return Values The rounded value Example: round() examples <?php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?> Example: mode examples <?php echo round(9.5, echo round(9.5, echo round(9.5, echo round(9.5, echo echo echo echo ?> round(8.5, round(8.5, round(8.5, round(8.5, 0, 0, 0, 0, 0, 0, 0, 0, PHP_ROUND_HALF_UP); // 10 PHP_ROUND_HALF_DOWN); // 9 PHP_ROUND_HALF_EVEN); // 10 PHP_ROUND_HALF_ODD); // 9 PHP_ROUND_HALF_UP); // 9 PHP_ROUND_HALF_DOWN); // 8 PHP_ROUND_HALF_EVEN); // 8 PHP_ROUND_HALF_ODD); // 9

fmod

Returns the floating point remainder (modulo) of the division of the arguments Description fmod ( $x , $y ) Returns the floating point remainder of dividing the dividend ( x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

SARASWATI ZEROX & PRINT

PH-02765-222990

Parameters x The dividend y The divisor Return Values The floating point remainder of x/y Example: Using fmod() <?php $x = 5.7; $y = 1.3; $r = fmod($x, $y); // $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7 ?>

min

Find lowest value

Description min ( $values ) min (


$value1

$value2

$value3

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values. Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it's seen as the numerically lowest value. If multiple arguments evaluate to 0, min() will return the lowest alphanumerical string value if any strings are given, else a numeric 0 is returned. Parameters values
SARASWATI ZEROX & PRINT PH-02765-222990

An array containing the values. Return Values min() returns the numerically lowest of the parameter values. Example: Example uses of min() <?php echo min(2, 3, 1, 6, 7); // 1 echo min(array(2, 4, 5)); // 2 echo min(0, 'hello'); echo min('hello', 0); echo min('hello', -1); // 0 // hello // -1

// With multiple arrays, min compares from left to right // so in our example: 2 == 2, but 4 < 5 $val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8) // If both an array and non-array are given, the array // is never returned as it's considered the largest $val = min('string', array(2, 5, 7), 42); // string ?>

max

Find highest value

Description max ( $values ) max (


$value1

$value2

$value3

If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values. Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it's seen as the numerically highest value. If multiple arguments evaluate to 0, max() will return a numeric 0 if given, else the alphabetical highest string value will be returned.
SARASWATI ZEROX & PRINT PH-02765-222990

Parameters values An array containing the values. Return Values max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned. When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value. When given a string it will be cast as an integer when comparing. Example: Example uses of max() <?php echo max(1, 3, 5, 6, 7); // 7 echo max(array(2, 4, 5)); // 5 // When 'hello' is cast as integer it will be 0. Both the parameter s are equally // long, so the order they are given in determines the result echo max(0, 'hello'); // 0 echo max('hello', 0); // hello echo max('42', 3); // '42' // Here 0 > -1, so 'hello' is the return value. echo max(-1, 'hello'); // hello // With multiple arrays of different lengths, max returns the lon gest $val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1) // With multiple arrays of the same length, max compares from left to right // using lexicographic order, so in our example: 2 == 2, but 4 < 5
SARASWATI ZEROX & PRINT PH-02765-222990

$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7) // If both an array and non-array are given, the array // is always returned as it's seen as the largest $val = max('string', array(2, 5, 7), 42); // array(2, 5, 7) ?>

pow

Exponential expression )
exp.

Description pow ( $base , Returns


base

$exp

raised to the power of

Parameters base The base to use exp The exponent Return Values base raised to the power of exp. If the result can be represented as integer it will be returned as type integer, else it will be returned as type float. If the power cannot be computed FALSE will be returned instead. Example: Some examples of pow() <?php var_dump(pow(2, 8)); // int(256) echo pow(-1, 20); // 1 echo pow(0, 0); // 1 echo pow(-1, 5.5); // PHP >4.0.6 NAN

SARASWATI ZEROX & PRINT

PH-02765-222990

echo pow(-1, 5.5); // PHP <=4.0.6 1.#IND ?>

sqrt

Square root

Description sqrt ( $arg ) Returns the square root of Parameters arg The argument to process Return Values The square root of numbers.
arg arg.

or the special value NAN for negative

Example: sqrt() example <?php // Precision depends on your precision directive echo sqrt(9); // 3 echo sqrt(10); // 3.16227766 ... ?>

rand

Generate a random integer

Description rand ( $min , $max ) If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

SARASWATI ZEROX & PRINT

PH-02765-222990

Note: On some platforms (such as Windows), getrandmax() is only 32768. If you require a range larger than 32768, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead. Parameters min The lowest value to return (default: 0) max The highest value to return (default: getrandmax()) Return Values A pseudo random value between getrandmax(), inclusive). Example: rand() example <?php echo rand() . "\n"; echo rand() . "\n"; echo rand(5, 15); ?> The above example will output something similar to: 7771 22264 11
min

(or 0) and

max

(or

3.4 Date Function : date, getdate, setdate, checkdate, time, mktime

date():

function is used to format a time and/or date.

The PHP date() function formats a timestamp to a more readable date and time.

SARASWATI ZEROX & PRINT

PH-02765-222990

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

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

The required format parameter in the date() function specifies how to format the date/time. Here are some characters that can be used:

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

A list of all the characters that can be used in the format parameter, can be found in our PHP Date reference. Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting: <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d"); ?> The output of the code above could be something like this: 2009/05/11 2009.05.11 2009-05-11 PHP Date() - Adding a Timestamp
SARASWATI ZEROX & PRINT PH-02765-222990

The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used. The mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. The getdate() function returns an array that contains date and time information for a Unix timestamp. The returning array contains ten elements with relevant information needed when formatting a date string:

[seconds] - seconds [minutes] - minutes [hours] - hours [mday] - day of the month [wday] - day of the week [year] - year [yday] - day of the year [weekday] - name of the weekday [month] - name of the month

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

SARASWATI ZEROX & PRINT

PH-02765-222990

?> The output of the code above could be: Array ( [seconds] => 45 [minutes] => 52 [hours] => 14 [mday] => 24 [wday] => 2 [mon] => 1 [year] => 2006 [yday] => 23 [weekday] => Tuesday [month] => January [0] => 1138110765 )

Example 2 <?php $my_t=getdate(date("U")); print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]"); ?> The output of the code above could be: Wednesday, January 25, 2006

setDate Sets the date


Report a bug Description Object oriented style

SARASWATI ZEROX & PRINT

PH-02765-222990

public DateTime DateTime::setDate ( int $year , int $month , int $day ) Procedural style DateTime date_date_set ( DateTime $object , int $year , int $month , int $day ) Resets the current date of the DateTime object to a different date. Report a bug Parameters object Procedural style only: A DateTime object returned by date_create(). The function modifies this object. year Year of the date. month Month of the date. day Day of the date. Report a bug Return Values Returns the DateTime object for method chaining or FALSE on failure. Report a bug

SARASWATI ZEROX & PRINT

PH-02765-222990

Changelog Versio n 5.3.0

Description

Changed the return value on success from NULL to DateTime.

Report a bug Examples Example #1 DateTime::setDate() example Object oriented style <?php $date = new DateTime(); $date->setDate(2001, 2, 3); echo $date->format('Y-m-d'); ?> Procedural style <?php $date = date_create(); date_date_set($date, 2001, 2, 3); echo date_format($date, 'Y-m-d'); ?> The above examples will output: 2001-02-03 Example #2 Values exceeding ranges are added to their parent values <?php $date = new DateTime(); $date->setDate(2001, 2, 28); echo $date->format('Y-m-d') . "\n";

SARASWATI ZEROX & PRINT

PH-02765-222990

$date->setDate(2001, 2, 29); echo $date->format('Y-m-d') . "\n"; $date->setDate(2001, 14, 3); echo $date->format('Y-m-d') . "\n"; ?> The above example will output: 2001-02-28 2001-03-01 2002-02-03 The checkdate() function returns true if the specified date is valid, and false otherwise. A date is valid if:

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

Syntax checkdate(month,day,year) Parameter month day year Example <?php var_dump(checkdate(12,31,2000)); var_dump(checkdate(2,29,2003)); var_dump(checkdate(2,29,2004)); ?>
SARASWATI ZEROX & PRINT PH-02765-222990

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

The output of the code above will be: bool(true) bool(false) bool(true) The time() function returns the current time as a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Syntax time(void) Parameter Description void Optional. Tips and Notes Note: Calling this function is identical to calling mktime() with no parameters, or calling date("U"). Example <?php $t=time(); echo($t . "<br />"); echo(date("D F d Y",$t)); ?> The output of the code above could be: 1138618081 Mon January 30 2006 The mktime() function returns the Unix timestamp for a date.

SARASWATI ZEROX & PRINT

PH-02765-222990

Syntax for mktime()


mktime(hour,minute,second,month,day,year,is_dst) To go one day in the future we simply add one to the day argument of mktime(): <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> The output of the code above could be something like this: Tomorrow is 2009/05/12

This timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Syntax mktime(hour,minute,second,month,day,year,is_dst) Parameter hour minute second month day year Description Optional. Specifies the hour Optional. Specifies the minute Optional. Specifies the second Optional. Specifies the numerical month Optional. Specifies the day Optional. Specifies the year. The valid range for year is on some systems between 1901 and 2038. However this limitation is overcome in PHP 5 Optional. Set this parameter to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown. If it's unknown, PHP tries to find out itself (which may cause unexpected results). Note: This parameter
PH-02765-222990

is_dst

SARASWATI ZEROX & PRINT

became deprecated in PHP 5. The new timezone handling features should be used instead. Tips and Notes Note: If the arguments are invalid, the function returns false (PHP versions before 5.1 returns -1). Example The mktime() function is useful for doing date arithmetic and validation. It will automatically calculate the correct value for out-of-range input: <?php echo(date("M-d-Y",mktime(0,0,0,12,36,2001))."<br />"); echo(date("M-d-Y",mktime(0,0,0,14,1,2001))."<br />"); echo(date("M-d-Y",mktime(0,0,0,1,1,2001))."<br />"); echo(date("M-d-Y",mktime(0,0,0,1,1,99))."<br />"); ?> The output of the code above would be: Jan-05-2002 Feb-01-2002 Jan-01-2001 Jan-01-1999

3.5 Array Function : count, list, in_array, current, next, previous, end, each, sort, array_merge, array_reverse
The count() function counts the elements of an array, or the properties of an object. Syntax count(array,mode) Parameter Description array Required. Specifies the array or object to count.
SARASWATI ZEROX & PRINT PH-02765-222990

mode

Optional. Specifies the mode of the function. Possible values: 0 - Default. Does not detect multidimensional arrays (arrays within arrays) 1 - Detects multidimensional arrays Note: This parameter was added in PHP 4.2

Tips and Notes Note: This function may return 0 if a variable isn't set, but it may also return 0 if a variable contains an empty array. The isset() function can be used to test if a variable is set. Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); $result = count($people); echo $result; ?> The output of the code above will be: 4 The list() function is used to assign values to a list of variables in one operation. Syntax list(var1,var2...)

SARASWATI ZEROX & PRINT

PH-02765-222990

Parameter Description var1 Required. The first variable to assign a value to var2 Optional. More variables to assign values to Tips and Notes Note: This function only works on numerical arrays.

Example 1 <?php $my_array = array("Dog","Cat","Horse"); list($a, $b, $c) = $my_array; echo "I have several animals, a $a, a $b and a $c."; ?> The output of the code above will be: I have several animals, a Dog, a Cat and a Horse. Example 2 <?php $my_array = array("Dog","Cat","Horse"); list($a, , $c) = $my_array; echo "Here I only use the $a and $c variables."; ?> The output of the code above will be: Here I only use the Dog and Horse variables. The in_array() function searches an array for a specific value.

SARASWATI ZEROX & PRINT

PH-02765-222990

This function returns TRUE if the value is found in the array, or FALSE otherwise. Syntax in_array(search,array,type) Parameter search array type Description Required. Specifies the what to search for Required. Specifies the array to search Optional. If this parameter is set, the in_array() function searches for the search-string and specific type in the array

Tips and Notes Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive. Example 1 <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn",$people)) { echo "Match found"; } else { echo "Match not found"; } ?> The output of the code above will be: Match found Example 2 <?php
SARASWATI ZEROX & PRINT PH-02765-222990

$people = array("Peter", "Joe", "Glenn", "Cleveland", 23); if (in_array("23",$people, TRUE)) { echo "Match found<br />"; } else { echo "Match not found<br />"; } if (in_array("Glenn",$people, TRUE)) { echo "Match found<br />"; } else { echo "Match not found<br />"; } if (in_array(23,$people, TRUE)) { echo "Match found<br />"; } else { echo "Match not found<br />"; } ?> The output of the code above will be: Match not found Match found Match found The current() function returns the value of the current element in an array. Syntax current(array) Parameter Description

SARASWATI ZEROX & PRINT

PH-02765-222990

array

Required. Specifies the array to use

Tips and Notes Note: This function returns FALSE on empty elements or elements with no value. Tip: This function does not move the arrays internal pointer. To do this, use the next() and prev() functions. Example 1 <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; ?> The output of the code above will be: Peter The next() function moves the internal pointer to, and outputs, the next element in the array. This function returns the value of the next element in the array on success, or FALSE if there are no more elements. Syntax next(array) Parameter Description array Required. Specifies the array to use

Tips and Notes

SARASWATI ZEROX & PRINT

PH-02765-222990

Note: This function returns FALSE on empty elements or elements with no value. Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; echo next($people); ?> The output of the code above will be: Peter Joe The prev() function moves the internal pointer to, and outputs, the previous element in the array. This function returns the value of the previous element in the array on success, or FALSE if there are no more elements. Syntax prev(array) Parameter Description array Required. Specifies the array to use Tips and Notes Note: This function returns FALSE on empty elements or elements with no value.

Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");

SARASWATI ZEROX & PRINT

PH-02765-222990

echo current($people) . "<br />"; echo next($people) . "<br />"; echo prev($people); ?> The output of the code above will be: Peter Joe Peter The end() function moves the internal pointer to, and outputs, the last element in the array. This function returns the value of the last element in the array on success. Syntax end(array) Parameter Description array Required. Specifies the array to use Example <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; echo end($people); ?> The output of the code above will be: Peter Cleveland The

each()

function returns the current element key and

SARASWATI ZEROX & PRINT

PH-02765-222990

value, and moves the internal pointer forward. This element key an value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key. This function returns FALSE if there are no more array elements. Syntax each(array) Parameter Description array Required. Specifies the array to use Tips and Notes Note: This function returns FALSE on empty elements or elements with no value. Example 1 <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); print_r (each($people)); ?> The output of the code above will be: Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )

Example 2 Same example as above, but with a loop to output the whole array: <?php $people = array("Peter", "Joe", "Glenn", "Cleveland");

SARASWATI ZEROX & PRINT

PH-02765-222990

reset($people); while (list($key, $val) = each($people)) { echo "$key => $val<br />"; } ?> The output of the code above will be: 0 1 2 3 => => => => Peter Joe Glenn Cleveland function sorts an array by the values.

The

sort()

This function assigns new keys for the elements in the array. Existing keys will be removed. This function returns TRUE on success, or FALSE on failure. Syntax sort(array,sorttype) Parameter Description array Required. Specifies the array to sort sorttype Optional. Specifies how to sort the array values. Possible values: SORT_REGULAR - Default. Treat values as they are (don't change types) SORT_NUMERIC - Treat values numerically

SORT_STRING - Treat values as strings SORT_LOCALE_STRING - Treat values as strings, based on local settings

Example

SARASWATI ZEROX & PRINT

PH-02765-222990

<?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); sort($my_array); print_r($my_array); ?> The output of the code above will be: Array ( [0] => Cat [1] => Dog [2] => Horse ) The array_merge() function merges one ore more arrays into one array. Syntax array_merge(array1,array2,array3...) Parameter array1 array2 array3 Description Required. Specifies an array Optional. Specifies an array Optional. Specifies an array

Tips and Notes Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others. Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value. (See example 2)

SARASWATI ZEROX & PRINT

PH-02765-222990

Example 1 <?php $a1=array("a"=>"Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge($a1,$a2)); ?> The output of the code above will be: Array ( [a] => Horse [b] => Cat [c] => Cow ) Example 2 Using only one array parameter. <?php $a=array(3=>"Horse",4=>"Dog"); print_r(array_merge($a)); ?> The output of the code above will be: Array ( [0] => Horse [1] => Dog )

The array_reverse() function returns an array in the reverse order. Syntax array_reverse(array,preserve) Parameter Description array Required. Specifies an array preserve Optional. Possible values: true false Specifies if the function should preserve the

SARASWATI ZEROX & PRINT

PH-02765-222990

array's keys or not. Example <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_reverse($a)); ?> The output of the code above will be: Array ( [c] => Horse [b] => Cat [a] => Dog )

3.6 File Function : fopen,fread,fwrite,fclose


The

fopen()

function opens a file or URL.

If fopen() fails, it returns FALSE and an error on failure. You can hide the error output by adding an '@' in front of the function name. Syntax fopen(filename,mode,include_path,context) Parameter Description filename Required. Specifies the file or URL to open mode Required. Specifies the type of access you require to the file/stream. Possible values:

"r" (Read only. Starts at the beginning of the file) "r+" (Read/Write. Starts at the beginning of the file) "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)

SARASWATI ZEROX & PRINT

PH-02765-222990

"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist) "a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist) "a+" (Read/Write. Preserves file content by writing to the end of the file) "x" (Write only. Creates a new file. Returns FALSE and an error if file already exists)

"x+" (Read/Write. Creates a new file. Returns FALSE and an error if file already exists) include_pathOptional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

Tips and Notes Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character. Windows offers a translation flag ('t') which will translate \n to \r\n when working with the file. You can also use 'b' to force binary mode. To use these flags, specify either 'b' or 't' as the last character of the mode parameter. Example <?php $file = $file = $file = $file = $file = ?> fopen("test.txt","r"); fopen("/home/test/test.txt","r"); fopen("/home/test/test.gif","wb"); fopen("http://www.example.com/","r"); fopen("ftp://user:password@example.com/test.txt","w");

SARASWATI ZEROX & PRINT

PH-02765-222990

The

fread()

reads from an open file.

The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the read string, or FALSE on failure. Syntax fread(file,length) Parameter Description file Required. Specifies the open file to read from length Required. Specifies the maximum number of bytes to read Tips and Notes Tip: This function is binary-safe (meaning that both binary data, like images, and character data can be written with this function). Example 1 Read 10 bytes from file: <?php $file = fopen("test.txt","r"); fread($file,"10"); fclose($file); ?> Example 2 Read entire file: <?php $file = fopen("test.txt","r"); fread($file,filesize("test.txt")); fclose($file); ?>
SARASWATI ZEROX & PRINT PH-02765-222990

The

fwrite()

writes to an open file.

The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the number of bytes written, or FALSE on failure. Syntax fwrite(file,string,length) Parameter Description file Required. Specifies the open file to write to string Required. Specifies the string to write to the open file length Optional. Specifies the maximum number of bytes to write Tips and Notes Tip: This function is binary-safe (meaning that both binary data, like images, and character data can be written with this function).

Example <?php $file = fopen("test.txt","w"); echo fwrite($file,"Hello World. Testing!"); fclose($file); ?> The output of the code above will be: 21 The

fclose()

function closes an open file.

SARASWATI ZEROX & PRINT

PH-02765-222990

This function returns TRUE on success or FALSE on failure. Syntax fclose(file) Parameter Description file Required. Specifies the file to close Example <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?>

SARASWATI ZEROX & PRINT

PH-02765-222990

4 - WORKING WITH DATA.


4.1 FORM element, INPUT elements The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. The most important form element is the input element. The input element is used to select user information. An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more. About HTML Form Tag When we create input box. check box, radio button etc. So this necessary to send these control value to the server. So Form tag is very necessary part to send these control value to the server. on Form tag some parameter is necessary. <form name="frm" action="test2.php" method="post"> you input box, check box etc here. </form> HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. The <form> tag is used to create an HTML form: <form> . input elements . </form>

SARASWATI ZEROX & PRINT

PH-02765-222990

name is name of the form action is where you send value here we send value on test2.php page. if you take action blank like action="" then values send same page. method there are two method post and get. post send value to the server but not show on URL. get send value to the server but show on URL. HTML Form Tags Tag Description

<form> Defines an HTML form for user input <input / Defines an input control > Defines a multi-line text input control <textarea rows="2" cols="20"> At W3Schools you will find all the Web-building tutorials you need, from basic HTML to advanced XML, SQL, ASP, and PHP. </textarea> <textare The <textarea> tag defines a multi-line text input a> control. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier). The size of a textarea can be specified by the cols and rows attributes, or even better; through CSS' height and width properties. Defines a label for an input element <label> <form> <label for="male">Male</label> <input type="radio" name="sex" id="male" />
SARASWATI ZEROX & PRINT PH-02765-222990

<br /> <label for="female">Female</label> <input type="radio" name="sex" id="female" /> </form> Defines a border around elements in a form <form> <fieldset> <legend>Personalia:</legend> Name: <input type="text" size="30" /><br /> Email: <input type="text" size="30" /><br /> Date of birth: <input type="text" size="10" /> <fieldset </fieldset> > </form> The <fieldset> tag is used to logically group together elements in a form. The <fieldset> tag draws a box around the related form elements. The <legend> tag defines a caption for the fieldset element. Defines a caption for a fieldset element <form> <fieldset> <legend>Personalia:</legend> Name: <input type="text" size="30" /><br /> <legend Email: <input type="text" size="30" /><br /> > Date of birth: <input type="text" size="10" /> </fieldset> </form> The <legend> tag defines a caption for the fieldset element. <select> Defines a select list (drop-down list)

SARASWATI ZEROX & PRINT

PH-02765-222990

<select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> The <select> tag is used to create a select list (dropdown list). The <option> tags inside the select element define the available options in the list. Defines a group of related options in a select list <select> <optgroup label="Swedish Cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </optgroup> <optgroup label="German Cars"> <optgrou <option value="mercedes">Mercedes</option> p> <option value="audi">Audi</option> </optgroup> </select> The <optgroup> tag is used to group together related options in a select list. If you have a long list of options, groups of related options are easier to handle for the user. Defines an option in a select list <select> <option>Volvo</option> <option> <option>Saab</option> <option>Mercedes</option> <option>Audi</option> </select>

SARASWATI ZEROX & PRINT

PH-02765-222990

The <option> tag defines an option in a select list. The option element goes inside the select element. Defines a push button <button type="button">Click Me!</button> The <button> tag defines a push button. <button Inside a button element you can put content, like text > or images. This is the difference between this element and buttons created with the input element. Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".

4.2 Processing the form The $_GET Function


The built-in $_GET function is used to collect values from a form sent with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. Example <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL sent to the server could look something like this: http://www.w3schools.com/welcome.php?
SARASWATI ZEROX & PRINT PH-02765-222990

fname=Peter&age=37 The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!

When to use method="get"? When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.

The $_POST Function


The built-in $_POST function is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file). Example <form action="welcome.php" method="post"> Name: <input type="text" name="fname" />
SARASWATI ZEROX & PRINT PH-02765-222990

Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL will look like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. When to use method="post"? Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The PHP $_REQUEST Function


The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.

Example Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old.

SARASWATI ZEROX & PRINT

PH-02765-222990

Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this: <html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> Output could be something like this: Welcome John! You are 28 years old. Example 1:Full code of HTML Tag. <html> <head> <title>test1</title>
SARASWATI ZEROX & PRINT PH-02765-222990

</head> <body> <form action="test2.php" method="post"> Enter Name<input name="fname" type="text" /><br /> <input name="btnsubmit" type="submit" value="Submit" /> </form> </body> </html> save this file such as you save it name as test1.php. In this code we use action="test2.php" then this value send to test2.php page We Received these value on test2.php page and can print it. Now make another page test2.php. How to reterive value of Form tag. For reterive value of Form tag use super global variable $_POST['controlname'] when method is post on form tag. $_GET['controlname'] when method is get on form tag. Example 1:PHP script to reterive form tag value. please save this file test2.php because our action is test2.php. <html> <head> <title>test2</title> </head> <body> <?php $fname=$_POST['fname']; echo $fname; ?> </body> </html>

4.3 User Input


The most important form element is the input element. The input element is used to select user information.

SARASWATI ZEROX & PRINT

PH-02765-222990

An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more.

4.3.1 INPUT checkbox type


Checkboxes <input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE options of a limited number of choices. <form> <input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br /> <input type="checkbox" name="vehicle" value="Car" /> I have a car </form> How the HTML code above looks in a browser: I have a bike I have a car

4.3.2 one form, multiple processing 4.3.3 Radio INPUT element


Radio Buttons <input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE one of a limited number of choices: <form> <input type="radio" name="sex" value="male" /> Male<br /> <input type="radio" name="sex" value="female" /> Female </form> How the HTML code above looks in a browser:

SARASWATI ZEROX & PRINT

PH-02765-222990

Male Female Example 2:<html> <head> <title>test1</title> </head> <body> <form name="frm" action="test2.php" method="get"> Enter Gender<input name="gender" type="radio" value="Male" /><br /> <input name="btnsubmit" type="submit" value="Submit" /> </form> </body> </html>

Note:-In this code we provide value in radio. Because we can not input any value in radio button like in textbox we can input any value. test2.php <html> <head> <title>test2</title> </head> <body> <?php $gender=$_Get['gender']; echo $gender; ?> </body> </html>

4.3.4 Multiple submit buttons


SARASWATI ZEROX & PRINT PH-02765-222990

If you have a bunch of submits, a good idea is to use a switch/case statement to handle the different code branches more efficiently. <html><head>Multi-button from with switch/case</head> <body> <form action="processor.php" method="post"> Enter a number: <input type="text" name="number_1" size="3"> <br> Enter another number: <input type="text" name="number_2" size="3"> <br> <input type="submit" name="calculate" value="add"> <input type="submit" name="calculate" value="subtract"> <input type="submit" name="calculate" value="multiply"> </form> </body> </html> The processing script needs to check the value of the $_POST['calculate'] element, and branch the code appropriately. The most efficient way to do this is with a switch-case statement, as follows: <?php // branch on the basis of 'calculate' value switch ($_POST['calculate']) { // if calculate => add case 'add': echo $_POST['number_1'] . " + " . $_POST['number_2'] . " = " . ($_POST['number_1']+$_POST['number_2']); break; // if calculate => subtract case 'subtract': echo $_POST['number_1'] . " - " . $_POST['number_2'] . " = " . ($_POST['number_1']-$_POST['number_2']); break; // if calculate => multiply case 'multiply': echo $_POST['number_1'] . " x " . $_POST['number_2'] . " = " . ($_POST['number_1']*$_POST['number_2']);
SARASWATI ZEROX & PRINT PH-02765-222990

break; } ?> Depending on which button gets clicked, the appropriate value is passed to the processing script and the corresponding "case" block is invoked. If you have a large number of submit buttons to deal with, this approach is easier to read and understand than multiple if-else blocks.

4.3.5 Basic input testing


Method What It Does

number($inp Tests if ut, $opts) input is a number. Can also check if numeric input falls within a specific range. email($input Tests if ) input is a valid email address. string($input Tests if , $opts) input is a string. Can also check if string conforms
SARASWATI ZEROX & PRINT PH-02765-222990

to a specific pattern or falls within a specific character limit. uri($input) Tests if input is a valid URL.

date($input, Tests if $opts) input is a valid date. So, if you need to test if a particular chunk of data conforms to, say, the format for an e-mail address, all you need to do is pass it to Validate'semail() method, which will check it for you and return a true/false value. You can use this value to display an error, halt further execution of the script, or write to an error log.

4.3.6 Dynamic page title 4.3.7 Manipulating the string as an array


<?php $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as $color) { echo "Do you like $color?\n"; } ?> The above example will output: Do you like red?

SARASWATI ZEROX & PRINT

PH-02765-222990

Do you like blue? Do you like green? Do you like yellow?

4.4 Adding items


array_push Push one or more elements onto the end of array Description array_push ( ,
$var)

$array

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as: <?php $array[] = $var; ?> repeated for each
var.

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created. Parameters array The input array. var The pushed value. Return Values Returns the new number of elements in the array.

SARASWATI ZEROX & PRINT

PH-02765-222990

Example: array_push() example <?php $stack = array("orange", "banana"); array_push($stack, "apple", "raspberry"); print_r($stack); ?> The above example will output: Array ( [0] => [1] => [2] => [3] => )

orange banana apple raspberry

4.5 Validating the user input


simple HTML form. <h3>* denotes required field!</h3>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <p> <label for="name">Name</label> <input id="name" type="text" name="userName" maxlength="25" />*<br /> <label for="address">Address</label> <input id="address" type="text" name="userAddress" maxlength="100" /><br /> <label for="city">City</label> <input id="city" type="text" name="userCity" maxlength="25" /><br /> <label for="zip">Zip</label> <input id="zip" type="text" name="userZip" maxlength="5" /><br /> <label for="email">Email</label> <input id="email" type="text" name="userEmail" maxlength="50" />*<br /> <label for="submit">Submit</label> <input id="submit" type="submit" value="Mail It!" /><br /> </p> </form>

With the maxlength set in our form, we can prevent most users from accidentally entering strings of 2 megabytes or something silly. Always check for string length. As you can see in our form

SARASWATI ZEROX & PRINT

PH-02765-222990

the action is $_SERVER['PHP_SELF'] so that it posts to itself. We have 5 input fields named:

userName userAddress userCity userZip userEmail

>From the name of the input fields we build our super global $_POST array. All of the inputs are of the type text. This means they will give us a string in the $_POST array of the same name. ie:

userName becomes $_POST['userName'] userAddress becomes $_POST['userAddress'] userCity becomes $_POST['userCity'] userZip becomes $_POST['userZip'] userEmail becomes $_POST['userEmail']

With this in mind, we can now begin to check them individually for content. you could use isset()'s ability to take multiple variables and check them all in one sweep by creating a function to do it for us. It might look something like this: <?php // check ALL the POST variables function checkSet(){ return isset($_POST['userName'], $_POST['userAddress'], $_PO ST['userCity'], $_POST['userZip'], $_POST['userEmail']); } if(checkSet() != FALSE)
{ // check the POST variable userName is sane, and is not empty if(empty($_POST['userName'])==FALSE && sanityCheck($_POST['userName'], 'string', 25) != FALSE) { $userName = $_POST['userName'];

SARASWATI ZEROX & PRINT

PH-02765-222990

} else { echo 'Username is not set'; exit(); } } else { // this will be the default message if the form accessed without POSTing echo '<p>Please fill in the form above</p>'; }

?>

Lets look at what we have done here. First we used our checkSet function to be sure all the variables were set. When the form page is first accessed, these variables are not set, so the default message Please fill in the form above is displayed. This also helps should a malicious user try to use there own form without a variable and so it will throw an error saying Undefined Index and will give the path of the filename. Not a good thing security wise. If all the variable have been set, then we can begin to check the sanity of of the variables using our sanityCheck() function. The first variable we have checked is the userName variable. This field is a required field in our form, so we check it with empty function to be sure that it has a value, i.e. It is not empty or zero. If userName is empty the script echoes and error message and exit()'s the script. Lets continue with some more of our fields. We do the same, exept we do not need to use the empty function to check for nonrequired fields.
<?php // check all our variables are set if(checkSet() != FALSE) { // check the POST variable userName is sane, and is not empty if(empty($_POST['userName'])==FALSE && sanityCheck($_POST['userName'], 'string', 25) != FALSE) { $userName = $_POST['userName']; } else { echo 'Username is not set'; exit();

SARASWATI ZEROX & PRINT

PH-02765-222990

} // here we test for the sanity of userAddress, we dont need to stop the // the script if it is empty as it is not a required field. if(sanityCheck($_POST['userAddress'], 'string', 100) != FALSE) { $userAddress = $_POST['userAddress']; } // here we test for the sanity of userCity, we dont need to stop the // the script if it is empty as it is not a required field. if(sanityCheck($_POST['userCity'], 'string', 25) != FALSE) { $userCity = $_POST['userCity']; } } else { // this will be the default message if the form accessed without POSTing echo '<p>Please fill in the form above</p>'; } ?>

How do I validate a number. Ok, now we come to something a little different, the next variable we must deal with is the userZip. This will have a value which is numerical. Whilst we still need to do our basic sanity check, we also need to check that the number is not greater than 5 digits and be sure a mailicious user does not try to put in something like minus ten or something silly. So, we need a function to check for this also. In our sanityCheck function we set the type to numeric which will check that the value is a number using is_numeric. You can use this function to check the numeric values.
<?php // check number is greater than 0 and $length digits long // returns TRUE on success function checkNumber($num, $length){ if($num > 0 && strlen($num) == $length) { return TRUE; } } ?>

With this little function we can now also check our numbers are correct for our use. Lets continue again:

SARASWATI ZEROX & PRINT

PH-02765-222990

<?php // check all our variables are set if(checkSet() != FALSE) { // check the POST variable userName is sane, and is not empty if(empty($_POST['userName'])==FALSE && sanityCheck($_POST['userName'], 'string', 25) != FALSE) { $userName = $_POST['userName']; } else { echo 'Username is not set'; exit(); } // here we test for the sanity of userAddress, we dont need to stop the // the script if it is empty as it is not a required field. if(sanityCheck($_POST['userAddress'], 'string', 100) != FALSE) { $userAddress = $_POST['userAddress']; } else { $userAddress = ''; } // here we test for the sanity of userCity, we dont need to stop the // the script if it is empty as it is not a required field. if(sanityCheck($_POST['userCity'], 'string', 25) != FALSE) { $userCity = $_POST['userCity']; } else { $userCity = ''; } // check the sanity of the number and that it is greater than zero and 5 digits long if(sanityCheck($_POST['userZip'], 'numeric', 5) != FALSE && checkNumber($_POST['us erZip'], 5) == TRUE) { $userZip = $_POST['userZip']; } else { $userZip=''; } } else { // this will be the default message if the form accessed without POSTing echo '<p>Please fill in the form above</p>';

SARASWATI ZEROX & PRINT

PH-02765-222990

} ?>

From the code we now have, we see that the userZip must be numerical and must be 5 digits long. If it is not, it is of no consequence as it is not a required field and can remain blank.

Vaidate phone number: ph_no.html: <html> <head> <title>phone number validation</title> </head> <body> <form action=ph_no.php method=post> Phone no:<input type=text name=no> <input type=submit name=submit value=submit> </from> </body> </html> ph_no.php: <?php $no=$_POST[no]; if(!eregi(^[+][0-9]{2}-[0-9]{3}-[0-9]{7}$,$no)) { echo not valid;
SARASWATI ZEROX & PRINT PH-02765-222990

} else echo valid; ?>

4.6 Passing variables between pages 4.6.1 Passing variables through a URL
A common way to pass values from the browser to the server is by appending them to the URL as follows: Syntax http://www.webucator.com/hello.php?greet=Hello&who=World The part of the URL that follows the question mark is called the query string. One or more name-value pairs can be passed to the server in this way. Each name-value pair is separated by an ampersand (&). The processing page can read these namevalue pairs and use them to determine its response. The HTML page below shows an example of how these namevalue pairs might be passed. Code Sample: PhpBasics/Demos/HelloHi.html <html> <head> <title>Preferred Greeting</title> </head> <body> Do you prefer a formal greeting or an informal greeting? <ul> <li><a href="HelloHi.php?greet=Hello">Formal</a></li> <li><a href="HelloHi.php?greet=Hi">Informal</a></li> <li><a href="HelloHi.php? greet=Howdy">Friendly</a></li> </ul> </body>

SARASWATI ZEROX & PRINT

PH-02765-222990

</html> Code Sample: PhpBasics/Demos/HelloHi.php <?php //Assign the passed variable to a variable with //a more convenient name. $greeting = $_GET['greet']; ?> <html> <head> <title><?= $greeting ?> World!</title> </head> <body> <?php echo "$greeting World!"; ?> </body> </html>

4.6.2 Passing variables with sessions


A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

PHP Session Variables When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping
SARASWATI ZEROX & PRINT PH-02765-222990

items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL. Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?> <html> <body> </body> </html> The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1; ?>

SARASWATI ZEROX & PRINT

PH-02765-222990

<html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> Output: Pageviews=1 In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?> Destroying a Session If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?> You can also completely destroy the session by calling the session_destroy() function:
SARASWATI ZEROX & PRINT PH-02765-222990

<?php session_destroy(); ?> Note: session_destroy() will reset your session and you will lose all your stored session data.

4.6.3 Passing variables with cookies


A cookie is often used to identify a user. What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie(name, value, expire, path, domain); Example 1 In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour: <?php setcookie("user", "Alex Porter", time()+3600); ?>

SARASWATI ZEROX & PRINT

PH-02765-222990

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead). Example 2 You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> In the example above the expiration time is set to a month ( 60 sec * 60 min * 24 hours * 30 days). How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?> In the following example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_COOKIE["user"]))

SARASWATI ZEROX & PRINT

PH-02765-222990

echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html> How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> What if a Browser Does NOT Support Cookies? If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial). The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>

SARASWATI ZEROX & PRINT

PH-02765-222990

</body> </html> Retrieve the values in the "welcome.php" file like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>

4.6.4 Passing information with forms


The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>

SARASWATI ZEROX & PRINT

PH-02765-222990

</body> </html> When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this: <html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> Output could be something like this: Welcome John! You are 28 years old

SARASWATI ZEROX & PRINT

PH-02765-222990

You might also like