Vous êtes sur la page 1sur 238

What is PHP

PHP is a scripting language that is often embedded into


HTML to add functions HTML alone can't do. PHP allows
you to collect, process and utilize data to create a desired
output. In short, it let's you interact with your pages.
PHP is able to preform a number of tasks including
printing data, making numeric calculations (such as
addition or multiplication), making comparisons (which is
bigger, are they equal, etc) and making
simplebooleanchoices.
PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to
competitors such as Microsoft's ASP.

What is PHP
PHP was originally an abbreviation
of Personal Home Page (tools). The
language was initially developed by
Rasmas Lerdorf.

What is MySQL
MySQL is a relational database system that is used to
store information. MySQL can store many types of data
from something as tiny as a single character to as large
as complete files or graphics. Although it can be accessed
by most programing languages, it is often coupled with
PHP because they work together with ease. Information
stored in a MySQL database hosted on a web server can
be accessed from anywhere in the world with a computer.
This makes it a good way to store information that needs
the ability to change over time, but also needs to be
accessed over the net. Some examples that can utilize
MySQL are a web message board or a customer's shipping
status.

Why use PHP and MySQL?


PHP and MySQL combine to be an easy yet powerful way
to create dynamic web pages that actually interact with
your visitors. HTML can create useful and well formatted
web pages. With the addition of PHP and MySQL you can
collect data from your users, create specific content on
the fly, and do many other things that HTML alone can't
do.The beauty of PHP as a language is that it is designed
to be used along with HTML.
You can use PHP right inside your already existing HTML
content, or put HTML tags right inside your PHP coding.
When learning PHP you are not making your existing
HTML knowledge obsolete, you are instead adding to it to
give it more functions and abilities

Servers and Clients and the PHP preprocessor


communications

Server Side Scripting


Definition:Server side scripting means that all of the
code is executed on the server before the data is passed
to the user's browser. In the case of PHP this means that
no PHP code ever reaches the user, it is instead
executed and only the information it outputs is sent to
the web browser.
One way to see this in action is to open one of your PHP
pages in a web browser and then choose the 'View
Source' option.
You will not see any PHP code; you will only see what the
PHP has outputted because all of the code was executed
on the server before it was delivered to the browser.
Examples:

<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>

What is PHP?
PHP is an acronym for "PHP:
Hypertext Preprocessor"
PHP is a widely-used, open source
scripting language
PHP scripts are executed on the
server
PHP is free to download and use

PHP is an amazing and popular language!


It is powerful enough to be at the core of the
biggest blogging system on the web (WordPress)!
It is deep enough to run the largest social
network (Facebook)!
It is also easy enough to be a beginner's first
server side language!

What is a PHP File?


PHP files can contain text, HTML,
CSS, JavaScript, and PHP code
PHP code are executed on the server,
and the result is returned to the
browser as plain HTML
PHP files have extension ".php"

What Can PHP Do?


PHP can generate dynamic page content
PHP can create, open, read, write, delete, and close
files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML. You can
output images, PDF files, and even Flash movies. You
can also output any text, such as XHTML and XML.

Why PHP?
PHP runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP
resource:www.php.net
PHP is easy to learn and runs efficiently on the
server side

What Do I Need?
To start using PHP, you can:
Find a web host with PHP and MySQL
support
Install a web server on your own PC,
and then install PHP and MySQL

Use a Web Host With PHP Support


If your server has activated support for
PHP you do not need to do anything.
Just create some .php files, place them
in your web directory, and the server
will automatically parse them for you.
You do not need to compile anything or
install any extra tools.
Because PHP is free, most web hosts
offer PHP support.

Set Up PHP on Your Own PC


However, if your server does not support
PHP, you must:
install a web server
install PHP
install a database, such as MySQL
The official PHP website (PHP.net) has
installation instructions for PHP:http://
php.net/manual/en/install.php

PHP 5Syntax
A PHP script is executed on the
server, and the plain HTML result is
sent back to the browser.
Basic PHP Syntax
A PHP script can be placed anywhere
in the document.
A PHP script starts with<?phpand
ends with?>:

<?php
// PHP code goes here
?>
The default file extension for PHP
files is ".php".
A PHP file normally contains HTML
tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text "Hello World!" on a
web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Note:PHP statements end with a semicolon (;).

Comments in PHP
A comment in PHP code is a line that is not
read/executed as part of the program. Its only
purpose is to be read by someone who is looking at
the code.
Comments can be used to:
Let others understand what you are doing
Remind yourself of what you did - Most
programmers have experienced coming back to
their own work a year or two later and having to refigure out what they did. Comments can remind you
of what you were thinking when you wrote the code

PHP supports several ways of commenting:


Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>

PHP Case Sensitivity


In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-sensitive.
In the example below, all three echo statements below are
legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
However; all variable names are case-sensitive.

In the example below, only the first statement will display the value of
the $color variable (this is because $color, $COLOR, and $coLOR are
treated as three different variables):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>

Variables are "containers" for storing


information.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed
by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

After the execution of the statements above,


the variable$txtwill hold the value Hello
world!, the variable$xwill hold the value5,
and the variable$ywill hold the value10.5.
Note:When you assign a text value to a
variable, put quotes around the value.
Note:Unlike other programming languages,
PHP has no command for declaring a
variable. It is created the moment you first
assign a value to it.

PHP Variables
A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name
of the variable
A variable name must start with a letter or the
underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are
two different variables)
Remember that PHP variable names are casesensitive!

Output Variables
The PHP echo statement is often used to
output data to the screen.
The following example will show how to
output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>

Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>

The following example will output the


sum of two variables:
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

Destroying Variables

To destroy a variable, pass the variable to PHPs aptly


named unset() function, as in the
following example:
<?php
// assign value to variable
$car = 'Porsche';
// print variable value
// output: 'Before unset(), my car is a Porsche'
echo "Before unset(), my car is a $car";
// destroy variable
unset($car);
// print variable value
// this will generate an 'undefined variable' error
// output: 'After unset(), my car is a '
echo "After unset(), my car is a $car";
?>

PHP is a Loosely Typed Language


In the example above, notice that we did 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 other languages such as C, C++, and Java,
the programmer must declare the name and
type of the variable before using it.

PHP 5Constants
Constants are like variables except that once
they are defined they cannot be changed or
undefined.
A constant is an identifier (name) for a simple
value. The value cannot be changed during the
script.
A valid constant name starts with a letter or
underscore (no $ sign before the constant
name).
Note:Unlike variables, constants are
automatically global across the entire script.

Create a PHP Constant


To create a constant, use the define()
function.
Syntax
define(name,value,case-insensitive)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the
constant name should be case-insensitive.
Default is false

The example below creates a constant


