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 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
SARASWATI ZEROX & PRINT PH-02765-222990
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
2 - BASICS OF PHP
SARASWATI ZEROX & PRINT PH-02765-222990
2.1 PHP structure and syntax
<?php?>
2.2 Creating the PHP pages
<?phpecho "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.
<?php
//This a comment;
/*This is a;
Comment;
SARASWATI ZEROX & PRINT PH-02765-222990
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>
<?phpecho "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 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
SARASWATI ZEROX & PRINT PH-02765-222990
<?php
// Valid constant namesdefine("FOO", "something");define("FOO2", "something else");define("FOO_BAR", "something more");
// Invalid constant namesdefine("2FOO", "something");
// This is valid, but should be avoided:// PHP may one day provide a magical constant// that will break your scriptdefine("__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:
<?php$txt="Hello World!";$x=16;?>
Use of Static Variable::
<?php$a = 1;
?>
<?phpfunction test()
SARASWATI ZEROX & PRINT PH-02765-222990
{ $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();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)
SARASWATI ZEROX & PRINT PH-02765-222990
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
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;
SARASWATI ZEROX & PRINT PH-02765-222990
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;
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!";?>
SARASWATI ZEROX & PRINT PH-02765-222990
</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.
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
SARASWATI ZEROX & PRINT PH-02765-222990
is used if no match is found.
Example
<html><body><?phpswitch ($x){case 1: echo "Number 1"; break;case 2: echo "Number 2"; break;case 3: echo "Number 3"; break;default: echo "No number between 1 and 3";}?></body></html>
PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:
SARASWATI ZEROX & PRINT PH-02765-222990
while - loops through a block of code while a specified condition is true do...while - loops through a block of code once, and then repeats the
loop as long as a specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
The while Loop
The while loop executes a block of code while a condition is true.
Syntax
while (condition) { code to be executed; }
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html><body><?php$i=1;while($i<=5) { echo "The number is " . $i . "<br />"; $i++; }?></body></html>
Output:
The number is 1The number is 2The number is 3
SARASWATI ZEROX & PRINT PH-02765-222990
The number is 4The number is 5
The do...while Statement
The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
Syntax
do { code to be executed; } while (condition);
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5:<html><body><?php$i=1;do { $i++; echo "The number is " . $i . "<br />"; }while ($i<=5);?></body></html>
Output:
The number is 2
SARASWATI ZEROX & PRINT PH-02765-222990
The number is 3The number is 4The number is 5The number is 6
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment) { code to be executed; }
Parameters:
init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html><body><?phpfor ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />";
SARASWATI ZEROX & PRINT PH-02765-222990
}?></body></html>
Output:
The number is 1The number is 2The number is 3The number is 4The number is 5
The foreach Loop
The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value) { code to be executed; }
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html><body><?php$x=array("one","two","three");foreach ($x as $value) { echo $value . "<br />"; }?>
SARASWATI ZEROX & PRINT PH-02765-222990
</body></html>
Output:
onetwothree
2.8 PHP Operators
PHP Operators
This section lists the different operators used in PHP.
Arithmetic Operators
Operator Description Example Result+ Addition x=2
x+24
- Subtraction x=25-x
3
* Multiplication x=4x*5
20
/ Division 15/55/2
32.5
% Modulus (division remainder) 5%210%810%2
120
++ Increment x=5x++
x=6
-- Decrement x=5x--
x=4
Assignment Operators
Operator Example Is The Same As= x=y x=y
SARASWATI ZEROX & PRINT PH-02765-222990
+= x+=y x=x+y-= x-=y x=x-y*= x*=y x=x*y/= x/=y x=x/y.= x.=y x=x.y%= x%=y x=x%y
Comparison Operators
Operator Description Example== is equal to 5==8 returns false!= is not equal 5!=8 returns true<> is not equal 5<>8 returns true> is greater than 5>8 returns false< is less than 5<8 returns true>= is greater than or equal to 5>=8 returns false<= is less than or equal to 5<=8 returns true
Logical Operators
Operator Description Example&& and x=6
y=3 (x < 10 && y > 1) returns true
|| or x=6y=3 (x==5 || y==5) returns false
! not x=6y=3 !(x==y) returns true
2.9 Arrays
SARASWATI ZEROX & PRINT PH-02765-222990
What is an Array?
A variable is a storage area holding a number or text. The problem is, a variable will hold only one value. An array is a special variable, which can store multiple values in one single variable. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Saab";$cars2="Volvo";$cars3="BMW"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The best solution here is to use an array! An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own index so that it can be easily accessed.In PHP, there are three kind of arrays:
Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a
value
Multidimensional array - An array containing one or more arrays
Numeric Arrays
A numeric array stores each array element with a numeric index.There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
2. In the following example we assign the index manually:
$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";
SARASWATI ZEROX & PRINT PH-02765-222990
Example
In the following example you access the variable values by referring to the array name and index:
<?php$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";?>
The code above will output:
Saab and Volvo are Swedish cars.
Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
SARASWATI ZEROX & PRINT PH-02765-222990
$ages['Quagmire'] = "30";$ages['Joe'] = "34";
The ID keys can be used in a script:
<?php$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";?>
The code above will output:
Peter is 32 years old.
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn"
SARASWATI ZEROX & PRINT PH-02765-222990
), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output:
Array([Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan )[Quagmire] => Array ( [0] => Glenn )[Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ))
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
SARASWATI ZEROX & PRINT PH-02765-222990
" a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?
2.10 User defined function, argument function, Variable function,Return Function, default argument, variable length argument
PHP Functions
In this chapter we will show you how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName(){code to be executed;}
PHP function guidelines:
Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a number)
User defined function
Example
A simple function that writes my name when it is called:
SARASWATI ZEROX & PRINT PH-02765-222990
<html><body>
<?phpfunction writeName(){echo "Kai Jim Refsnes";}
echo "My name is ";writeName();?>
</body></html>
Output:
My name is Kai Jim Refsnes
PHP Functions - Adding parameters
argument function
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html><body>
SARASWATI ZEROX & PRINT PH-02765-222990
<?phpfunction writeName($fname){echo $fname . " Refsnes.<br />";}
echo "My name is ";writeName("Kai Jim");echo "My sister's name is ";writeName("Hege");echo "My brother's name is ";writeName("Stale");?>
</body></html>
Output:
My name is Kai Jim Refsnes.My sister's name is Hege Refsnes.My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<html><body>
<?phpfunction writeName($fname,$punctuation){echo $fname . " Refsnes" . $punctuation . "<br />";}
SARASWATI ZEROX & PRINT PH-02765-222990
echo "My name is ";writeName("Kai Jim",".");echo "My sister's name is ";writeName("Hege","!");echo "My brother's name is ";writeName("Ståle","?");?>
</body></html>
Output:
My name is Kai Jim Refsnes.My sister's name is Hege Refsnes!My brother's name is Ståle Refsnes?
PHP Functions - Return values
Return Function
If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of statement or script file.
since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return() with parentheses but with no arguments will result in a parse error.
You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value
SARASWATI ZEROX & PRINT PH-02765-222990
of $a).
To let a function return a value, use the return statement.
Example
<html><body>
<?phpfunction add($x,$y){$total=$x+$y;return $total;}
echo "1 + 16 = " . add(1,16);?>
</body></html>
Output:
1 + 16 = 17
Variable function:
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Example: Variable function example
<?phpfunction foo() { echo "In foo()<br />\n";
SARASWATI ZEROX & PRINT PH-02765-222990
}
function bar($arg = ''){ echo "In bar(); argument was '$arg'.<br />\n";}
// This is a wrapper function around echofunction echoit($string){ echo $string;}
$func = 'foo';$func(); // This calls foo()
$func = 'bar';$func('test'); // This calls bar()
$func = 'echoit';$func('test'); // This calls echoit()?>
default argument
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:
Example: Incorrect usage of default function arguments
<?phpfunction makeyogurt($type = "acidophilus", $flavour){ return "Making a bowl of $type $flavour.\n";}
SARASWATI ZEROX & PRINT PH-02765-222990
echo makeyogurt("raspberry"); // won't work as expected?>
The above example will output:
Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/phptest/functest.html on line 41Making a bowl of raspberry .
Now, compare the above with this:
Example: Correct usage of default function arguments
<?phpfunction makeyogurt($flavour, $type = "acidophilus"){ return "Making a bowl of $type $flavour.\n";} echo makeyogurt("raspberry"); // works as expected?>
The above example will output:
Making a bowl of acidophilus raspberry.
Note: As of PHP 5, default values may be passed by reference.
Example Use of default parameters in functions
<?phpfunction makecoffee($type = "cappuccino"){ return "Making a cup of $type.\n";}echo makecoffee();echo makecoffee(null);echo makecoffee("espresso");?>
SARASWATI ZEROX & PRINT PH-02765-222990
The above example will output:
Making a cup of cappuccino.Making a cup of .Making a cup of espresso.
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 variable-length 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.
SARASWATI ZEROX & PRINT PH-02765-222990
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"); 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 Calling a function that uses func_num_args():\n"); print(" ".myMax()."\n"); print(" ".myMax(3)."\n"); print(" ".myMax(3, 1, 4)."\n"); print(" ".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 Calling a function that uses func_get_args():\n"); print(" ".myMin()."\n");
SARASWATI ZEROX & PRINT PH-02765-222990
print(" ".myMin(5)."\n"); print(" ".myMin(5, 6, 2)."\n"); print(" ".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 9
Calling a function that uses func_get_args():
5 2 1
SARASWATI ZEROX & PRINT PH-02765-222990
3 - WORKING WITH FUNCTIONS
3.1 Variable Function : gettype, settype, isset, unset, strval, floatval,intval, print_r
gettype:This function returns the type of variable.
Return Type :- string
Descriptionstring gettype ($var )
Returns the type of the PHP variable var.
Return Values
Possibles values for the returned string are:
"boolean" "integer"
"double" (for historical reasons "double" is returned in case of a float, and not simply "float")
"string"
"array"
"object"
SARASWATI ZEROX & PRINT PH-02765-222990
"resource"
"NULL"
"unknown type"
Example 6:-<?php$x="welcome";$y=56;$z=56.34;echo gettype($x);echo "<br>";echo gettype($y);echo "<br>";echo gettype($z);?>
Output :stringintegerdouble
settype ::This function returns convert variable datatype.
Return Type :- bool
Descriptionbool settype ($var , string $type )
Set the type of variable var to type.
Parametersvar
The variable being converted.
type
SARASWATI ZEROX & PRINT PH-02765-222990
Possibles values of 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)
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 :integerbooleandouble
isset:
SARASWATI ZEROX & PRINT PH-02765-222990
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
Descriptionbool 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 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.
Parametersvar
The variable to be checked.
var
Another variable ..
Return Values
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Example 2:-<?php
$var = 30;
if (isset($var))
SARASWATI ZEROX & PRINT PH-02765-222990
{echo "Varible is exist";}else{echo "Varible is not exist";}
?>
Output :-Varible is exist
unset:This function destroy variables.
Note :- You can use unset function to destroy session varaibles.
Return Type :- void
Descriptionvoid 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.
Parametersvar
The variable to be unset.
var
Another variable ..
SARASWATI ZEROX & PRINT PH-02765-222990
<?phpfunction foo(){ static $bar; $bar++; echo "Before unset: $bar, "; unset($bar); $bar = 23; echo "after unset: $bar\n";}
foo();foo();foo();?>
The above example will output:
Before unset: 1, after unset: 23Before unset: 2, after unset: 23Before unset: 3, after unset: 23
Example 3:-
<?php
$var = 30;
echo $var;
unset($var);
echo $var;
?>
Output :- 30
SARASWATI ZEROX & PRINT PH-02765-222990
strval: Get string value of a variable or Converts a value to a string.
Descriptionstring 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).
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 requiredprint $string . $double; // Displays: I am a string 2.2
Parametersvar
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
SARASWATI ZEROX & PRINT PH-02765-222990
<?php$value = 1.223;print strval ($value);?>
floatval: Get float value of a variable
Descriptionfloat floatval ($var )
Gets the float value of var.
Parametersvar
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
Descriptionint intval ($var)
SARASWATI ZEROX & PRINT PH-02765-222990
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.
Parametersvar
The scalar value being converted to an integer
base
The base for the conversion
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:-
<?phpecho intval(45.67);echo "<br>";echo intval(-67.45);?>
Output :45-67
SARASWATI ZEROX & PRINT PH-02765-222990
print_r:This function display information about variable.
Return Type :- bool
Descriptionmixed 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.
Parametersexpression
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);?>
SARASWATI ZEROX & PRINT PH-02765-222990
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:
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
Descriptionstring chr ( int $ascii )
Returns a one-character string containing the character specified by ascii.
This function complements ord().
SARASWATI ZEROX & PRINT PH-02765-222990
Parametersascii
The ascii code.
Return Values
Returns the specified character.
Example: chr() example
<?php$str = "The string ends in escape: ";$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
Descriptionint ord ( string $string )
Returns the ASCII value of the first character of string.
This function complements chr().
Parametersstring
A character.
Return Values
Returns the ASCII value as an integer.
Example: ord() example
<?php
SARASWATI ZEROX & PRINT PH-02765-222990
$str="A";
$a=ord($str);
echo $a;
?>
strtolower — Make a string lowercase
Descriptionstring strtolower ( string $str )
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
Parametersstr
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
Descriptionstring strtoupper ( string $string )
Returns string with all alphabetic characters converted to uppercase.
SARASWATI ZEROX & PRINT PH-02765-222990
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.
Parametersstring
The input string.
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 IT SO?>
strlen — Get string length
Descriptionint strlen ( string $string )
Returns the length of the given string
Parametersstring
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
SARASWATI ZEROX & PRINT PH-02765-222990
$str = ' ab cd ';echo strlen($str); // 7?>
ltrim — Strip whitespace (or other characters) from the beginning of a string
Descriptionstring ltrim ( string $str [, string $charlist ] )
Strip whitespace (or other characters) from the beginning of a string.
Parametersstr
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 :) ... ";
SARASWATI ZEROX & PRINT PH-02765-222990
$binary = "\x09Example string\x0A";$hello = "Hello World";var_dump($text, $binary, $hello);
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 — Strip whitespace (or other characters) from the end of a string
Descriptionstring rtrim ( string $str [, string $charlist ] )
This function returns a string with whitespace stripped from the end of str.
SARASWATI ZEROX & PRINT PH-02765-222990
Without the second parameter, rtrim() 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.
Parametersstr
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);
SARASWATI ZEROX & PRINT PH-02765-222990
$trimmed = rtrim($text, " \t.");var_dump($trimmed);
$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
Descriptionstring trim ( string $str [, string $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.
SARASWATI ZEROX & PRINT PH-02765-222990
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
Parametersstr
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);
SARASWATI ZEROX & PRINT PH-02765-222990
// trim the ASCII control characters at the beginning and end of $binary// (from 0 to 31 inclusive)$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()
<?phpfunction 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"
SARASWATI ZEROX & PRINT PH-02765-222990
[1]=> string(7) "banana " [2]=> string(11) " cranberry "}array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(9) "cranberry"}
substr — Return part of a string
Descriptionstring substr ( string $string , int $start [, int $length ] )
Returns the portion of string specified by the start and length parameters.
Parametersstring
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 start characters long, FALSE will be returned.
length
SARASWATI ZEROX & PRINT PH-02765-222990
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 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 FALSE on failure or an 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 = substr("abcdef", 0, -1); // returns "abcde"$rest = substr("abcdef", 2, -1); // returns "cde"$rest = substr("abcdef", 4, -4); // returns false$rest = substr("abcdef", -3, -1); // returns "de"?>
strcmp — Binary safe string comparison
SARASWATI ZEROX & PRINT PH-02765-222990
Descriptionint strcmp ( string $str1 , string $str2 )
Note that this comparison is case sensitive.
<?php$str1 = 'a';$str2 = 'b';var_dump(strcmp($str1, $str2)); //int(-1)?>
strcasecmp — Binary safe case-insensitive string comparison
Descriptionint strcasecmp ( string $str1 , string $str2 )
Binary safe case-insensitive string comparison.
Return Values
Returns < 0 if str1 is less than str2; > 0 if str1 is greater 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';}?>
strpos — Find position of first occurrence of a string
Descriptionint strpos ( string $haystack , $needle [, int $offset = 0 ] )
SARASWATI ZEROX & PRINT PH-02765-222990
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.
Parametershaystack
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 needle is not found, 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 expected// because the position of 'a' was the 0th (first) character.if ($pos === false) { echo "The string '$findme' was not found in the string '$mystring'";} else { echo "The string '$findme' was found in the string '$mystring'"; echo " and exists at position $pos";}?>
SARASWATI ZEROX & PRINT PH-02765-222990
Example: Using !==
<?php$mystring = 'abc';$findme = 'a';$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) evaluates // to false.if ($pos !== false) { echo "The string '$findme' was found in the string '$mystring'"; echo " and exists at position $pos";} else { echo "The string '$findme' was not found in the string '$mystring'";}?>
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
Descriptionint strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
Returns the numeric position of the last occurrence of needle in the haystack string.
Parametershaystack
The string to search 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 FALSE if 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 five positions // from the end. Result: int(17)
var_dump(strrpos($foo, '7', 20)); // Starts searching 20 positions into the // string. Result: int(27)
SARASWATI ZEROX & PRINT PH-02765-222990
var_dump(strrpos($foo, '7', 28)); // Result: bool(false)?>
strstr — Find first occurrence of a string
Descriptionstring strstr ( string $haystack , $needle [, bool $before_needle = false ] )
Returns part of haystack string from the first occurrence of needle to the end of haystack.
Note:
This function is case-sensitive. For case-insensitive searches, use stristr().
Parametershaystack
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 haystack before the first occurrence of the needle.
Return Values
Returns the portion of string, or FALSE if needle is not found.
Example: strstr() example
<?php$email = '[email protected]';$domain = strstr($email, '@');echo $domain; // prints @example.com
SARASWATI ZEROX & PRINT PH-02765-222990
$user = strstr($email, '@', true); // As of PHP 5.3.0echo $user; // prints name?>
stristr — Case-insensitive strstr()
Descriptionstring stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
Returns all of haystack from the first occurrence of needle to the end.
Parametershaystack
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 haystack before the first occurrence of the needle.
needle and haystack are examined in a case-insensitive manner.
Return Values
Returns the matched substring. If needle is not found, returns FALSE.
Example: stristr() example
<?php $email = '[email protected]'; echo stristr($email, 'e'); // outputs [email protected] echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US?>
Example: Testing if a string is found or not
SARASWATI ZEROX & PRINT PH-02765-222990
<?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 replace are arrays, their elements are processed first to last.
search
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
replace
SARASWATI ZEROX & PRINT PH-02765-222990
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='%body%'>");
// Provides: Hll Wrld f PHP$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// Provides: You should eat pizza, beer, and ice cream every day$phrase = "You should eat fruits, vegetables, and fiber every day.";$healthy = array("fruits", "vegetables", "fiber");$yummy = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// Provides: 2$str = str_replace("ll", "", "good golly miss molly!", $count);
SARASWATI ZEROX & PRINT PH-02765-222990
echo $count;?>
strrev — Reverse a string
Descriptionstring strrev ( string $string )
Returns string, reversed.
Parametersstring
The string to be reversed.
Return Values
Returns the reversed string.
Example: Reversing a string with strrev()
<?phpecho strrev("Hello world!"); // outputs "!dlrow olleH"?>
echo — Output one or more strings
Descriptionvoid 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
SARASWATI ZEROX & PRINT PH-02765-222990
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.
Parametersarg1
The parameter to output.
Return Values
No value is returned.
print — Output a string
Descriptionint print ( string $arg )
Outputs arg.
print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.
Parametersarg
The input data.
Return Values
Returns 1, always.
SARASWATI ZEROX & PRINT PH-02765-222990
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 number.
Parametersnumber
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)?>
ceil — Round fractions up
Descriptionfceil ( $value )
Returns the next highest integer value by rounding up value if necessary.
Parametersvalue
The value to round
SARASWATI ZEROX & PRINT PH-02765-222990
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
<?phpecho ceil(4.3); // 5echo ceil(9.999); // 10echo ceil(-3.14); // -3?>
floor — Round fractions down
Description floor ($value )
Returns the next lowest integer value by rounding down value if necessary.
Parametersvalue
The numeric value to round
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
<?phpecho floor(4.3); // 4echo floor(9.999); // 9echo floor(-3.14); // -4?>
round — Rounds a float
SARASWATI ZEROX & PRINT PH-02765-222990
Description round ( $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
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
Parametersval
The value to round
precision
The optional number of decimal digits to round to.
mode
One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.
Return Values
The rounded value
Example: round() examples
<?phpecho round(3.4); // 3echo round(3.5); // 4echo round(3.6); // 4echo round(3.6, 0); // 4echo round(1.95583, 2); // 1.96echo round(1241757, -3); // 1242000echo round(5.045, 2); // 5.05echo round(5.055, 2); // 5.06?>
SARASWATI ZEROX & PRINT PH-02765-222990
Example: mode examples
<?phpecho round(9.5, 0, PHP_ROUND_HALF_UP); // 10echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8echo round(8.5, 0, 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.
Parametersx
The dividend
y
The divisor
Return Values
The floating point remainder of x/y
Example: Using fmod()
<?php$x = 5.7;
SARASWATI ZEROX & PRINT PH-02765-222990
$y = 1.3;$r = fmod($x, $y);// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7?>
min — Find lowest value
Descriptionmin ( $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.
Parametersvalues
An array containing the values.
Return Values
min() returns the numerically lowest of the parameter values.
Example: Example uses of min()
<?phpecho min(2, 3, 1, 6, 7); // 1echo min(array(2, 4, 5)); // 2
echo min(0, 'hello'); // 0echo min('hello', 0); // helloecho min('hello', -1); // -1
SARASWATI ZEROX & PRINT PH-02765-222990
// 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
Descriptionmax ( $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.
Parametersvalues
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.
SARASWATI ZEROX & PRINT PH-02765-222990
When given a string it will be cast as an integer when comparing.
Example: Example uses of max()
<?phpecho max(1, 3, 5, 6, 7); // 7echo max(array(2, 4, 5)); // 5
// When 'hello' is cast as integer it will be 0. Both the parameters are equally// long, so the order they are given in determines the resultecho max(0, 'hello'); // 0echo 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 longest$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$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
Description pow ( $base , $exp )
Returns base raised to the power of exp.
SARASWATI ZEROX & PRINT PH-02765-222990
Parametersbase
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); // 1echo pow(0, 0); // 1
echo pow(-1, 5.5); // PHP >4.0.6 NANecho pow(-1, 5.5); // PHP <=4.0.6 1.#IND?>
sqrt — Square root
Descriptionsqrt ( $arg )
Returns the square root of arg.
Parametersarg
SARASWATI ZEROX & PRINT PH-02765-222990
The argument to process
Return Values
The square root of arg or the special value NAN for negative numbers.
Example: sqrt() example
<?php// Precision depends on your precision directiveecho sqrt(9); // 3echo sqrt(10); // 3.16227766 ...?>
rand — Generate a random integer
Descriptionrand ( $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).
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. Parametersmin
The lowest value to return (default: 0)
max
The highest value to return (default: getrandmax())
Return Values
A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).
Example: rand() example
SARASWATI ZEROX & PRINT PH-02765-222990
<?phpecho rand() . "\n";echo rand() . "\n";
echo rand(5, 15);?>
The above example will output something similar to:
77712226411
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.
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 Required. Specifies the format of the timestamp
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)
SARASWATI ZEROX & PRINT PH-02765-222990
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:
<?phpecho 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/112009.05.112009-05-11
PHP Date() - Adding a Timestamp
The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used.
The mktime() function returns the Unix timestamp for a date.
The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
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
SARASWATI ZEROX & PRINT PH-02765-222990
[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 Descriptiontimestamp Optional. Specifies the time in Unix time format
Example 1
<?phpprint_r(getdate());?>
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)
SARASWATI ZEROX & PRINT PH-02765-222990
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
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
Parametersobject
Procedural style only: A DateTime object returned by date_create(). The function modifies this object.
year
Year of the date.
month
SARASWATI ZEROX & PRINT PH-02765-222990
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
Changelog
Version Description
5.3.0 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');?>
SARASWATI ZEROX & PRINT PH-02765-222990
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";
$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-282001-03-012002-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)
SARASWATI ZEROX & PRINT PH-02765-222990
Parameter Descriptionmonth Required. Specifies the monthday Required. Specifies the dayyear Required. Specifies the year
Example
<?phpvar_dump(checkdate(12,31,2000));var_dump(checkdate(2,29,2003));var_dump(checkdate(2,29,2004));?>
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 Descriptionvoid Optional.
Tips and Notes
Note: Calling this function is identical to calling mktime() with no parameters, or calling date("U").
Example
<?php$t=time();
SARASWATI ZEROX & PRINT PH-02765-222990
echo($t . "<br />");echo(date("D F d Y",$t));?>
The output of the code above could be:
1138618081Mon January 30 2006
The mktime() function returns the Unix timestamp for a date.
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 Descriptionhour Optional. Specifies the hourminute Optional. Specifies the minutesecond Optional. Specifies the second
SARASWATI ZEROX & PRINT PH-02765-222990
month Optional. Specifies the numerical monthday Optional. Specifies the dayyear 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
is_dst 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 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:
<?phpecho(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-2002Feb-01-2002Jan-01-2001Jan-01-1999
3.5 Array Function : count, list, in_array, current, next, previous,end, each, sort, array_merge, array_reverse
SARASWATI ZEROX & PRINT PH-02765-222990
The count() function counts the elements of an array, or the properties of an object.
Syntax
count(array,mode)
Parameter Descriptionarray Required. Specifies the array or object to count.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
SARASWATI ZEROX & PRINT PH-02765-222990
The list() function is used to assign values to a list of variables in one operation.
Syntax
list(var1,var2...)
Parameter Descriptionvar1 Required. The first variable to assign a value tovar2 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:
SARASWATI ZEROX & PRINT PH-02765-222990
Here I only use the Dog and Horse variables.
The in_array() function searches an array for a specific value.
This function returns TRUE if the value is found in the array, or FALSE otherwise.
Syntax
in_array(search,array,type)
Parameter Descriptionsearch Required. Specifies the what to search forarray Required. Specifies the array to searchtype 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
SARASWATI ZEROX & PRINT PH-02765-222990
Example 2
<?php$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.
SARASWATI ZEROX & PRINT PH-02765-222990
Syntax
current(array)
Parameter Descriptionarray 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 Descriptionarray Required. Specifies the array to use
SARASWATI ZEROX & PRINT PH-02765-222990
Tips and Notes
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:
PeterJoe
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 Descriptionarray Required. Specifies the array to use
Tips and Notes
Note: This function returns FALSE on empty elements or elements with no
SARASWATI ZEROX & PRINT PH-02765-222990
value.
Example
<?php$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br />";echo next($people) . "<br />";echo prev($people);?>
The output of the code above will be:
PeterJoePeter
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 Descriptionarray Required. Specifies the array to use
Example
<?php$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br />";echo end($people);
SARASWATI ZEROX & PRINT PH-02765-222990
?>
The output of the code above will be:
PeterCleveland
The each() function returns the current element key and 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 Descriptionarray 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 )
SARASWATI ZEROX & PRINT PH-02765-222990
Example 2
Same example as above, but with a loop to output the whole array:
<?php$people = array("Peter", "Joe", "Glenn", "Cleveland");
reset($people);
while (list($key, $val) = each($people)) { echo "$key => $val<br />"; }?>
The output of the code above will be:
0 => Peter1 => Joe2 => Glenn3 => Cleveland
The sort() function sorts an array by the values.
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 Descriptionarray Required. Specifies the array to sortsorttype Optional. Specifies how to sort the array values. Possible
values: SORT_REGULAR - Default. Treat values as they are (don't
change types)
SARASWATI ZEROX & PRINT PH-02765-222990
SORT_NUMERIC - Treat values numerically
SORT_STRING - Treat values as strings
SORT_LOCALE_STRING - Treat values as strings, based on local settings
Example
<?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.
Syntaxarray_merge(array1,array2,array3...)
Parameter Descriptionarray1 Required. Specifies an arrayarray2 Optional. Specifies an arrayarray3 Optional. Specifies an array
Tips and Notes
Tip: You can assign one array to the function, or as many as you like.
SARASWATI ZEROX & PRINT PH-02765-222990
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)
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
SARASWATI ZEROX & PRINT PH-02765-222990
array Required. Specifies an arraypreserve Optional. Possible values:
true false
Specifies if the function should preserve the 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 Descriptionfilename Required. Specifies the file or URL to openmode 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)
SARASWATI ZEROX & PRINT PH-02765-222990
"w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)
"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_path Optional. 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 = fopen("test.txt","r");$file = fopen("/home/test/test.txt","r");$file = fopen("/home/test/test.gif","wb");$file = fopen("http://www.example.com/","r");$file = fopen("ftp://user:[email protected]/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 Descriptionfile Required. Specifies the open file to read fromlength 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 Descriptionfile Required. Specifies the open file to write tostring Required. Specifies the string to write to the open filelength 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.
This function returns TRUE on success or FALSE on failure.
Syntax
SARASWATI ZEROX & PRINT PH-02765-222990
fclose(file)
Parameter Descriptionfile Required. Specifies the file to close
Example
<?php$file = fopen("test.txt","r");//some code to be executedfclose($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 TagWhen 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 formaction 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
<textarea>
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>
The <textarea> tag defines a multi-line text input 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.
<label> Defines a label for an input element
<form> <label for="male">Male</label> <input type="radio" name="sex" id="male" /> <br /> <label for="female">Female</label> <input type="radio" name="sex" id="female" />
SARASWATI ZEROX & PRINT PH-02765-222990
</form>
<fieldset>
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></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.
<legend>
Defines a caption for a fieldset element
<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></form>
The <legend> tag defines a caption for the fieldset element.
<select> Defines a select list (drop-down list)
<select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option>
SARASWATI ZEROX & PRINT PH-02765-222990
<option value="audi">Audi</option></select>
The <select> tag is used to create a select list (drop-down list).
The <option> tags inside the select element define the available options in the list.
<optgroup>
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"> <option value="mercedes">Mercedes</option> <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.
<option>
Defines an option in a select list
<select> <option>Volvo</option> <option>Saab</option> <option>Mercedes</option> <option>Audi</option></select>
The <option> tag defines an option in a select list.
The option element goes inside the select element.
<button> Defines a push button
SARASWATI ZEROX & PRINT PH-02765-222990
<button type="button">Click Me!</button>
The <button> tag defines a push 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 FunctionThe 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?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):
SARASWATI ZEROX & PRINT PH-02765-222990
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" />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
SARASWATI ZEROX & PRINT PH-02765-222990
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.
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.
Example 1:- Full code of HTML Tag. <html><head><title>test1</title></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
SARASWATI ZEROX & PRINT PH-02765-222990
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.
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>
SARASWATI ZEROX & PRINT PH-02765-222990
<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:
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>
SARASWATI ZEROX & PRINT PH-02765-222990
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 buttonsIf 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:
SARASWATI ZEROX & PRINT PH-02765-222990
<?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']); 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($input, $opts) Tests if input
is a number. Can also check if numeric
SARASWATI ZEROX & PRINT PH-02765-222990
input falls within a specific range.
email($input)Tests if input is a valid e-mail address.
string($input, $opts) Tests if input
is a string. Can also check if string conforms to a specific pattern or falls within a specific character limit.
uri($input)Tests if input is a valid URL.
date($input, $opts) Tests if 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
SARASWATI ZEROX & PRINT PH-02765-222990
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?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
Descriptionarray_push ( $array , $var)
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.
SARASWATI ZEROX & PRINT PH-02765-222990
Parametersarray
The input array.
var
The pushed value.
Return Values
Returns the new number of elements in the array.
Example: array_push() example
<?php$stack = array("orange", "banana");array_push($stack, "apple", "raspberry");print_r($stack);?>
The above example will output:
Array( [0] => orange [1] => banana [2] => apple [3] => 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>
SARASWATI ZEROX & PRINT PH-02765-222990
<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 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']
SARASWATI ZEROX & PRINT PH-02765-222990
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'], $_POST['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']; } 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 messagePlease fill in the form aboveis 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
SARASWATI ZEROX & PRINT PH-02765-222990
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 non-required 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(); } // 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'];
SARASWATI ZEROX & PRINT PH-02765-222990
} } 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:
<?php // check all our variables are set if(checkSet() != FALSE)
SARASWATI ZEROX & PRINT PH-02765-222990
{ // 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($_
SARASWATI ZEROX & PRINT PH-02765-222990
POST['userZip'], 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>'; }?>
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”>
SARASWATI ZEROX & PRINT PH-02765-222990
<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”;
}
else
echo “valid”;
?>
4.6 Passing variables between pages4.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:
Syntaxhttp://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 name-value pairs and use them to determine its response.
SARASWATI ZEROX & PRINT PH-02765-222990
The HTML page below shows an example of how these name-value 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></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
SARASWATI ZEROX & PRINT PH-02765-222990
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 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.
SARASWATI ZEROX & PRINT PH-02765-222990
Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?phpsession_start();// store session data$_SESSION['views']=1;?>
<html><body>
<?php//retrieve session dataecho "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:
<?phpsession_start();if(isset($_SESSION['views']))$_SESSION['views']=$_SESSION['views']+1;else$_SESSION['views']=1;echo "Views=". $_SESSION['views'];?>
Destroying a Session
SARASWATI ZEROX & PRINT PH-02765-222990
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:
<?phpunset($_SESSION['views']);?>
You can also completely destroy the session by calling the session_destroy() function:
<?phpsession_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:
SARASWATI ZEROX & PRINT PH-02765-222990
<?phpsetcookie("user", "Alex Porter", time()+3600);?>
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 cookieecho $_COOKIE["user"];
// A way to view all cookiesprint_r($_COOKIE);?>
In the following example we use the isset() function to find out if a cookie has been set:
<html>
SARASWATI ZEROX & PRINT PH-02765-222990
<body>
<?phpif (isset($_COOKIE["user"])) 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 agosetcookie("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">
SARASWATI ZEROX & PRINT PH-02765-222990
Name: <input type="text" name="name" />Age: <input type="text" name="age" /><input type="submit" /></form>
</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">
SARASWATI ZEROX & PRINT PH-02765-222990
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
SARASWATI ZEROX & PRINT PH-02765-222990