with acase-sensitivename:
Example
<?php
define("GREETING", "Welcome to
W3Schools.com!");
echo GREETING;
?>
Output :Welcome to W3Schools.com!

The example below creates a constant


with acase-insensitivename:
Example
<?php
define("GREETING", "Welcome to
W3Schools.com!", true);
echo greeting;
?>
Output : Welcome to W3Schools.com!

Constants are Global


Constants are automatically global and can be used across the
entire script.
The example below uses a constant inside a function, even if it is
defined outside the function:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING;
}

myTest();
?>
Output :Welcome to W3Schools.com!

PHP - Functions
PHP functions are similar to other programming
languages. A function is a piece of code which
takes one more input in the form of parameter and
does some processing and returns a value.
You already have seen many functions
likefopen()andfread()etc. They are built-in
functions but PHP gives you option to create your
own functions as well.
There are two parts which should be clear to you
Creating a PHP Function
Calling a PHP Function

Creating PHP Function


Its very easy to create your own PHP function.
Suppose you want to create a PHP function
which will simply write a simple message on
your browser when you will call it. Following
example creates a function called
writeMessage() and then calls it just after
creating it.
Note that while creating a function its name
should start with keywordfunction and all the
PHP code should be put inside { and } braces
as shown in the following example below

<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result
You are really a nice person, Have a nice time!

PHP Functions with Parameters


PHP gives you option to pass your
parameters inside a function. You can
pass as many as parameters your
like. These parameters work like
variables inside your function.
Following example takes two integer
parameters and add them together
and then print them.

<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result
Sum of the two numbers is : 30

Passing Arguments by Reference


It is possible to pass arguments to functions
by reference. This means that a reference to
the variable is manipulated by the function
rather than a copy of the variable's value.
Any changes made to an argument in these
cases will change the value of the original
variable. You can pass an argument by
reference by adding an ampersand to the
variable name in either the function call or
the function definition.

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>

This will display following result


Original Value is 10
Original Value is 16

PHP Functions returning value


A function can return a value using
thereturnstatement in conjunction with a
value or object. return stops the execution of
the function and sends the value back to the
calling code.
You can return more than one value from a
function usingreturn array(1,2,3,4).
Following example takes two integer
parameters and add them together and then
returns their sum to the calling program. Note
thatreturnkeyword is used to return a value
from a function.

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function :
$return_value";
?>
</body>
</html>
This will display following result
Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a


default value if the function's caller
doesn't pass it.
Following function prints NULL in
case use does not pass any value to
this function.

<html>
<head>
<title>Writing PHP Function which returns
value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result
This is test

Dynamic Function Calls


It is possible to assign function
names as strings to variables and
then treat these variables exactly as
you would the function name itself.
Following example depicts this
behaviour.

<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
This will display following result
Hello

PHP Variables Scope


In PHP, variables can be declared
anywhere in the script.
The scope of a variable is the part of the
script where the variable can be
referenced/used.
PHP has three different variable scopes:
local
global
static

Global and Local Scope


A variable declaredoutsidea function has a GLOBAL
SCOPE and can only be accessed outside a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>

A variable declaredwithina function has a LOCAL


SCOPE and can only be accessed within that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

<?php
//globalscope
$x=10;
functionvar_scope()
{
//localscope
$y=20;
echo"Thevalueofxis:$x"."<br/>";
echo"Thevalueofyis:$y"."<br/>";
}
var_scope();
echo"Thevalueofxis:$x"."<br/>";
echo"Thevalueofyis:$y";
?>

The
The
The
The

value
value
value
value

of
of
of
of

x
y
x
y

is
is
is
is

:
: 20
: 10
:

You can have local variables with the


same name in different functions,
because local variables are only
recognized by the function in which
they are declared.

PHP The global Keyword


The global keyword is used to access a global variable from
within a function.
To do this, use the global keyword before the variables (inside
the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called


$GLOBALS[index]. Theindexholds the name of the variable.
This array is also accessible from within functions and can be
used to update global variables directly.
The example above can be rewritten like this:
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>

PHP The static Keyword


Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local
variable NOT to be deleted. We need it for a further job.
To do this, use thestatickeyword when you first declare the
variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
Then, each time the function is called, that variable will still have
the information it contained from the last time the function was
called.
Note:The variable is still local to the function.

Example : without static variable


<?php
functiontest_variable()
{
$x=1;
echo$x;
$x++;
}
test_variable();
echo"<br>";
test_variable();
echo"<br>";
test_variable();
?>

Example : with static variable


<?php
functiontest_count()
{
static$x=1;
echo$x;
$x++;
}
test_count();
echo"<br>";
test_count();
echo"<br>";
test_count();
?>

PHP 5echo and print Statements


In PHP there are two basic ways to get output: echo and print.
In this tutorial we use echo (and print) in almost every
example. So, this chapter contains a little more info about
those two output statements.
PHP echo and print Statements
echo and print are more or less the same. They are both used
to output data to the screen.
The differences are small: echo has no return value while print
has a return value of 1 so it can be used in expressions. echo
can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster
than print.

PHP Data Types


Variables can store data of different types, and
different data types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource

PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use
single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

PHP Integer
An integer data type is a non-decimal number
between -2,147,483,648 and 2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats:
decimal (10-based), hexadecimal (16-based prefixed with 0x) or octal (8-based - prefixed
with 0)

In the following example $x is an integer. The


PHP var_dump() function returns the data type
and value:
The var_dump() function is used to display
structured information (type and value) about
one or more variables.
Example
<?php
$x = 5985;
var_dump($x);
?>

PHP Float
A float (floating point number) is a number with
a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP
var_dump() function returns the data type and
value:
Example
<?php
$x = 10.365;
var_dump($x);
?>

PHP Boolean
A Boolean represents two possible
states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in
conditional testing.

Booleans is the easiest type. It can be either TRUE


or FALSE. It is used in control structurelike the
testing portion of an if statement.
<?php
$height=100;
$width=50;
if($width==0)
{
echo"Thewidthneedstobeanon-zeronumber";
}
?>

<?php
$height=100;
$width=50;
if($width)
{
echo"Theareaoftherectangleis".$height*$width;
}
else
{
echo"Thewidthneedstobeanon-zeronumber";
}
?>
In this example no comparison operator is used. But PHP
automatically converted $width value50 to its Boolean
equivalent true and calculate the area of the rectangle
i.e. execute the commands inside the if() statement.

PHP Object
An object is a data type which stores data and information on how to
process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class
keyword. A class is a structure that can contain properties and
methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>

PHP NULL Value


Null is a special data type which can
have only one value: NULL.
A variable of data type NULL is a
variable that has no value assigned to it.
Tip:If a variable is created without a
value, it is automatically assigned a
value of NULL.
Variables can also be emptied by setting
the value to NULL:

Setting and Checking Variable Data Types

Unlike other programming languages, where a


variables data type must be explicitly
defined by the programmer, PHP automatically
determines a variables data type from the
content it holds. And if the variables content
changes over the duration of a script, the
language will automatically set the variable to
the appropriate new data type.
Heres an example which illustrates this type
juggling:

<?php
// define string variable
$whoami = 'Sarah';
// output: 'string'
echo gettype($whoami);
// assign new integer value to variable
$whoami = 99.8;
// output: 'double'
echo gettype($whoami);
// destroy variable
unset($whoami);
// output: 'NULL'
echo gettype($whoami);
?>
This example introduces PHPs gettype() operator,
which is a handy little tool for finding out the type of
a particular variable.

Type Cast
its possible to explicitly set the type of a PHP
variable by casting a variable to a specific type
before using it.
Casting is a technique commonly used by Java
programmers; to use it, simply specify the
desired data type in parentheses on the right
side of the assignment equation.
Consider the following example, which
illustrates turning a floating-point value into an
integer value:

<?php
// define floating-point variable
$speed = 501.789;
// cast to integer
$newSpeed = (integer) $speed;
// output: 501
echo $newSpeed;
?>

PHP includes a number of more specialized


functions, to test if a variable is of a specific
type.
is_bool() :Tests if a variable holds a Boolean
value
is_numeric() :Tests if a variable holds a numeric
value
is_int() : Tests if a variable holds an integer
is_float() : Tests if a variable holds a floatingpoint value
is_string() :Tests if a variable holds a string value
is_null() : Tests if a variable holds a NULL value
is_array() :Tests if a variable is an array
is_object() : Tests if a variable is an object

PHP Array
An array in PHP is a collection of
key/value pairs. This means that it
maps values to keys.
Array keys (or indexes) may be either
an integers or a strings whereas
values can be any type. Example

Array() construct
An array can be declared using the array() language
construct, which generally takes the following format.
<p>array(key1=>value1,
key2=>value3,
key3=>value3,
..........)</p>
Key1, key2, key3 may be an integer or string.
value1, value2, value3 may be any value of any type.
As of PHP 5.4 a short array syntax [] is used instead
of array().

<?php
$fruits=array(
fruit1=>"Banana",
fruit2=>"Apple"
);
//declaringtheabovearrayasofPHP5.4
$fruits=[
fruit1=>"Banana",
fruit2=>"Apple"
];
?>

Indexed and Associative Arrays


In PHP there are two kind of arrays :
indexed array and associative array.
The only difference is that numeric
values are used as 'keys' in indexed
array start from zero (0) and in
associative array strings are used as
'keys'. PHP does not differentiate
between indexed and associative
arrays, therefore a PHP array may
contain strings as well as integers as

Indexed arrays with key


<?php
$fruits[0]="Banana";
$fruits[1]="Apple";
$fruits[2]="Mango";
$fruits[3]="Coconut";
var_dump($fruits);
?>
Output :
array(4) { [0]=> string(6) "Banana" [1]=> string(5)
"Apple" [2]=> string(5) "Mango" [3]=> string(7)
"Coconut" }

Indexed arrays without key


<?php
$fruits=array("Banana","Apple","Mango","Coconut");
var_dump($fruits);
?>
Output :

In PHP array key is optional. If no key is


specified, keys start from zero (0).

Example : Integer and string keys together

<?php
$fruits=array(
0=>"Banana",
"fruit1"=>"Apple",
11=>"Mango",
-34=>"Coconut",
);
var_dump($fruits);
?>

Output :

Example : Keys are not present on all elements

<?php
$fruits=array(
"Banana",
11=>"Apple",
"Mango",
"fruit1"=>"Coconut",
);
var_dump($fruits);
?>
Output :
array(4) { [0]=> string(6) "Banana" [11]=> string(5) "Apple"
[12]=> string(5) "Mango" ["fruit1"]=> string(7) "Coconut" }
In the above example the third value "Mango" is assigned the key
12 because the largest integer key before that was 11.

Storing Data in an Array


Storing a value in an array is easy, you can use any of
the following method to store date:
<?php
//StoredatathroughanIndexedarray.
$country[0]='India';
$country[1]='USA';
$country[2]='Peru';
//Storedatathroughanassociativearray.
$price['country1']='India';
$price['country2']='USA';
$price['country3']='Peru';
?>

Accessing array elements


The elements of an array can be accessed using the array[key] syntax,
see the following example.
<?php
$fruits=array(
0=>"Banana",
"fruit1"=>"Apple",
11=>"Mango",
-34=>"Coconut",
);
echo($fruits[0]);
echo($fruits["fruit1"]);
echo($fruits[11]);
echo($fruits[-34]);
?>
Output :
BananaAppleMangoCoconut

Retrieving Array Size

An important task when using arrays, especially


in combination with loops, is finding out
how many values the array contains.
This is easily accomplished with PHPs count()
function, which accepts the array variable as a
parameter and returns an integer value
indicating how many elements it contains.
Heres an example:

<?php
// define array
$data = array('Monday', 'Tuesday',
'Wednesday');
// get array size
echo 'The array has ' . count($data) . '
elements';
?>

Multidimensional Arrays
A multi-dimensional 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. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional
array to store marks of three students in three
subjects
Example

Processing Arrays with Loops and Iterators

your PHP program will need to work its


way through an array, performing an
operation or calculation on each value
it finds.
The best way to do this is with a loop,
Consider the following example, which
sets up an array and then iterates over
it using a for loop:

<?php
// define array
$cities = array('London', 'Paris', 'Madrid', 'Los
Angeles', 'Bombay', 'Jakarta');
// iterate over array
// print each value
for ($i=0; $i<count($cities); $i++) {
echo $cities[$i] . "\r\n";
}
?>

foreach
With a foreach loop, each time the loop runs, the
current array element is assigned to a temporary
variable, which can then be processed in any
way you pleaseprinted, copied to another
variable, used in a calculation, and so on.
Unlike a for loop, a foreach loop doesnt use a
counter; it automatically knows where it is in
the array, and it moves forward continuously
until it reaches the end of the array, at which
point it automatically halts.

<?php
// define array
$cities = array('London', 'Paris', 'Madrid', 'Los
Angeles', 'Bombay', 'Jakarta');
// iterate over array
// print each value
foreach ($cities as $c) {
echo "$c \r\n";
}
?>

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

PHP Resource
The special resource type is not an
actual data type. It is the storing of a
reference to functions and resources
external to PHP.
A common example of using the
resource data type is a database call.

Using String Functions


PHP has over 75 built-in string
manipulation functions, supporting
operations ranging
from string repetition and reversal to
comparison and search-and-replace

empty() Tests if a string is empty


strlen() Calculates the number of characters in a string
strrev() Reverses a string
str_repeat() Repeats a string
substr() Retrieves a section of a string
strcmp() Compares two strings
str_word_count() Calculates the number of words in a
string
str_replace() Replaces parts of a string
trim() Removes leading and trailing whitespace from a
string
strtolower() Lowercases a string
strtoupper() Uppercases a string
ucfirst() Uppercases the first character of a string
ucwords() Uppercases the first character of every word
of a string

addslashes() Escapes special characters in a string


with backslashes
stripslashes() Removes backslashes from a string
htmlentities() Encodes HTML within a string
htmlspecialchars() Encodes special HTML
characters within a string
nl2br() Replaces line breaks in a string with <br/>
elements
html_entity_decode() Decodes HTML entities within
a string
htmlspecialchars_decode() Decodes special HTML
characters within a string
strip_tags() Removes PHP and HTML code from a
string

PHP 5Strings
A string is a sequence of characters, like "Hello world!".
Reversing and Repeating Strings
The strlen() function returns the number of characters
in a string. Heres an example
of it in action:
<?php
// calculate length of string
// output: 17
$str = 'Welcome to Xanadu';
echo strlen($str);
?>

Reversing a string is as simple as calling


the strrev() function, as in the next
listing:
<?php
// reverse string
// output: 'pets llams enO'
$str = 'One small step';
echo strrev($str);
?>

In case you need to repeat a string, PHP offers the


str_repeat() function, which accepts two
argumentsthe string to be repeated, and the
number of times to repeat it.
Heres an example:
<?php
// repeat string
// output: 'yoyoyo'
$str = 'yo';
echo str_repeat($str, 3);
?>

Count The Number of Words in a String

The PHP str_word_count() function


counts the number of words in a string:
Example
<?php
echo str_word_count("Hello world!"); //
outputs 2
?>
The output of the code above will be: 2.

Working with Substrings

PHP also allows you to slice a string into smaller parts with
the substr() function, which accepts three arguments: the
original string, the position (offset) at which to start
slicing, and the number of characters to return from the
starting position. The following
listing illustrates this in action:
<?php
// extract substring
// output: 'come'
$str = 'Welcome to nowhere';
echo substr($str, 3, 4);
?>
NOTE
When using the substr() function, the first character of the string is
treated as offset 0, the second character as offset 1, and so on.

Search For a Specific Text Within a String


The PHP strpos() function searches for a specific text within
a string.
If a match is found, the function returns the character
position of the first match. If no match is found, it will
return FALSE.
The example below searches for the text "world" in the
string "Hello world!":
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The output of the code above will be: 6.
Tip:The first character position in a string is 0 (not 1).

Replace Text Within a String


The PHP str_replace() function replaces some
characters with some other characters in a string.
The example below replaces the text "world" with
"Dolly":
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); //
outputs Hello Dolly!
?>
The output of the code above will be: Hello Dolly!

Comparing,
If you need to compare two strings, the strcmp()
function performs a case-sensitive comparison of
two strings, returning a negative value if the first
is less than the second, a positive value if its
the other way around, and zero if both strings are
equal. Here are some examples of how this
works:
<?php
// compare strings
$a = "hello";
$b = "hello";
$c = "hEllo";
// output: 0
echo strcmp($a, $b);
// output: 1
echo strcmp($a, $c);

Formatting Strings
PHPs trim() function can be used to remove
leading or trailing whitespace from a string;
this is quite useful when processing data
entered into a Web form. Heres an
example:
<?php
// remove leading and trailing whitespace
// output 'a b c'
$str = ' a
b
c ';
echo trim($str);
?>

Changing the case of a string is as simple as


calling the strtolower() or strtoupper() function, as
illustrated in the next listing:
<?php
// change string case
$str = 'Yabba Dabba Doo';
// output: 'yabba dabba doo'
echo strtolower($str);
// output: 'YABBA DABBA DOO'
echo strtoupper($str);
?>

You can also uppercase the first character of


a string with the ucfirst() function, or format
a string in word case with the ucwords()
function. The following listing
demonstrates both these functions:
<?php
// change string case
$str = 'the yellow brigands';
// output: 'The Yellow Brigands'
echo ucwords($str);
// output: 'The yellow brigands'
echo ucfirst($str);
?>

Working with HTML Strings

PHP also has some functions exclusively for working


with HTML strings. First up, the addslashes() function,
which automatically escapes special characters in a
string with backslashes. Heres an example:
<?php
// escape special characters
// output: 'You\'re awake, aren\'t you?'
$str = "You're awake, aren't you?";
echo addslashes($str);
?>

You can reverse the work done by addslashes()


with the aptly named stripslashes() function,
which removes all the backslashes from a string.
Consider the following example, which illustrates:
<?php
// remove slashes
// output: 'John D'Souza says "Catch you later".'
$str = "John D\'Souza says \"Catch you later\".";
echo stripslashes($str);
?>

The htmlentities() and htmlspecialchars()


functions automatically convert special
HTML symbols (like < and >) into their
corresponding HTML representations (<
and &<hairline #>gt;).
Similarly, the nl2br() function
automatically replaces newline characters
in a string with the corresponding HTML
line break tag <br />. Heres an example:

You can reverse the effect of the htmlentities()


and htmlspecialchars() functions with the
html_entity_decode() and
htmlspecialchars_decode() functions.

the strip_tags() function searches for all HTML


and PHP code within a string and removes it to
generate a clean string. Heres an example:
<?php
// strip HTML tags from string
// output: 'Please log in again'
$html = '<div width="200">Please
<strong>log in again</strong></div>';
echo strip_tags($html);
?>

PHP Operators
Operators are used to perform operations on variables
and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators

PHP Arithmetic Operators

<?php
// define variables
$x = 10;
$y = 5;
$z = 3;
// add
$sum = $x + $y;
echo "$x + $y = $sum\n";
// subtract
$diff = $x - $y;
echo "$x - $y = $diff\n";
// multiply
$product = $x * $y;
echo "$x * $y = $product\n";
// divide and get quotient
$quotient = $x / $y;
echo "$x / $y = $quotient\n";
// divide and get modulus
$modulus = $x % $y;
echo "$x % $y = $modulus\n";
?>

PHP Assignment Operators

<?php
// define variables
$count = 7;
$age = 60;
$greeting = 'We';
// subtract 2 and re-assign new value to variable
// equivalent to $count = $count - 2
// output: 5
$count -= 2;
echo $count;
// divide by 5 and re-assign new value to variable
// equivalent to $age = $age / 5
// output: 12
$age /= 5;
echo $age;
// add new string and re-assign new value to variable
// equivalent to $greeting = $greeting . 'lcome!'
// output: 'Welcome!'
$greeting .= 'lcome!';
echo $greeting;
?>

PHP Comparison Operators


The PHP comparison operators are
used to compare two values (number
or string):

<?php
// define variables
$p = 10;
$q = 11;
$r = 11.3;
$s = 11;
// test if $q is greater than $p
// returns true
echo ($q > $p);
// test if $q is less than $p
// returns false
echo ($q < $p);
// test if $q is greater than or equal to $s
// returns true
echo ($q >= $s);
// test if $r is less than or equal to $s
// returns false
echo ($r <= $s);

// test if $q is equal to $s
// returns true
echo ($q == $s);
// test if $q is equal to $r
// returns false
echo ($q == $r);
?>

PHP Increment / Decrement Operators


The PHP increment operators are used to
increment a variable's value.
The PHP decrement operators are used to
decrement a variable's value.

<?php
// define variable
$count = 19;
// increment
$count++;
// output: 20
echo $count;
// now decrement
$count--;
// output: 19
echo $count;
?>

PHP Logical Operators


The PHP logical operators are used to
combine conditional statements.

<?php
// define variables
$price = 100;
$size = 18;
// logical AND test
// returns true if both comparisons are true
// returns true here
echo ($price > 50 && $size < 25);
// logical OR test
// returns true if any of the comparisons are true
// returns false here
echo ($price > 150 || $size > 75);
// logical NOT test
// reverses the logical test
// returns false here
echo !($size > 10);
?>

PHP String Operators


PHP has two operators that are
specially designed for strings.

<?php
// define variables
$country = 'England';
$city = 'London';
// combine into single string
// output: 'Welcome to London, the coolest
city in all of England'
echo 'Welcome to ' . $city . ', the coolest city
in all of ' . $country;
?>

PHP 5if...else...elseifStatements
Conditional statements are used to perform different actions
based on different conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different
actions for different conditions. You can use conditional
statements in your code to do this.
In PHP we have the following conditional statements:
if statement- executes some code if one condition is true
if...else statement- executes some code if a condition is true
and another code if that condition is false
if...elseif....else statement- executes different codes for
more than two conditions
switch statement- selects one of many blocks of code to be
executed

PHP - The if Statement


The if statement executes some code if
one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a
good day!" if the current time (HOUR) is
less than 20:

<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>

PHP - The if...else Statement


The if....else statement executes some code
if a condition is true and another code if
that condition is false.
Syntax
if (condition){
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The example below will output "Have a good day!" if the


current time is less than 20, and "Have a good night!"
otherwise:
Example
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The if...elseif....else Statement


The if....elseif...else statement executes
different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are
false;
}

Repeating Actions with Loops


Like any good programming language, PHP
also supports loopsessentially, the ability to
repeat a series of actions until a prespecified
condition is fulfilled.
Loops are an important tool that help in
automating repetitive tasks within a program.
PHP supports four different types of loops,
three of which are discussed in the following
section

The while Loop

The easiest type of loop to understand is the while


loop, which repeats continuously while a prespecified
condition is true.
Heres an example, which uses a loop to repeatedly
print an 'x' to the output page.
<?php
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
while ($counter < 10) {
echo 'x';
$counter++;
}
?>

The do-while Loop


With a while loop, the condition to be evaluated is
tested at the beginning of each loop iteration.
Theres also a variant of this loop, the do-while
loop, which evaluates the condition at the end of
each loop iteration. Heres a revision of the
preceding example that
illustrates it in action:
<?php
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
do {
echo 'x';
$counter++;
} while ($counter < 10);
?>

The difference in behavior between a while loop


and a do-while loop has one important implication:
with a while loop, if the conditional expression
evaluates to false on the first pass itself, the loop
will never be executed.
With a do-while loop,on the other hand, the loop
will always be executed once, even if the
conditional
expression is false, because the condition is
evaluated at the end of the loop iteration
rather than the beginning.

The for Loop


The while and do-while loops are fairly simple:
they repeat for so long as the specified condition
remains true. But PHP also supports a more
sophisticated type of loop, the for loop, which is
useful when you need to execute a set of
statements a specific number of
times.
The best way to understand a for loop is by
looking at some code. Heres a simple example,
which lists the numbers between 1 and 10:

<?php
// repeat continuously until counter
becomes 10
// output:
for ($x=1; $x<10; $x++) {
echo "$x ";
}
?>

Working with Array Functions


PHP has numerous built-in array
manipulation functions, supporting
operations ranging
from array search and comparison to
sorting and conversion operations

explode() Splits a string into array elements


implode() Joins array elements into a string
range() Generates a number range as an array
min() Finds the smallest value in an array
max() Finds the largest value in an array
shuffle() Randomly rearranges the sequence of
elements in an array
array_slice() Extracts a segment of an array
array_shift() Removes an element from the beginning of
an array
array_unshift() Adds an element to the beginning of an
array

array_pop() Removes an element from the end of an array


array_push() Adds an element to the end of an array
array_unique() Removes duplicate elements from an array
array_reverse() Reverses the sequence of elements in an
array
array_merge() Combines two or more arrays
array_intersect() Calculates the common elements between
two or more arrays
array_diff() Calculates the difference between two arrays
in_array() Checks if a particular value exists in an array
array_key_exists() Checks if a particular key exists in an
array
sort() Sorts an array
asort() Sorts an associative array by value
ksort() Sorts an associative array by key
rsort() Reverse-sorts an array
krsort() Reverse-sorts an associative array by value
arsort() Reverse-sorts an associative array by key

Converting Between Strings and


Arrays
PHP lets you convert a string into an array, by
splitting the string on a user-defined separator
and assigning the resulting segments to an
array. The PHP function to accomplish this task
is the aptly named explode() function, which
accepts two argumentsthe separator and the
source stringand returns an array. Heres an
example:

<?php
// define string
$str = 'tinker,tailor,soldier,spy';
// convert string to array
// output: ('tinker', 'tailor', 'soldier,
'spy')
$arr = explode(',', $str);
print_r($arr);
?>

Its also possible to reverse the process,


joining the elements of an array into a single
string using user-supplied glue. The PHP
function for this is named implode(), and its
illustrated in the next listing:
<?php
// define array
$arr = array('one', 'two', 'three', 'four');
// convert array to string
// output: 'one and two and three and four'
$str = implode(' and ', $arr);
print_r($str);
?>

Working with Number


Ranges

If youre trying to fill an array with a range of numbers, the


range() function offers a convenient alternative to manually
entering each value. This function accepts two end
points and returns an array containing all the numbers
between those end points.
Heres an example, which generates an array containing all
the values between 1 and 1000:
<?php
// define array
$arr = range(1,1000);
print_r($arr);
?>

If you already have an array of numbers


and are trying to calculate the minimum
or maximum of the series,
PHPs min() and max() functions will
come in handythey accept an array of
numbers and return the smallest and
largest values in the array respectively.
The next listing has an example:

<?php
// define array
$arr = array(7, 36, 5, 48, 28, 90, 91,
3, 67, 42);
// get min and max
// output: 'Minimum is 3 and
maximum is 91'
echo 'Minimum is ' . min($arr) . ' and
maximum is ' . max($arr);
?>

Extracting Array Segments

PHP allows you to slice an array into smaller parts with the
array_slice() function, which accepts three arguments: the
original array, the index position (offset) at which to start
slicing, and the number of elements to return from the
starting offset. The following listing illustrates this in action:
<?php
// define array
$rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow',
'orange', 'red');
// extract 3 central values
// output: ('blue', 'green', 'yellow')
$arr = array_slice($rainbow, 2, 3);
print_r($arr);
?>

To extract a segment from the end of an


array (rather than the beginning), pass
array_slice() a negative offset, as in this
revision of the preceding example:
<?php
// define array
$rainbow = array('violet', 'indigo', 'blue',
'green', 'yellow', 'orange', 'red');
// extract 3 central values
// starting from the end
// output: ('blue', 'green', 'yellow')
$arr = array_slice($rainbow, -5, 3);
print_r($arr);
?>

Adding and Removing Array


Elements
PHP comes with four functions that allow you to add
or remove elements from the beginning or end of an
array:
the array_unshift() function adds an element to the
beginning of an array;
the array_shift() function removes the first element
of an array;
the array_push() function adds an element to the end
of an array; and
the array_pop() function removes the last element of
an array.
The following listing illustrates them all in action:

<?php
// define array
$movies = array('The Lion King', 'Cars', 'A Bug\'s
Life');
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
// output: ('The Incredibles', 'Cars', 'Ratatouille')
print_r($movies);
?>

Removing Duplicate Array Elements


PHP lets you strip an array of duplicate values with its
array_unique() function, which accepts an array and
returns a new array containing only unique values. The
next listing illustrates it in action:
<?php
// define array
$duplicates = array('a', 'b', 'a', 'c', 'e', 'd', 'e');
// remove duplicates
// output: ('a', 'b', 'c', 'e', 'd')
$uniques = array_unique($duplicates);
print_r($uniques);
?>

Randomizing and Reversing Arrays


PHPs shuffle() function re-arranges the elements of an
array in random order, while its array_reverse() function
reverses the order of an arrays elements.
The following listing illustrates:
<?php
// define array
$rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow',
'orange', 'red');
// randomize array
shuffle($rainbow);
print_r($rainbow);
// reverse array
// output: ('red', 'orange', 'yellow', 'green', 'blue',
// 'indigo', 'violet')
$arr = array_reverse($rainbow);
print_r($arr);
?>

Searching Arrays
The in_array() function looks through an array for a
specified value and returns true if found. Heres an
example, which searches the array $cities for the
string
'Barcelona':
<?php
// define array
$cities = array('London', 'Paris', 'Barcelona', 'Lisbon',
'Zurich');
// search array for value output :1
echo in_array('Barcelona', $cities);
?>

If, instead of values, youd like to search the keys of an associative


array, PHP has you covered there too: the array_key_exists()
function looks for a match to the specified search term among an
arrays keys. The following listing illustrates:

<?php
// define array
$cities = array(
"United Kingdom" => "London",
"United States" => "Washington",
"France" => "Paris",
"India" => "Delhi"
);
// search array for key
echo array_key_exists('India', $cities);
?>

Sorting Arrays

PHP comes with a number of built-in functions designed


for sorting array elements in different ways. The first of
these is the sort() function, which lets you sort
numerically indexed arrays alphabetically or
numerically, from lowest to highest value. Heres an
example:
<?php
// define array
$data = array(15,81,14,74,2);
// sort and print array
// output: (2,14,15,74,81)
sort($data);
print_r($data);
?>

If youre sorting an associative array, though, its better to use


the asort() function, which maintains the correlation between
keys and values while sorting.
The following listing illustrates this:
<?php
// define array
$profile = array(
"fname" => "Susan",
"lname" => "Doe",
"sex" => "female",
"sector" => "Asset Management"
);
// sort by value
// output: ('sector' => 'Asset Management',
// 'lname' => 'Doe',
// 'fname' => 'Susan',
// 'sex' => 'female')
asort($profile);
print_r($profile);
?>

Also related to associative arrays is the ksort() function,


which uses keys instead of values when performing the
sorting. Heres an example:
<?php
// define array
$profile = array(
"fname" => "Susan",
"lname" => "Doe",
"sex" => "female",
"sector" => "Asset Management"
);
// sort by key
// output: ('fname' => 'Susan',
// 'lname' => 'Doe',
// 'sector' => 'Asset Management',
// 'sex' => 'female')
ksort($profile);
print_r($profile);
?>

To reverse the sorted sequence


generated by sort(), asort(), and
ksort(), use the
rsort(), arsort(), and krsort()
functions respectively.

Merging Arrays

PHP lets you merge one array into another with its
array_merge() function, which accepts one or more array
variables. The following listing and output illustrates its use:
<?php
// define arrays
$dark = array('black', 'brown', 'blue');
$light = array('white', 'silver', 'yellow');
// merge arrays
// output: ('black', 'brown', 'blue',
// 'white', 'silver', 'yellow')
$colors = array_merge($dark, $light);
print_r($colors);
?>

Comparing Arrays

PHP provides two functions to compare arrays: the array_intersect()


function returns the values common to two arrays, while the
array_diff() function returns the values from the first array that
dont exist in the second. Heres an example, which illustrates both
these functions in action:
<?php
// define arrays
$orange = array('red', 'yellow');
$green = array('yellow', 'blue');
// find common elements
// output: ('yellow')
$common = array_intersect($orange, $green);
print_r($common);
// find elements in first array but not in second
// output: ('red')
$unique = array_diff($orange, $green);
print_r($unique);
?>

Using Numeric Functions


the language has over 50 built-in
functions for working with numbers,
ranging from simple formatting
functions to
functions for arithmetic, logarithmic,
and trigonometric manipulations.

ceil() Rounds a number up


floor() Rounds a number down
abs() Finds the absolute value of a number
pow() Raises one number to the power of another
log() Finds the logarithm of a number
exp() Finds the exponent of a number
rand() Generates a random number
bindec() Converts a number from binary to decimal
decbin() Converts a number from decimal to binary
decoct() Converts a number from decimal to octal
dechex() Converts a number from decimal to
hexadecimal
hexdec() Converts a number from hexadecimal to
decimal
octdec() Converts a number from octal to decimal

Doing Calculus

A common task when working with numbers involves rounding


them up and down. PHP offers
the ceil() and floor() functions for this task, and theyre illustrated in
the next listing:
<?php
// round number up
// output: 19
$num = 19.7;
echo floor($num);
// round number down
// output: 20
echo ceil($num);
?>

Theres also the abs() function, which returns


the absolute value of a number. Heres
an example:
<?php
// return absolute value of number
// output: 19.7
$num = -19.7;
echo abs($num);
?>

The pow() function returns the value


of a number raised to the power of
another:
<?php
// calculate 4 ^ 3
// output: 64
echo pow(4,3);
?>

The log() function calculates the natural or base10 logarithm of a number, while the exp()
function calculates the exponent of a number.
Heres an example of both in action:
<?php
// calculate natural log of 100
// output: 2.30258509299
echo log(10);
// calculate log of 100, base 10
// output: 2
echo log(100,10);
// calculate exponent of 2.30258509299
// output: 9.99999999996
echo exp(2.30258509299);
?>

Generating Random
Numbers
Generating random numbers with PHP is pretty simple
too: the languages built-in rand() function automatically
generates a random integer greater than 0.
You can constrain it to a specific number range by
providing optional limits as arguments. The
following example illustrates:
<?php
// generate a random number
echo rand();
// generate a random number between 10 and 99
echo rand(10,99);
?>

Converting Between Number Bases


PHP comes with built-in functions for
converting between binary, decimal,
octal, and hexadecimal bases. Heres
an example which demonstrates the
bindec(), decbin(), decoct(),
dechex(), hexdec(), and octdec()
functions in action:

<?php
// convert to binary
// output: 1000
echo decbin(8);
// convert to hexadecimal
// output: 8
echo dechex(8);
// convert to octal
// output: 10
echo decoct(8);
// convert from octal
// output: 8
echo octdec(10);
// convert from hexadecimal
// output: 101
echo hexdec(65);
// convert from binary
// output: 8
echo bindec(1000);
?>

PHPError Handling
The default error handling in PHP is very simple. An error
message with filename, line number and a message describing
the error is sent to the browser.
PHP Error Handling
When creating scripts and web applications, error handling is an
important part. If your code lacks error checking code, your
program may look very unprofessional and you may be open to
security risks.
This tutorial contains some of the most common error checking
methods in PHP.
We will show different error handling methods:
Simple "die()" statements
Custom errors and error triggers
Error reporting

Basic Error Handling: Using the die() function

The first example shows a simple script that


opens a text file:
<?php
$file=fopen("welcome.txt","r");
?>
If the file does not exist you might get an error
like this:
Warning: fopen(welcome.txt) [function.fopen]:
failed to open stream:
No such file or directory
inC:\webfolder\test.phpon line2

To prevent the user from getting an error message like the one
above, we test whether the file exist before we try to access it:
<?php
if(!file_exists("welcome.txt")){
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
Now if the file does not exist you get an error like this:
File not found
The code above is more efficient than the earlier code,
because it uses a simple error handling mechanism to stop the
script after the error.

Creating a Custom Error Handler


Creating a custom error handler is quite simple.
We simply create a special function that can be
called when an error occurs in PHP.
This function must be able to handle a minimum
of two parameters (error level and error
message) but can accept up to five parameters
(optionally: file, line-number, and the error
context):
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context)

Error Report levels


These error report levels are the
different types of error the userdefined error handler can be used
for:

Now lets create a function to handle errors:


function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
The code above is a simple error handling function.
When it is triggered, it gets the error level and an
error message. It then outputs the error level and
message and terminates the script.
Now that we have created an error handling function
we need to decide when it should be triggered.

Set Error Handler


The default error handler for PHP is the built in error
handler. We are going to make the function above the
default error handler for the duration of the script.
It is possible to change the error handler to apply for
only some errors, that way the script can handle
different errors in different ways. However, in this
example we are going to use our custom error handler
for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors,
the set_error_handler() only needed one parameter, a
second parameter could be added to specify an error
level.

Example
Testing the error handler by trying to output variable that does not
exist:
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
The output of the code above should be something like this:
Error:[8] Undefined variable: test

Trigger an Error
In a script where users can input data it is useful to trigger errors
when an illegal input occurs. In PHP, this is done by the
trigger_error() function.
Example
In this example an error occurs if the "test" variable is bigger than
"1":
<?php
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
inC:\webfolder\test.phpon line6

An error can be triggered anywhere you wish in a script,


and by adding a second parameter, you can specify what
error level is triggered.
Possible error types:
E_USER_ERROR - Fatal user-generated run-time error.
Errors that can not be recovered from. Execution of the
script is halted
E_USER_WARNING - Non-fatal user-generated run-time
warning. Execution of the script is not halted
E_USER_NOTICE - Default. User-generated run-time
notice. The script found something that might be an
error, but could also happen when running a script
normally

Example
In this example an E_USER_WARNING occurs if the "test" variable is
bigger than "1". If an E_USER_WARNING occurs we will use our custom
error handler and end the script:
<?php
//error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1){
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error:[512] Value must be 1 or below
Ending Script

What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to
enable communications between clients and servers.
HTTP works as a request-response protocol between a
client and server.
A web browser may be the client, and an application on
a computer that hosts a web site may be the server.
Example: A client (browser) submits an HTTP request to
the server; then the server returns a response to the
client. The response contains status information about
the request and may also contain the requested
content.

Two HTTP Request Methods: GET and POST


Two commonly used methods for a requestresponse between a client and server are:
GET and POST.
GET- Requests data from a specified
resource
POST- Submits data to be processed to a
specified resource

PHP - GET & POST Methods


There are two ways the browser
client can send information to the
web server.
The GET Method
The POST Method

The GET Method


The GET method sends the encoded user information
appended to the page request. The page and the encoded
information are separated by the?character.
http://www.test.com/index.htm?name1=value1&name2=val
ue2
The GET method produces a long string that appears in
your server logs, in the browser's Location: box.
The GET method is restricted to send upto 1024 characters
only.
Never use GET method if you have password or other
sensitive information to be sent to the server.
GET can't be used to send binary data, like images or word
documents, to the server.
The data sent by GET method can be accessed using
QUERY_STRING environment variable.
The PHP provides$_GETassociative array to access all the
sent information using GET method.

<?php
if( isset($_GET["name"])|| isset( $_GET["age"] ))
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
issetDetermine if a variable is set and is notNULL

$_PHP_SELF variable contains the


name of self script in which it is
being called.

The POST Method


The POST method transfers information via HTTP headers.
The information is encoded as described in case of GET
method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data
size to be sent.
The POST method can be used to send ASCII as well as
binary data.
The data sent by POST method goes through HTTP header
so security depends on HTTP protocol. By using Secure
HTTP you can make sure that your information is secure.
The PHP provides$_POSTassociative array to access all
the sent information using POST method.

<?php
if( isset($_POST["name"]) ||isset( $_POST["age"] )) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>

When to use GET?


Information sent from a form with the GET method
isvisible to everyone(all variable names and
values are displayed in the URL). GET also has limits
on the amount of information to send. The limitation
is about 2000 characters. However, because the
variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note:GET should NEVER be used for sending
passwords or other sensitive information!

When to use POST?


Information sent from a form with the POST method
isinvisible to others(all names/values are
embedded within the body of the HTTP request) and
hasno limitson the amount of information to send.
Moreover POST supports advanced functionality such
as support for multi-part binary input while uploading
files to server.
However, because the variables are not displayed in
the URL, it is not possible to bookmark the page.
Developers prefer POST for sending form data.

The $_REQUEST variable


The PHP $_REQUEST variable
contains the contents of both $_GET,
$_POST, and $_COOKIE. We will
discuss $_COOKIE variable when we
will explain about cookies.
The PHP $_REQUEST variable can be
used to get the result from form data
sent with both the GET and POST
methods

<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>

Form Handling

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields
and a submit button:
Example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

When the user fills out the form above and clicks the submit
button, the form data is sent for processing to a PHP file
named "welcome.php". The form data is sent with the HTTP
POST method.
To display the submitted data you could simply echo all the
variables. The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

The output could be something like


this:
Welcome John
Your email address is
john.doe@example.com

The same result could also be achieved using the HTTP GET
method:
Example
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

and "welcome_get.php" looks like this:


<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
The code above is quite simple. However, the most
important thing is missing. You need to validate form data to
protect your script from malicious code.

PHP - Cookies
Cookies are text files stored on the client computer and
they are kept of use tracking purpose. PHP transparently
supports HTTP cookies.
There are three steps involved in identifying returning
users
Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
Browser stores this information on local machine for
future use.
When next time browser sends any request to web server
then it sends those cookies information to the server and
server uses that information to identify the user.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header
(although JavaScript can also set a cookie directly
on a browser). A PHP script that sets a cookie
might send headers that look something like this

A PHP script will then have access to


the cookie in the environmental
variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds
all cookie names and values. Above
cookie can be accessed using
$HTTP_COOKIE_VARS["name"].

Setting Cookies with PHP


PHP providedsetcookie()function
to set a cookie. This function requires
upto six arguments and should be
called before <html> tag. For each
cookie this function has to be called
separately.
setcookie(name, value, expire, path,
domain, security);

Here is the detail of all the arguments


Name This sets the name of the cookie and is
stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while
accessing cookies.
Value This sets the value of the named variable
and is the content that you actually want to store.
Expiry This specify a future time in seconds since
00:00:00 GMT on 1st Jan 1970. After this time cookie
will become inaccessible. If this parameter is not set
then cookie will automatically expire when the Web
Browser is closed.

Path This specifies the directories for which the


cookie is valid. A single forward slash character
permits the cookie to be valid for all directories.
Domain This can be used to specify the domain
name in very large domains and must contain at
least two periods to be valid. All cookies are only
valid for the host and domain which created them.
Security This can be set to 1 to specify that
the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0
which mean cookie can be sent by regular HTTP.

Following example will create two cookies name and age


these cookies will be expired after one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

Accessing Cookies with PHP


PHP provides many ways to access cookies. Simplest way is to use
either $_COOKIE or $HTTP_COOKIE_VARS variables. Following
example will access all the cookies set in above example.
<html>

<head>

<title>Accessing Cookies with PHP</title>


</head>

<body>

<?php

echo $_COOKIE["name"]. "<br />";

/* is equivalent to */

echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";

/* is equivalent to */

echo $HTTP_COOKIE_VARS["name"] . "<br />";

?>

</body>
</html>

You can use isset() function to check if a cookie is set or not.


<html>
<head>

<title>Accessing Cookies with PHP</title>


</head>
<body>

<?php

if( isset($_COOKIE["name"]))

echo "Welcome " . $_COOKIE["name"] . "<br />";

else

echo "Sorry... Not recognized" . "<br />";

?>

</body>
</html>

Deleting Cookie with PHP


Officially, to delete a cookie you should call setcookie() with the name
argument only but this does not always work well, however, and should not be
relied on.
It is safest to set the cookie with a date that has already expired

<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

PHP - Sessions
An alternative way to make data accessible across
the various pages of an entire website is to use a
PHP Session.
A session creates a file in a temporary directory on
the server where registered session variables and
their values are stored. This data will be available
to all pages on the site during that visit.
The location of the temporary file is determined by
a setting in the php.inifile
calledsession.save_path. Before using any
session variable make sure you have setup this
path.

When a session is started following things happen


PHP first creates a unique identifier for that particular
session which is a random string of 32 hexadecimal
numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
A cookie calledPHPSESSIDis automatically sent to
the user's computer to store unique session
identification string.
A file is automatically created on the server in the
designated temporary directory and bears the name
of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value


from a session variable, PHP automatically
gets the unique session identifier string from
the PHPSESSID cookie and then looks in its
temporary directory for the file bearing that
name and a validation can be done by
comparing both values.
A session ends when the user loses the
browser or after leaving the site, the server will
terminate the session after a predetermined
period of time, commonly 30 minutes duration.

Starting a PHP Session


A PHP session is easily started by making a call to the
session_start()function.This function first checks if a
session is already started and if none is started then it
starts one. It is recommended to put the call
tosession_start()at the beginning of the page.
Session variables are stored in associative array
called$_SESSION[]. These variables can be accessed
during lifetime of a session.
The following example starts a session then register a
variable calledcounterthat is incremented each time
the page is visited during the session.
Make use ofisset()function to check if session variable
is already set or not.

Put this code in a test.php file and load this file many times to see the result
<?php
session_start();

if( isset( $_SESSION['counter'] ) ) {

$_SESSION['counter'] += 1;
}else {

$_SESSION['counter'] = 1;
}

$msg = "You have visited this page ". $_SESSION['counter'];


$msg .= "in this session.";
?>
<html>

<head>

<title>Setting up a PHP session</title>


</head>

<body>

<?php echo ( $msg ); ?>


</body>

</html>

Destroying a PHP Session


A PHP session can be destroyed
bysession_destroy()function. This function
does not need any argument and a single call
can destroy all the session variables. If you want
to destroy a single session variable then you can
useunset()function to unset a session variable.
Here is the example to unset a single variable
<?php unset($_SESSION['counter']); ?>
Here is the call which will destroy all the session
variables
<?php session_destroy(); ?>

Turning on Auto Session


You don't need to call start_session()
function to start a session when a
user visits your site if you can
setsession.auto_start variable to 1
inphp.inifile.

Sessions without cookies


There may be a case when a user does not
allow to store cookies on their machine. So
there is another method to send session ID to
the browser.
Alternatively, you can use the constant SID
which is defined if the session started. If the
client did not send an appropriate session
cookie, it has the form
session_name=session_id. Otherwise, it
expands to an empty string. Thus, you can
embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to


link correctly to another page using SID.
<?php
session_start();

if (isset($_SESSION['counter'])) {

$_SESSION['counter'] = 1;
}else {

$_SESSION['counter']++;
}

$msg = "You have visited this page ". $_SESSION['counter'];


$msg .= "in this session.";

echo ( $msg );
?>
<p>
To continue click following link <br />

<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">

PHP - Regular Expressions


Regular expressions are nothing more than a sequence or
pattern of characters itself. They provide the foundation
for pattern-matching functionality.
Using regular expression you can search a particular
string inside a another string, you can replace one string
by another string and you can split a string into many
chunks.
PHP offers functions specific to two sets of regular
expression functions, each corresponding to a certain
type of regular expression. You can use any of them
based on your comfort.
POSIX Regular Expressions
PERL Style Regular Expressions

The ereg, eregi, ... are the POSIX


versions and preg_match,
preg_replace, ... are the Perl version. It
is important that using Perl compatible
regular expressions the expression
should be enclosed in the delimiters, a
forward slash (/), for example.
However this version is more powerful
and faster as well than the POSIX one.

The regular expressions basic


syntax
To use regular expressions first you need to
learn the syntax of the patterns. We can group
the characters inside a pattern like this:
Normal characters which match themselves
like hello

Start and end indicators as ^ and $


Count indicators like +,*,?
Logical operator like |
Grouping with {},(),[]

An example pattern to check valid emails looks


like this:
Code:
^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]
{2,5}$
The code to check the email using Perl
compatible regular expression looks like this:
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.
[a-zA-Z.]{2,5}$/";
$email = "jim@demo.com";

if (preg_match($pattern,$email)) echo
"Match";
else echo "Not match";

And very similar in case of POSIX


extended regular expressions:
Code:
$pattern = "^[a-zA-Z0-9._-]+@[a-zA-Z09-]+\.[a-zA-Z.]{2,5}$";
$email = "jim@demo.com";

if (eregi($pattern,$email)) echo "Match";
else echo "Not match";

complex regular expression examples


User name check with regular expression
First start with a user name check. In case of a registration form
you may want to control available user names a bit. Let's suppose
you don't want to allow any special character in the name except
"_.-" and of course letters and numbers. Besides this you may
want to control the length of the user name to be between 4 and
20.
First we need to define the available characters. This can be
realised with the following code:
[a-zA-Z0-9_.-]
After that we need to limit the number of characters with the
following code:
{4,20}
At least we need to put it together:
^[a-zA-Z-0-9_.-]{4,20}$
In case of Perl compatible regular expression surround it with '/'.
At the end the PHP code looks like this:

<?php
$pattern = '/^[a-zA-Z0-9_.-]{4,20}$/';
$username = "this.is.a-demo_-";
if (preg_match($pattern,$username))
echo "Match";
else
echo "Not match";
?>

Check hexadecimal color codes with regular expression

A hexadecimal color code looks like this: #5A332C or


you can use a short form like #C5F. In both case it
starts with a # and follows with exactly 3 or 6 numbers
or letters from a-f.
So the first it starts as:
^#
the following character range is:
[a-fA-F0-9]
and the length can be 3 or 6. The complete pattern is
the following:
^#(([a-fA-F0-9]{3}$)|([a-fA-F0-9]{6}$))
Here we use an or statement first check the #123 form
and then the #123456 form. At the end the PHP code
looks like this:

$pattern = '/^#(([a-fA-F0-9]{3}$)|([a-fA-F0-9]
{6}$))/';
$color = "#1AA";

if (preg_match($pattern,$color))
echo "Match";
else
echo "Not match";

Email check with regular


expression

At least let's see how we can check an email address
with regular expressions. First take a careful look at
the following example emails:
john.demo@demo.com
john@demo.us
john_123.demo_.name@demo.info
What we can see is that the @ is a mandatory
element in an email. Besides this there must be some
character before and some after it. More precisely
there must be a valid domain name after the @.

So the first part must be a string with letters a numbers or


some special characters like _-. In pattern we can write it
as follows:
^[a-zA-Z0-9_.-]+
The domain name always have a let's say name and tld.
The tld is the .com, .us. .info and the name can be any
string with valid characters. It means that the domain
pattern looks like this:
[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$
Now we only need to put together the 2 parts with the @
and get the complete pattern:
^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$
The PHP code looks like this:

<? php
$pattern = '/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]
{2,5}$/';
$email = "john123.demo_.name@demo.info";

if (preg_match($pattern,$email))
echo "Match";
else
echo "Not match";
?>

Vous aimerez peut-être aussi