Vous êtes sur la page 1sur 430

PHP – Complete Reference

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.

Easy Learning with "Show PHP"


Our "Show PHP" tool makes it easy to learn PHP, it shows both the PHP source
code and the HTML output of the code.

Example
<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>

PHP 5 vs. PHP 7

PHP 7 is the newest version of PHP.

PHP 7 is much faster than the previous popular stable release!

PHP 7 has improved Error Handling, supports stricter Type Declarations and
supports new operators, methods and properties.

PHP 5 Introduction
PHP scripts are executed on the server.
What You Should Already Know
Before you continue you should have a basic understanding of the following:

 HTML
 CSS
 JavaScript

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

PHP 5 Installation
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 5 Syntax
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 <?php and 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 re-figure
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, NO keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are 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>

PHP 5 Variables
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 $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.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.

Think of variables as containers for storing data.

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 case-sensitive!

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

The following example will produce the same output as the example above:

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

Note: You will learn more about the echo statement and how to output data to
the screen in the next chapter.

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 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 declared outside a 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 declared within a 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>";
?>

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


The index holds 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 the static keyword when you first declare the variable:

Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>

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.

PHP 5 echo 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.

The PHP echo Statement


The echo statement can be used with or without parentheses: echo or echo().

Display Text

The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):

Example
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

Display Variables

The following example shows how to output text and variables with
the echo statement:

Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>

The PHP print Statement


The print statement can be used with or without
parentheses: print or print().

Display Text

The following example shows how to output text with the print command
(notice that the text can contain HTML markup):

Example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>

Display Variables

The following example shows how to output text and variables with
the print statement:

Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
PHP 5 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:

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. You will learn more about
conditional testing in a later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function


returns the data type and value:

Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

You will learn a lot more about arrays in later chapters of this tutorial.

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:

Example
<?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.

We will not talk about the resource type here, since it is an advanced topic.

PHP 5 Strings
A string is a sequence of characters, like "Hello world!".

PHP String Functions


In this chapter we will look at some commonly used functions to manipulate
strings.

Get The Length of a String


The PHP strlen() function returns the length of a string.

The example below returns the length of the string "Hello world!":

Example
<?php
echo strlen("Hello world!"); // outputs 12
?>

The output of the code above will be: 12.

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.

Reverse a String
The PHP strrev() function reverses a string:

Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

The output of the code above will be: !dlrow olleH.

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!

Complete PHP String Reference


For a complete reference of all string functions, go to our complete PHP String
Reference.

The PHP string reference contains description and example of use, for each
function!
PHP 5 Constants
Constants are like variables except that once they are defined they cannot
be changed or undefined.

PHP Constants
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 a case-sensitive name:


Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>

The example below creates a constant with a case-insensitive name:

Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>

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

PHP 5 Operators
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


The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

PHP Assignment Operators


The PHP assignment operators are used with numeric values to write a value to
a variable.

The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or
string):

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 Logical Operators
The PHP logical operators are used to combine conditional statements.

PHP String Operators


PHP has two operators that are specially designed for strings.

PHP Array Operators


The PHP array operators are used to compare arrays.
PHP 5 if...else...elseif Statements
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:

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

The example below will output "Have a good morning!" if the current time is
less than 10, and "Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":

Example
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The switch Statement


The switch statement will be explained in the next chapter.
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;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

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 breakto prevent the code from
running into the next case automatically. The default statement is used if no
match is found.

Example
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

PHP 5 while Loops


PHP while loops execute a block of code while the specified condition is true.

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 code-lines in a
script, we can use loops to perform a task like this.

In PHP, we have the following looping statements:

 while - loops through a block of code as long as the specified condition is


true
 do...while - loops through a block of code once, and then repeats the
loop as long as the 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 PHP while Loop


The while loop executes a block of code as long as the specified condition is
true.

Syntax
while (condition is true) {
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop
will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will
increase by 1 each time the loop runs ($x++):

Example
<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

The PHP do...while Loop


The do...while loop will always execute the block of code once, it will then
check the condition, and repeat the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);

The example below first sets a variable $x to 1 ($x = 1). Then, the do while
loop will write some output, and then increment the variable $x with 1. Then
the condition is checked (is $x less than, or equal to 5?), and the loop will
continue to run as long as $x is less than, or equal to 5:

Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the
statements within the loop. This means that the do while loop would execute
its statements at least once, even if the condition is false the first time.

The example below sets the $x variable to 6, then it runs the loop, and then
the condition is checked:

Example
<?php
$x = 6;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

The for loop and the foreach loop will be explained in the next chapter.

PHP 5 for Loops


PHP for loops execute a block of code a specified number of times.

The PHP for Loop


The for loop is used when you know in advance how many times the script
should run.

Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.

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, until it reaches the last array
element.

The following example demonstrates a loop that will output the values of the
given array ($colors):

Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

You will learn more about arrays in a later chapter.


PHP 5 Functions
The real power of PHP comes from its functions; it has more than 1000 built-
in functions.

PHP User Defined Functions


Besides the built-in PHP functions, we can create our own functions.

A function is a block of statements that can be used repeatedly in a program.

A function will not execute immediately when a page loads.

A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:

Syntax
function functionName() {
code to be executed;
}

Note: A function name can start with a letter or underscore (not a number).

Tip: Give the function a name that reflects what the function does!

Function names are NOT case-sensitive.

In the example below, we create a function named "writeMsg()". The opening


curly brace ( { ) indicates the beginning of the function code, and the closing
curly brace ( } ) indicates the end of the function. The function outputs "Hello
world!". To call the function, just write its name followed by brackets ():
Example
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just
like a variable.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and the
name is used inside the function, which outputs several different first names,
but an equal last name:

Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:

Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values


To let a function return a value, use the return statement:

Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

PHP 5 Arrays
An array stores multiple values in one single variable:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

What is an Array?
An array is a special variable, which can hold more than one value at a time.

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 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

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 solution is to create an array!

An array can hold many values under a single name, and you can access the
values by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:
array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Get The Length of an Array - The count()


Function
The count() function is used to return the length (the number of elements) of
an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use
a for loop, like this:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:


Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use
a foreach loop, like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

Multidimensional Arrays
Multidimensional arrays will be explained in the PHP advanced section.

Complete PHP Array Reference


For a complete reference of all array functions, go to our complete PHP Array
Reference.

The reference contains a brief description, and examples of use, for each
function!
PHP 5 Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.

PHP - Sort Functions For Arrays


In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the
value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the
value
 krsort() - sort associative arrays in descending order, according to the
key

Sort Array in Ascending Order - sort()


The following example sorts the elements of the $cars array in ascending
alphabetical order:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

The following example sorts the elements of the $numbers array in ascending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>

Sort Array in Descending Order - rsort()


The following example sorts the elements of the $cars array in descending
alphabetical order:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

The following example sorts the elements of the $numbers array in descending
numerical order:

Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>

Sort Array (Ascending Order), According to


Value - asort()
The following example sorts an associative array in ascending order, according
to the value:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

Sort Array (Ascending Order), According to Key


- ksort()
The following example sorts an associative array in ascending order, according
to the key:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

Sort Array (Descending Order), According to


Value - arsort()
The following example sorts an associative array in descending order, according
to the value:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>

Sort Array (Descending Order), According to


Key - krsort()
The following example sorts an associative array in descending order, according
to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

PHP 5 Global Variables - Superglobals


Superglobals were introduced in PHP 4.1.0, and are built-in variables that
are always available in all scopes.

PHP Global Variables - Superglobals


Several predefined variables in PHP are "superglobals", which means that they
are always accessible, regardless of scope - and you can access them from any
function, class or file without having to do anything special.

The PHP superglobal variables are:

 $GLOBALS
 $_SERVER
 $_REQUEST
 $_POST
 $_GET
 $_FILES
 $_ENV
 $_COOKIE
 $_SESSION

This chapter will explain some of the superglobals, and the rest will be explained
in later chapters.

PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global
variables from anywhere in the PHP script (also from within functions or
methods).

PHP stores all global variables in an array called $GLOBALS[index].


The index holds the name of the variable.

The example below shows how to use the super global variable $GLOBALS:

Example
<?php
$x = 75;
$y = 25;

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>

In the example above, since z is a variable present within the $GLOBALS array,
it is also accessible from outside the function!

PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.

The example below shows how to use some of the elements in $_SERVER:

Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

The following table lists the most important elements that can go inside
$_SERVER:

Element/Code Description

$_SERVER['PHP_SELF'] Returns the filename of the currently


executing script

$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common


Gateway Interface (CGI) the server is
using

$_SERVER['SERVER_ADDR'] Returns the IP address of the host


server

$_SERVER['SERVER_NAME'] Returns the name of the host server


(such as www.w3schools.com)

$_SERVER['SERVER_SOFTWARE'] Returns the server identification string


(such as Apache/2.2.24)

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the


information protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to
access the page (such as POST)

$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of


the request (such as 1377687496)

$_SERVER['QUERY_STRING'] Returns the query string if the page is


accessed via a query string

$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the


current request

$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from


the current request (such as utf-8,ISO-
8859-1)

$_SERVER['HTTP_HOST'] Returns the Host header from the


current request

$_SERVER['HTTP_REFERER'] Returns the complete URL of the page


from which the current page was called

$_SERVER['HTTPS'] Is the script queried through a secure


HTTP protocol

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the


user is viewing the current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the
user is viewing the current page

$_SERVER['REMOTE_PORT'] Returns the port being used on the


user's machine to communicate with the
web server

$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the


currently executing script

$_SERVER['SERVER_ADMIN'] Returns the value given to the


SERVER_ADMIN directive in the web
server configuration file (if your script
runs on a virtual host, it will be the
value defined for that virtual host) (such
as someone@w3schools.com)

$_SERVER['SERVER_PORT'] Returns the port on the server machine


being used by the web server for
communication (such as 80)

$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual


host name which are added to server-
generated pages

$_SERVER['PATH_TRANSLATED'] Returns the file system based path to


the current script

$_SERVER['SCRIPT_NAME'] Returns the path of the current script


$_SERVER['SCRIPT_URI'] Returns the URI of the current page

PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When
a user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to
this file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_REQUEST to collect the value of the input field:

Example
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When
a user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to
the file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_POST to collect the value of the input field:

Example
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form
with method="get".

$_GET can also collect data sent in the URL.

Assume we have an HTML page that contains a hyperlink with parameters:


<html>
<body>

<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>

When a user clicks on the link "Test $GET", the parameters "subject" and "web"
are sent to "test_get.php", and you can then access their values in
"test_get.php" with $_GET.

The example below shows the code in "test_get.php":

Example
<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>

PHP 5 Form Handling


The PHP superglobals $_GET and $_POST are used to collect form-data.

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.

Think SECURITY when processing PHP forms!

This page does not contain any form validation, it just shows how you can send
and retrieve form data.

However, the next pages will show how to process PHP forms with security in
mind! Proper validation of form data is important to protect your form from
hackers and spammers!

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where keys are
the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do anything
special.

$_GET is an array of variables passed to the current script via the URL
parameters.

$_POST is an array of variables passed to the current script via the HTTP POST
method.
When to use GET?
Information sent from a form with the GET method is visible 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 is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no
limits on 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.

Next, lets see how we can process PHP forms the secure way!

Form Validation
This and the next chapters show how to use PHP to validate form data.

PHP Form Validation


Think SECURITY when processing PHP forms!
These pages will show how to process PHP forms with security in mind. Proper
validation of form data is important to protect your form from hackers and
spammers!

The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:

The validation rules for the form above are as follows:


First we will look at the plain HTML code for the form:

Text Fields
The name, email, and website fields are text input elements, and the comment
field is a textarea. The HTML code looks like this:

Name: <input type="text" name="name">


E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>

Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:

Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other

The Form Element


The HTML code of the form looks like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])


;?>">

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename


of the currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.
What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities.


This means that it will replace HTML characters like < and > with &lt; and &gt;.
This prevents attackers from exploiting the code by injecting HTML or Javascript
code (Cross-site Scripting attacks) in forms.

Big Note on PHP Form Security


The $_SERVER["PHP_SELF"] variable can be used by hackers!

If PHP_SELF is used in your page then a user can enter a slash (/) and then
some Cross Site Scripting (XSS) commands to execute.

Cross-site scripting (XSS) is a type of computer security vulnerability


typically found in Web applications. XSS enables attackers to inject
client-side script into Web pages viewed by other users.

Assume we have the following form in a page named "test_form.php":

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:

<form method="post" action="test_form.php">

So far, so good.

However, consider that a user enters the following URL in the address bar:

http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/scr
ipt%3E

In this case, the above code will be translated to:

<form method="post" action="test_form.php/"><script>alert('hacked')</script>

This code adds a script tag and an alert command. And when the page loads,
the JavaScript code will be executed (the user will see an alert box). This is just
a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script>
tag! A hacker can redirect the user to a file on another server, and that file can
hold malicious code that can alter the global variables or submit the form to
another address to save the user data, for example.

How To Avoid $_SERVER["PHP_SELF"] Exploits?


$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars()
function.

The form code should look like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])


;?>">

The htmlspecialchars() function converts special characters to HTML entities.


Now if the user tries to exploit the PHP_SELF variable, it will result in the
following output:

<form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hack


ed')&lt;/script&gt;">

The exploit attempt fails, and no harm is done!

Validate Form Data With PHP


The first thing we will do is to pass all variables through PHP's
htmlspecialchars() function.

When we use the htmlspecialchars() function; then if a user tries to submit the
following in a text field:

<script>location.href('http://www.hacked.com')</script>

- this would not be executed, because it would be saved as HTML escaped code,
like this:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

1. Strip unnecessary characters (extra space, tab, newline) from the user
input data (with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP
stripslashes() function)

The next step is to create a function that will do all the checking for us (which is
much more convenient than writing the same code over and over again).

We will name the function test_input().

Now, we can check each $_POST variable with the test_input() function, and
the script looks like this:

Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

Notice that at the start of the script, we check whether the form has been
submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is
POST, then the form has been submitted - and it should be validated. If it has
not been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works
fine even if the user does not enter any data.

The next step is to make input fields required and create error messages if
needed.

PHP 5 Forms - Required Fields


This chapter shows how to make input fields required and create error
messages if needed.

PHP - Required Fields


From the validation rules table on the previous page, we see that the "Name",
"E-mail", and "Gender" fields are required. These fields cannot be empty and
must be filled out in the HTML form.

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @ an

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)


Gender Required. Must select one

In the previous chapter, all input fields were optional.

In the following code we have added some new variables: $nameErr, $emailErr,
$genderErr, and $websiteErr. These error variables will hold error messages for
the required fields. We have also added an if else statement for each $_POST
variable. This checks if the $_POST variable is empty (with the
PHP empty() function). If it is empty, an error message is stored in the different
error variables, and if it is not empty, it sends the user input data through
the test_input() function:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

PHP - Display The Error Messages


Then in the HTML form, we add a little script after each required field, which
generates the correct error message if needed (that is if the user tries to submit
the form without filling out the required fields):

Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])
;?>">

Name: <input type="text" name="name">


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>
The next step is to validate the input data, that is "Does the Name field contain
only letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid
URL?".

PHP 5 Forms - Validate E-mail and URL


This chapter shows how to validate names, e-mails, and URLs.

PHP - Validate Name


The code below shows a simple way to check if the name field only contains
letters and whitespace. If the value of the name field is not valid, then store an
error message:

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}

The preg_match() function searches a string for pattern, returning true if the
pattern exists, and false otherwise.

PHP - Validate E-mail


The easiest and safest way to check whether an email address is well-formed is
to use PHP's filter_var() function.

In the code below, if the e-mail address is not well-formed, then store an error
message:

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this
regular expression also allows dashes in the URL). If the URL address syntax is
not valid, then store an error message:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

PHP - Validate Name, E-mail, and URL


Now, the script looks like this:

Example
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

PHP 5 Complete Form Example


This chapter shows how to keep the values in the input fields when the user
hits the submit button.

PHP - Keep The Values in The Form


To show the values in the input fields after the user hits the submit button, we
add a little PHP script inside the value attribute of the following input fields:
name, email, and website. In the comment textarea field, we put the script
between the <textarea> and </textarea> tags. The little script outputs the
value of the $name, $email, $website, and $comment variables.

Then, we also need to show which radio button that was checked. For this, we
must manipulate the checked attribute (not the value attribute for radio
buttons):

Name: <input type="text" name="name" value="<?php echo $name;?>">

E-mail: <input type="text" name="email" value="<?php echo $email;?>">

Website: <input type="text" name="website" value="<?php echo $website;


?>">

Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comme


nt;?></textarea>

Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other

PHP - Complete Form Example


Here is the complete code for the PHP Form Validation Example:
Example

PHP 5 Multidimensional Arrays


Earlier in this tutorial, we have described arrays that are a single list of
key/value pairs.

However, sometimes you want to store values with more than one key.

This can be stored in multidimensional arrays.

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep. However, arrays more than three levels deep are hard to
manage for most people.

The dimension of an array indicates the number of indices you need to


select an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).

First, take a look at the following table:

We can store the data from the table above in a two-dimensional array, like
this:

$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.

To get access to the elements of the $cars array we must point to the two
indices (row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

We can also put a for loop inside another for loop to get the elements of the
$cars array (we still have to point to the two indices):

Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

PHP 5 Date and Time


The PHP date() function is used to format a date and/or a time.

The PHP Date() Function


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

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 ti

A timestamp is a sequence of characters, denoting the date and/or time at


which a certain event occurred.

Get a Simple Date


The required format parameter of the date() function specifies how to format
the date (or time).

Here are some characters that are commonly used for dates:

 d - Represents the day of the month (01 to 31)


 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)
 l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters
to add additional formatting.

The example below formats today's date in three different ways:

Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
PHP Tip - Automatic Copyright Year
Use the date() function to automatically update the copyright year on your
website:

Example
&copy; 2010-<?php echo date("Y");?>

Get a Simple Time


Here are some characters that are commonly used for times:

 H - 24-hour format of an hour (00 to 23)


 h - 12-hour format of an hour with leading zeros (01 to 12)
 i - Minutes with leading zeros (00 to 59)
 s - Seconds with leading zeros (00 to 59)
 a - Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:

Example
<?php
echo "The time is " . date("h:i:sa");
?>

Note that the PHP date() function will return the current date/time of the
server!

Get Your Time Zone


If the time you got back from the code is not the right time, it's probably
because your server is in another country or set up for a different timezone.

So, if you need the time to be correct according to a specific location, you can
set a timezone to use.
The example below sets the timezone to "America/New_York", then outputs the
current time in the specified format:

Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>

Create a Date With PHP mktime()


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 (as
shown in the examples above).

The mktime() function returns the Unix timestamp for a date. The Unix
timestamp contains the number of seconds between the Unix Epoch (January 1
1970 00:00:00 GMT) and the time specified.

Syntax
mktime(hour,minute,second,month,day,year)

The example below creates a date and time from a number of parameters in
the mktime() function:

Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

Create a Date From a String With PHP


strtotime()
The PHP strtotime() function is used to convert a human readable string to a
Unix time.
Syntax
strtotime(time,now)

The example below creates a date and time from the strtotime() function:

Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

PHP is quite clever about converting a string to a date, so you can put in various
values:

Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>

However, strtotime() is not perfect, so remember to check the strings you put
in there.

More Date Examples


The example below outputs the dates for the next six Saturdays:
Example
<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $startdate);

while ($startdate < $enddate) {


echo date("M d", $startdate) . "<br>";
$startdate = strtotime("+1 week", $startdate);
}
?>

The example below outputs the number of days until 4th of July:

Example
<?php
$d1=strtotime("July 04");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 4th of July.";
?>

Complete PHP Date Reference


For a complete reference of all date functions, go to our complete PHP Date
Reference.

The reference contains a brief description, and examples of use, for each
function!

PHP 5 Include Files


The include (or require) statement takes all the text/code/markup that
exists in the specified file and copies it into the file that uses the include
statement.

Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website.
PHP include and require Statements
It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

 require will produce a fatal error (E_COMPILE_ERROR) and stop the


script
 include will only produce a warning (E_WARNING) and the script will
continue

So, if you want the execution to go on and show users the output, even if the
include file is missing, use the include statement. Otherwise, in case of
FrameWork, CMS, or a complex PHP application coding, always use the require
statement to include a key file to the flow of execution. This will help avoid
compromising your application's security and integrity, just in-case one key file
is accidentally missing.

Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header
needs to be updated, you can only update the header include file.

Syntax
include 'filename';

or

require 'filename';

PHP include Examples


Example 1
Assume we have a standard footer file called "footer.php", that looks like this:

<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>

Example 2
Assume we have a standard menu file called "menu.php":

<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>

All pages in the Web site should use this menu file. Here is how it can be done
(we are using a <div> element so that the menu easily can be styled with CSS
later):

Example
<html>
<body>

<div class="menu">
<?php include 'menu.php';?>
</div>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>

Example 3
Assume we have a file called "vars.php", with some variables defined:

<?php
$color='red';
$car='BMW';
?>

Then, if we include the "vars.php" file, the variables can be used in the calling
file:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php include 'vars.php';
echo "I have a $color $car.";
?>

</body>
</html>

PHP include vs. require


The require statement is also used to include a file into the PHP code.

However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will
continue to execute:

Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

If we do the same example using the require statement, the echo statement
will not be executed because the script execution dies after
therequire statement returned a fatal error:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

Use require when the file is required by the application.

Use include when the file is not required and application should continue when
file is not found.

File handling is an important part of any web application. You often need to
open and process a file for different tasks.

PHP Manipulating Files


PHP has several functions for creating, reading, uploading, and editing files.

Be careful when manipulating files!

When you are manipulating files you must be very careful.


You can do a lot of damage if you do something wrong. Common errors are:
editing the wrong file, filling a hard-drive with garbage data, and deleting the
content of a file by accident.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.

Assume we have a text file called "webdictionary.txt", stored on the server, that
looks like this:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The PHP code to read the file and write it to the output buffer is as follows
(the readfile() function returns the number of bytes read on success):

Example
<?php
echo readfile("webdictionary.txt");
?>

The readfile() function is useful if all you want to do is open up a file and read
its contents.

The next chapters will teach you more about file handling.

PHP 5 File Open/Read/Close


In this chapter we will teach you how to open, read, and close a file on the
server.
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives
you more options than the readfile() function.

We will use the text file, "webdictionary.txt", during the lessons:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The first parameter of fopen() contains the name of the file to be opened and
the second parameter specifies in which mode the file should be opened. The
following example also generates a message if the fopen() function is unable to
open the specified file:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Tip: The fread() and the fclose() functions will be explained below.

The file may be opened in one of the following modes:

Modes Description

r Open a file for read only. File pointer starts at the


beginning of the file
w Open a file for write only. Erases the contents of the file
or creates a new file if it doesn't exist. File pointer starts at
the beginning of the file

a Open a file for write only. The existing data in file is


preserved. File pointer starts at the end of the file. Creates
a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an


error if file already exists

r+ Open a file for read/write. File pointer starts at the


beginning of the file

w+ Open a file for read/write. Erases the contents of the


file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is


preserved. File pointer starts at the end of the file. Creates
a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and


an error if file already exists

PHP Read File - fread()


The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and
the second parameter specifies the maximum number of bytes to read.

The following PHP code reads the "webdictionary.txt" file to the end:

fread($myfile,filesize("webdictionary.txt"));

PHP Close File - fclose()


The fclose() function is used to close an open file.

It's a good programming practice to close all files after you have finished with
them. You don't want an open file running around on your server taking up
resources!

The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:

<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>

PHP Read Single Line - fgets()


The fgets() function is used to read a single line from a file.

The example below outputs the first line of the "webdictionary.txt" file:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the
next line.

PHP Check End-Of-File - feof()


The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

The example below reads the "webdictionary.txt" file line by line, until end-of-
file is reached:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

PHP Read Single Character - fgetc()


The fgetc() function is used to read a single character from a file.

The example below reads the "webdictionary.txt" file character by character,


until end-of-file is reached:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next
character.

Complete PHP Filesystem Reference


For a complete reference of filesystem functions, go to our complete PHP
Filesystem Reference.

PHP 5 File Create/Write


In this chapter we will teach you how to create and write to a file on the
server.

PHP Create File - fopen()


The fopen() function is also used to create a file. Maybe a little confusing, but
in PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the
file is opened for writing (w) or appending (a).

The example below creates a new file called "testfile.txt". The file will be created
in the same directory where the PHP code resides:

Example
$myfile = fopen("testfile.txt", "w")

PHP File Permissions


If you are having errors when trying to get this code to run, check that you
have granted your PHP file access to write information to the hard drive.

PHP Write to File - fwrite()


The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and
the second parameter is the string to be written.

The example below writes a couple of names into a new file called "newfile.txt":

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the
file we sent the string $txt that first contained "John Doe" and second contained
"Jane Doe". After we finished writing, we closed the file using
the fclose() function.

If we open the "newfile.txt" file it would look like this:

John Doe
Jane Doe

PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we
open an existing file for writing. All the existing data will be ERASED and we
start with an empty file.
In the example below we open our existing file "newfile.txt", and write some
new data into it:

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the "newfile.txt" file, both John and Jane have vanished, and
only the data we just wrote is present:

Mickey Mouse
Minnie Mouse

Complete PHP Filesystem Reference


For a complete reference of filesystem functions, go to our complete PHP
Filesystem Reference.

PHP 5 File Upload


With PHP, it is easy to upload files to the server.

However, with ease comes danger, so always be careful when allowing file
uploads!

Configure The "php.ini" File


First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On

Create The HTML Form


Next, create an HTML form that allow users to choose the image file they want
to upload:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Some rules to follow for the HTML form above:

 Make sure that the form uses method="post"


 The form also needs the following attribute: enctype="multipart/form-
data". It specifies which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

Other things to notice:

 The type="file" attribute of the <input> tag shows the input field as a
file-select control, with a "Browse" button next to the input control

The form above sends data to a file called "upload.php", which we will create
next.

Create The Upload File PHP Script


The "upload.php" file contains the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

PHP script explained:

 $target_dir = "uploads/" - specifies the directory where the file is going to


be placed
 $target_file specifies the path of the file to be uploaded
 $uploadOk=1 is not used yet (will be used later)
 $imageFileType holds the file extension of the file (in lower case)
 Next, check if the image file is an actual image or a fake image

Note: You will need to create a new directory called "uploads" in the directory
where "upload.php" file resides. The uploaded files will be saved there.

Check if File Already Exists


Now we can add some restrictions.

First, we will check if the file already exists in the "uploads" folder. If it does, an
error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

Limit File Size


The file input field in our HTML form above is named "fileToUpload".

Now, we want to check the size of the file. If the file is larger than 500KB, an
error message is displayed, and $uploadOk is set to 0:

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

Limit File Type


The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All
other file types gives an error message before setting $uploadOk to 0:

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

Complete Upload File PHP Script


The complete "upload.php" file now looks like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ".
basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

Complete PHP Filesystem Reference


For a complete reference of filesystem functions, go to our complete PHP
Filesystem Reference.

PHP 5 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.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John
Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the
cookie is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:

Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400
= 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Note: The setcookie() function must appear BEFORE the <html> tag.

Note: The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent URLencoding,
use setrawcookie() instead).

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:

Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are
enabled. First, try to create a test cookie with the setcookie()function, then
count the $_COOKIE array variable:

Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

</body>
</html>

PHP 5 Sessions
A session is a way to store information (in variables) to be used across
multiple pages.

Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?


When you work 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 or what you
do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used


across multiple pages (e.g. username, favorite color, etc). By default, session
variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available
to all pages in one application.

Tip: If you need a permanent storage, you may want to store the data in
a database.

Start a PHP Session


A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start
a new PHP session and set some session variables:

Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we
will access the session information we set on the first page
("demo_session1.php").

Notice that session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning of each
page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION
variable:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Another way to show all the session variable values for a user session is to run
the following code:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

How does it work? How does it know it's me?

Most sessions set a user-key on the user's computer that looks something like
this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on
another page, it scans the computer for a user-key. If there is a match, it
accesses that session, if not, it starts a new session.

Modify a PHP Session Variable


To change a session variable, just overwrite it:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session,
use session_unset() and session_destroy():

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

PHP Filters
Validating data = Determine if the data is in proper form.

Sanitizing data = Remove any illegal character from the data.

The PHP Filter Extension


PHP filters are used to validate and sanitize external input.

The PHP filter extension has many of the functions needed for checking user
input, and is designed to make data validation easier and quicker.

The filter_list() function can be used to list what the PHP filter extension
offers:
Example
<table>
<tr>
<td>Filter Name</td>
<td>Filter ID</td>
</tr>
<?php
foreach (filter_list() as $id =>$filter) {
echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter)
. '</td></tr>';
}
?>
</table>

Why Use Filters?


Many web applications receive external input. External input/data can be:

 User input from a form


 Cookies
 Web services data
 Server variables
 Database query results

You should always validate external data!


Invalid submitted data can lead to security problems and break your webpage!
By using PHP filters you can be sure your application gets the correct input!

PHP filter_var() Function


The filter_var() function both validate and sanitize data.

The filter_var() function filters a single variable with a specified filter. It


takes two pieces of data:

 The variable you want to check


 The type of check to use
Sanitize a String
The following example uses the filter_var() function to remove all HTML tags
from a string:

Example
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>

Validate an Integer
The following example uses the filter_var() function to check if the variable
$int is an integer. If $int is an integer, the output of the code below will be:
"Integer is valid". If $int is not an integer, the output will be: "Integer is not
valid":

Example
<?php
$int = 100;

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {


echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>

Tip: filter_var() and Problem With 0


In the example above, if $int was set to 0, the function above will return
"Integer is not valid". To solve this problem, use the code below:

Example
<?php
$int = 0;
if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int,
FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>

Validate an IP Address
The following example uses the filter_var() function to check if the variable
$ip is a valid IP address:

Example
<?php
$ip = "127.0.0.1";

if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {


echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
}
?>

Sanitize and Validate an Email Address


The following example uses the filter_var() function to first remove all illegal
characters from the $email variable, then check if it is a valid email address:

Example
<?php
$email = "john.doe@example.com";

// Remove all illegal characters from email


$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>

Sanitize and Validate a URL


The following example uses the filter_var() function to first remove all illegal
characters from a URL, then check if $url is a valid URL:

Example
<?php
$url = "https://www.w3schools.com";

// Remove all illegal characters from a url


$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>

PHP Filters Advanced


Validate an Integer Within a Range
The following example uses the filter_var() function to check if a variable is
both of type INT, and between 1 and 200:

Example
<?php
$int = 122;
$min = 1;
$max = 200;
if (filter_var($int,
FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=
>$max))) === false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>

Validate IPv6 Address


The following example uses the filter_var() function to check if the variable
$ip is a valid IPv6 address:

Example
<?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";

if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {


echo("$ip is a valid IPv6 address");
} else {
echo("$ip is not a valid IPv6 address");
}
?>

Validate URL - Must Contain QueryString


The following example uses the filter_var() function to check if the variable
$url is a URL with a querystring:

Example
<?php
$url = "https://www.w3schools.com";

if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) ===


false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>

Remove Characters With ASCII Value > 127


The following example uses the filter_var() function to sanitize a string. It
will both remove all HTML tags, and all characters with ASCII value > 127, from
the string:

Example
<?php
$str = "<h1>Hello WorldÆØÅ!</h1>";

$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);


echo $newstr;
?>

PHP Error 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 in C:\webfolder\test.php on line 2

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.

However, simply stopping the script is not always the right way to go. Let's take
a look at alternative PHP functions for handling errors.

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)

Parameter Description

error_level Required. Specifies the error report level for the user-defined
error. Must be a value number. See table below for possible
error report levels

error_message Required. Specifies the error message for the user-defined


error

error_file Optional. Specifies the filename in which the error occurred

error_line Optional. Specifies the line number in which the error


occurred

error_context Optional. Specifies an array containing every variable, and


their values, in use when the error occurred

Error Report levels


These error report levels are the different types of error the user-defined error
handler can be used for:

Value Constant Description


2 E_WARNING Non-fatal run-time errors. Execution of the script is not
halted

8 E_NOTICE Run-time notices. The script found something that


might be an error, but could also happen when running
a script normally

256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR


set by the programmer using the PHP function
trigger_error()

512 E_USER_WARNING Non-fatal user-generated warning. This is like an


E_WARNING set by the programmer using the PHP
function trigger_error()

1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set


by the programmer using the PHP function
trigger_error()

4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can
be caught by a user defined handle (see also
set_error_handler())

8191 E_ALL All errors and warnings (E_STRICT became a part of


E_ALL in PHP 5.4)

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


in C:\webfolder\test.php on line 6

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

Now that we have learned to create our own errors and how to trigger them,
lets take a look at error logging.

Error Logging
By default, PHP sends an error log to the server's logging system or a file,
depending on how the error_log configuration is set in the php.ini file. By using
the error_log() function you can send error logs to a specified file or a remote
destination.

Sending error messages to yourself by e-mail can be a good way of getting


notified of specific errors.

Send an Error Message by E-Mail


In the example below we will send an e-mail with an error message and end the
script, if a specific error occurs:

<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}

//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


Webmaster has been notified

And the mail received from the code above looks like this:

Error: [512] Value must be 1 or below

This should not be used with all errors. Regular errors should be logged on the
server using the default PHP logging system.

PHP Exception Handling


Exceptions are used to change the normal flow of a script if a specified error
occurs.

What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.

Exception handling is used to change the normal flow of the code execution if a
specified error (exceptional) condition occurs. This condition is called an
exception.

This is what normally happens when an exception is triggered:

 The current code state is saved


 The code execution will switch to a predefined (custom) exception handler
function
 Depending on the situation, the handler may then resume the execution
from the saved code state, terminate the script execution or continue the
script from a different location in the code

We will show different error handling methods:

 Basic use of Exceptions


 Creating a custom exception handler
 Multiple exceptions
 Re-throwing an exception
 Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be
used to jump to another place in the code at a specified point.

Basic Use of Exceptions


When an exception is thrown, the code following it will not be executed, and
PHP will try to find the matching "catch" block.

If an exception is not caught, a fatal error will be issued with an "Uncaught


Exception" message.

Lets try to throw an exception without catching it:

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception 'Exception'


with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch


To avoid the error from the example above, we need to create the proper code
to handle an exception.

Proper exception code should include:

1. try - A function using an exception should be in a "try" block. If the


exception does not trigger, the code will continue as normal. However if
the exception triggers, an exception is "thrown"
2. throw - This is how you trigger an exception. Each "throw" must have at
least one "catch"
3. catch - A "catch" block retrieves an exception and creates an object
containing the exception information

Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception in a "try" block


try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like this:

Message: Value must be 1 or below

Example explained:
The code above throws an exception and catches it:

1. The checkNum() function is created. It checks if a number is greater than


1. If it is, an exception is thrown
2. The checkNum() function is called in a "try" block
3. The exception within the checkNum() function is thrown
4. The "catch" block retrieves the exception and creates an object ($e)
containing the exception information
5. The error message from the exception is echoed by calling $e-
>getMessage() from the exception object

However, one way to get around the "every throw must have a catch" rule is to
set a top level exception handler to handle errors that slip through.

Creating a Custom Exception Class


To create a custom exception handler you must create a special class with
functions that can be called when an exception occurs in PHP. The class must be
an extension of the exception class.

The custom exception class inherits the properties from PHP's exception class
and you can add custom functions to it.

Lets create an exception class:

<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this-
>getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example...com";

try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}

catch (customException $e) {


//display custom message
echo $e->errorMessage();
}
?>

The new class is a copy of the old exception class with an addition of the
errorMessage() function. Since it is a copy of the old class, and it inherits the
properties and methods from the old class, we can use the exception class
methods like getLine() and getFile() and getMessage().

Example explained:
The code above throws an exception and catches it with a custom exception
class:

1. The customException() class is created as an extension of the old


exception class. This way it inherits all methods and properties from the
old exception class
2. The errorMessage() function is created. This function returns an error
message if an e-mail address is invalid
3. The $email variable is set to a string that is not a valid e-mail address
4. The "try" block is executed and an exception is thrown since the e-mail
address is invalid
5. The "catch" block catches the exception and displays the error message
Multiple Exceptions
It is possible for a script to use multiple exceptions to check for multiple
conditions.

It is possible to use several if..else blocks, a switch, or nest multiple exceptions.


These exceptions can use different exception classes and return different error
messages:

<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this-
>getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example.com";

try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
throw new Exception("$email is an example e-mail");
}
}

catch (customException $e) {


echo $e->errorMessage();
}

catch(Exception $e) {
echo $e->getMessage();
}
?>

Example explained:
The code above tests two conditions and throws an exception if any of the
conditions are not met:

1. The customException() class is created as an extension of the old


exception class. This way it inherits all methods and properties from the
old exception class
2. The errorMessage() function is created. This function returns an error
message if an e-mail address is invalid
3. The $email variable is set to a string that is a valid e-mail address, but
contains the string "example"
4. The "try" block is executed and an exception is not thrown on the first
condition
5. The second condition triggers an exception since the e-mail contains the
string "example"
6. The "catch" block catches the exception and displays the correct error
message

If the exception thrown were of the class customException and there were no
customException catch, only the base exception catch, the exception would be
handled there.

Re-throwing Exceptions
Sometimes, when an exception is thrown, you may wish to handle it differently
than the standard way. It is possible to throw an exception a second time within
a "catch" block.

A script should hide system errors from users. System errors may be important
for the coder, but are of no interest to the user. To make things easier for the
user you can re-throw the exception with a user friendly message:

<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}

$email = "someone@example.com";

try {
try {
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e) {
//re-throw exception
throw new customException($email);
}
}

catch (customException $e) {


//display custom message
echo $e->errorMessage();
}
?>

Example explained:
The code above tests if the email-address contains the string "example" in it, if
it does, the exception is re-thrown:

1. The customException() class is created as an extension of the old


exception class. This way it inherits all methods and properties from the
old exception class
2. The errorMessage() function is created. This function returns an error
message if an e-mail address is invalid
3. The $email variable is set to a string that is a valid e-mail address, but
contains the string "example"
4. The "try" block contains another "try" block to make it possible to re-
throw the exception
5. The exception is triggered since the e-mail contains the string "example"
6. The "catch" block catches the exception and re-throws a
"customException"
7. The "customException" is caught and displays an error message

If the exception is not caught in its current "try" block, it will search for a catch
block on "higher levels".

Set a Top Level Exception Handler


The set_exception_handler() function sets a user-defined function to handle
all uncaught exceptions:

<?php
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');


?>

The output of the code above should be something like this:

Exception: Uncaught Exception occurred

In the code above there was no "catch" block. Instead, the top level exception
handler triggered. This function should be used to catch uncaught exceptions.

Rules for exceptions


 Code may be surrounded in a try block, to help catch potential exceptions
 Each try block or "throw" must have at least one corresponding catch
block
 Multiple catch blocks can be used to catch different classes of exceptions
 Exceptions can be thrown (or re-thrown) in a catch block within a try
block

A simple rule: If you throw something, you have to catch it.


PHP MySQL Database
With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of


related data, and it consists of columns and rows.

Databases are useful for storing information categorically. A company may have
a database with the following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL Database System


 PHP combined with MySQL are cross-platform (you can develop in
Windows and serve on a Unix platform)
Database Queries
A query is a question or a request.

We can query a database for specific information and have a recordset


returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the
"Employees" table.

To learn more about SQL, please visit our SQL tutorial.

Download MySQL Database


If you don't have a PHP server with a MySQL Database, you can download it for
free here: http://www.mysql.com

Facts About MySQL Database


MySQL is the de-facto standard database system for web sites with HUGE
volumes of both data and end-users (like Facebook, Twitter, and Wikipedia).

Another great thing about MySQL is that it can be scaled down to support
embedded database applications.

Look at http://www.mysql.com/customers/ for an overview of companies using


MySQL.

PHP Connect to MySQL


PHP 5 and later can work with a MySQL database using:
 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)

Earlier versions of PHP used the MySQL extension. However, this extension
was deprecated in 2012.

Should I Use MySQLi or PDO?


If you need a short answer, it would be "Whatever you like".

Both MySQLi and PDO have their advantages:

PDO will work on 12 different database systems, whereas MySQLi will only work
with MySQL databases.

So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queries included.

Both are object-oriented, but MySQLi also offers a procedural API.

Both support Prepared Statements. Prepared Statements protect from SQL


injection, and are very important for web application security.

MySQL Examples in Both MySQLi and PDO


Syntax
In this, and in the following chapters we demonstrate three ways of working
with PHP and MySQL:

 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO

MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most
cases, when php5 mysql package is installed.

For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php

Open a Connection to MySQL


Before we can access data in the MySQL database, we need to be able to
connect to the server:

Example (MySQLi Object-Oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

PHP is an amazing and popular language!

Note on the object-oriented example above: $connect_error was broken until


PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with PHP versions prior
to 5.2.9 and 5.3.0, use the following code instead:

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Note: In the PDO example above we have also specified a database
(myDB). PDO require a valid database to connect to. If no database is
specified, an exception is thrown.

Tip: A great benefit of PDO is that it has an exception class to handle any
problems that may occur in our database queries. If an exception is thrown
within the try{ } block, the script stops executing and flows directly to the first
catch(){ } block.

Close the Connection


The connection will be closed automatically when the script ends. To close the
connection before, use the following:

Example (MySQLi Object-Oriented)


$conn->close();

Example (MySQLi Procedural)


mysqli_close($conn);

Example (PDO)
$conn = null;

PHP Create a MySQL Database


A database consists of one or more tables.

You will need special CREATE privileges to create or to delete a MySQL


database.
Create a MySQL Database Using MySQLi and
PDO
The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Note: When you create a new database, you must only specify the first three
arguments to the mysqli object (servername, username and password).

Tip: If you have to use a specific port, add an empty string for the database-
name argument, like this: new mysqli("localhost", "username", "password", "",
port)
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Note: The following PDO example create a database named "myDBPDO":

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Tip: A great benefit of PDO is that it has exception class to handle any problems
that may occur in our database queries. If an exception is thrown within the
try{ } block, the script stops executing and flows directly to the first catch(){ }
block. In the catch block above we echo the SQL statement and the generated
error message.

PHP Create MySQL Tables


A database table has its own unique name and consists of columns and
rows.

Create a MySQL Table Using MySQLi and PDO


The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)

Notes on the table above:


The data type specifies what type of data the column can hold. For a complete
reference of all the available data types, go to our Data Types reference.

After the data type, you can specify other optional attributes for each column:

 NOT NULL - Each row must contain a value for that column, null values
are not allowed
 DEFAULT value - Set a default value that is added when no other value is
passed
 UNSIGNED - Used for number types, limits the stored data to positive
numbers and zero
 AUTO INCREMENT - MySQL automatically increases the value of the field
by 1 each time a new record is added
 PRIMARY KEY - Used to uniquely identify the rows in a table. The column
with PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT

Each table should have a primary key column (in this case: the "id" column). Its
value must be unique for each record in the table.

The following examples shows how to create the table in PHP:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

// use exec() because no results are returned


$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
PHP Insert Data Into MySQL
Insert Data Into MySQL Using MySQLi and
PDO
After a database and a table have been created, we can start adding data in
them.

Here are some syntax rules to follow:

 The SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.

In the previous chapter we created an empty table named "MyGuests" with five
columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill
the table with data.

Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP


(like the "reg_date" column), it is no need to be specified in the SQL query;
MySQL will automatically add the value.

The following examples add a new record to the "MyGuests" table:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

PHP Get ID of Last Inserted Record


Get ID of The Last Inserted Record
If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field,
we can get the ID of the last inserted/updated record immediately.

In the table "MyGuests", the "id" column is an AUTO_INCREMENT field:


CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)

The following examples are equal to the examples from the previous page (PHP
Insert Data Into MySQL), except that we have added one single line of code to
retrieve the ID of the last inserted record. We also echo the last inserted ID:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

PHP Insert Multiple Records Into


MySQL
Insert Multiple Records Into MySQL Using
MySQLi and PDO
Multiple SQL statements must be executed with
the mysqli_multi_query() function.

The following examples add three new records to the "MyGuests" table:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if ($conn->multi_query($sql) === TRUE) {


echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Note that each SQL statement must be separated by a semicolon.

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

The PDO way is a little bit different:

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// begin the transaction


$conn->beginTransaction();
// our SQL statements
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')");

// commit the transaction


$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}

$conn = null;
?>

PHP Prepared Statements


Prepared statements are very useful against SQL injections.

Prepared Statements and Bound Parameters


A prepared statement is a feature used to execute the same (or similar) SQL
statements repeatedly with high efficiency.

Prepared statements basically work like this:

1. Prepare: An SQL statement template is created and sent to the database.


Certain values are left unspecified, called parameters (labeled "?").
Example: INSERT INTO MyGuests VALUES(?, ?, ?)
2. The database parses, compiles, and performs query optimization on the
SQL statement template, and stores the result without executing it
3. Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values

Compared to executing SQL statements directly, prepared statements have


three main advantages:

 Prepared statements reduce parsing time as the preparation on the query


is done only once (although the statement is executed multiple times)
 Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
 Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different protocol,
need not be correctly escaped. If the original statement template is not
derived from external input, SQL injection cannot occur.

Prepared Statements in MySQLi


The following example uses prepared statements and bound parameters in
MySQLi:

Example (MySQLi with Prepared Statements)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// prepare and bind


$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute


$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?>

Code lines to explain from the example above:

"INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"

In our SQL, we insert a question mark (?) where we want to substitute in an


integer, string, double or blob value.

Then, have a look at the bind_param() function:

$stmt->bind_param("sss", $firstname, $lastname, $email);

This function binds the parameters to the SQL query and tells the database
what the parameters are. The "sss" argument lists the types of data that the
parameters are. The s character tells mysql that the parameter is a string.

The argument may be one of four types:

 i - integer
 d - double
 s - string
 b - BLOB

We must have one of these for each parameter.

By telling mysql what type of data to expect, we minimize the risk of SQL
injections.

Note: If we want to insert any data from external sources (like user input), it is
very important that the data is sanitized and validated.

Prepared Statements in PDO


The following example uses prepared statements and bound parameters in
PDO:

Example (PDO with Prepared Statements)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters


$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname,
email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

// insert another row


$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

// insert another row


$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

PHP Select Data From MySQL


Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

To learn more about SQL, please visit our SQL tutorial.

Select Data With MySQLi


The following example selects the id, firstname and lastname columns from the
MyGuests table and displays it on the page:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Code lines to explain from the example above:

First, we set up an SQL query that selects the id, firstname and lastname
columns from the MyGuests table. The next line of code runs the query and puts
the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows
returned.

If there are more than zero rows returned, the function fetch_assoc() puts all
the results into an associative array that we can loop through. The while() loop
loops through the result set and outputs the data from the id, firstname and
lastname columns.

The following example shows the same as the example above, in the MySQLi
procedural way:

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

You can also put the result in an HTML table:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]."
".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

Select Data With PDO (+ Prepared Statements)


The following example uses prepared statements.

It selects the id, firstname and lastname columns from the MyGuests table and
displays it in an HTML table:

Example (PDO)
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {


function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width:150px;border:1px solid black;'>" .
parent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();

// set the resulting array to associative


$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt-
>fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

PHP Delete Data From MySQL


Delete Data From a MySQL Table Using
MySQLi and PDO
The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value
Notice the WHERE clause in the DELETE syntax: The WHERE clause
specifies which record or records that should be deleted. If you omit the WHERE
clause, all records will be deleted!

To learn more about SQL, please visit our SQL tutorial.

Let's look at the "MyGuests" table:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22


14:26:15

2 Mary Moe mary@example.com 2014-10-23


10:22:30

3 Julie Dooley julie@example.com 2014-10-26


10:48:23

The following examples delete the record with id=3 in the "MyGuests" table:

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

// use exec() because no results are returned


$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

After the record is deleted, the table will look like this:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15


2 Mary Moe mary@example.com 2014-10-23 10:22:30

PHP Update Data in MySQL


Update Data In a MySQL Table Using MySQLi
and PDO
The UPDATE statement is used to update existing records in a table:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Notice the WHERE clause in the UPDATE syntax: The WHERE clause
specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!

To learn more about SQL, please visit our SQL tutorial.

Let's look at the "MyGuests" table:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Moe mary@example.com 2014-10-23 10:22:30

The following examples update the record with id=2 in the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";


if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

// Prepare statement
$stmt = $conn->prepare($sql);

// execute the query


$stmt->execute();

// echo a message to say the UPDATE succeeded


echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
After the record is updated, the table will look like this:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Doe mary@example.com 2014-10-23 10:22:30

PHP Limit Data Selections From MySQL


Limit Data Selections From a MySQL Database
MySQL provides a LIMIT clause that is used to specify the number of records to
return.

The LIMIT clause makes it easy to code multi page results or pagination with
SQL, and is very useful on large tables. Returning a large number of records can
impact on performance.

Assume we wish to select all records from 1 - 30 (inclusive) from a table called
"Orders". The SQL query would then look like this:

$sql = "SELECT * FROM Orders LIMIT 30";

When the SQL query above is run, it will return the first 30 records.

What if we want to select records 16 - 25 (inclusive)?

Mysql also provides a way to handle this: by using OFFSET.

The SQL query below says "return only 10 records, start on record 16 (OFFSET
15)":

$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";


You could also use a shorter syntax to achieve the same result:

$sql = "SELECT * FROM Orders LIMIT 15, 10";

Notice that the numbers are reversed when you use a comma.
PHP XML Parsers
What is XML?
The XML language is a way to structure data for sharing across websites.

Several web technologies like RSS Feeds and Podcasts are written in XML.

XML is easy to create. It looks a lot like HTML, except that you make up your
own tags.

If you want to learn more about XML, please visit our XML tutorial.

What is an XML Parser?


To read and update, create and manipulate an XML document, you will need an
XML parser.

In PHP there are two major types of XML parsers:

 Tree-Based Parsers
 Event-Based Parsers

Tree-Based Parsers
Tree-based parsers holds the entire document in Memory and transforms the
XML document into a Tree structure. It analyzes the whole document, and
provides access to the Tree elements (DOM).

This type of parser is a better option for smaller XML documents, but not for
large XML document as it causes major performance issues.

Example of tree-based parsers:

 SimpleXML
 DOM
Event-Based Parsers
Event-based parsers do not hold the entire document in Memory, instead, they
read in one node at a time and allow you to interact with in real time. Once you
move onto the next node, the old one is thrown away.

This type of parser is well suited for large XML documents. It parses faster and
consumes less memory.

Example of event-based parsers:

 XMLReader
 XML Expat Parser

PHP SimpleXML Parser


SimpleXML is a PHP extension that allows us to easily manipulate and get
XML data.

The SimpleXML Parser


SimpleXML is a tree-based parser.

SimpleXML provides an easy way of getting an element's name, attributes and


textual content if you know the XML document's structure or layout.

SimpleXML turns an XML document into a data structure you can iterate
through like a collection of arrays and objects.

Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code
to read text data from an element.

Installation
As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is
required to use these functions.

PHP SimpleXML - Read From String


The PHP simplexml_load_string() function is used to read XML data from a
string.

Assume we have a variable that contains XML data, like this:

$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

The example below shows how to use the simplexml_load_string() function


to read XML data from a string:

Example
<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");


print_r($xml);
?>

Run example »

The output of the code above will be:


SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder
[body] => Don't forget me this weekend! )

Error Handling Tip: Use the libxml functionality to retrieve all XML errors when
loading the document and then iterate over the errors. The following example
tries to load a broken XML string:

Example
<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john@example.com</wrongemail>
</document>";

$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
print_r($xml);
}
?>

The output of the code above will be:

Failed loading XML:


Opening and ending tag mismatch: user line 3 and wronguser
Opening and ending tag mismatch: email line 4 and wrongemail

PHP SimpleXML - Read From File


The PHP simplexml_load_file() function is used to read XML data from a file.

Assume we have an XML file called "note.xml", that looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example below shows how to use the simplexml_load_file() function to


read XML data from a file:

Example
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>

The output of the code above will be:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder
[body] => Don't forget me this weekend! )

Tip: The next chapter shows how to get/retrieve node values from an XML file
with SimpleXML!

PHP SimpleXML - Get Node/Attribute


Values
SimpleXML is a PHP extension that allows us to easily manipulate and get
XML data.

PHP SimpleXML - Get Node Values


Get the node values from the "note.xml" file:
Example
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

The output of the code above will be:

Tove
Jani
Reminder
Don't forget me this weekend!

Another XML File


Assume we have an XML file called "books.xml", that looks like this:

<?xml version="1.0" encoding="utf-8"?>


<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en-us">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en-us">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

PHP SimpleXML - Get Node Values of Specific


Elements
The following example gets the node value of the <title> element in the first
and second <book> elements in the "books.xml" file:

Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]->title . "<br>";
echo $xml->book[1]->title;
?>

The output of the code above will be:

Everyday Italian
Harry Potter

PHP SimpleXML - Get Node Values - Loop


The following example loops through all the <book> elements in the
"books.xml" file, and gets the node values of the <title>, <author>, <year>,
and <price> elements:

Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title . ", ";
echo $books->author . ", ";
echo $books->year . ", ";
echo $books->price . "<br>";
}
?>

The output of the code above will be:

Everyday Italian, Giada De Laurentiis, 2005, 30.00


Harry Potter, J K. Rowling, 2005, 29.99
XQuery Kick Start, James McGovern, 2003, 49.99
Learning XML, Erik T. Ray, 2003, 39.95

PHP SimpleXML - Get Attribute Values


The following example gets the attribute value of the "category" attribute of the
first <book> element and the attribute value of the "lang" attribute of the
<title> element in the second <book> element:

Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]['category'] . "<br>";
echo $xml->book[1]->title['lang'];
?>

The output of the code above will be:

COOKING
en

PHP SimpleXML - Get Attribute Values - Loop


The following example gets the attribute values of the <title> elements in the
"books.xml" file:
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title['lang'];
echo "<br>";
}
?>

The output of the code above will be:

en
en
en-us
en-us

PHP XML Expat Parser


The built-in XML Expat Parser makes it possible to process XML documents
in PHP.

The XML Expat Parser


The Expat parser is an event-based parser.

Look at the following XML fraction:

<from>Jani</from>

An event-based parser reports the XML above as a series of three events:

 Start element: from


 Start CDATA section, value: Jani
 Close element: from

The XML Expat Parser functions are part of the PHP core. There is no installation
needed to use these functions.
The XML File
The XML file "note.xml" will be used in the example below:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Initializing the XML Expat Parser


We want to initialize the XML Expat Parser in PHP, define some handlers for
different XML events, and then parse the XML file.

Example
<?php
// Initialize the XML parser
$parser=xml_parser_create();

// Function to use at the start of an element


function start($parser,$element_name,$element_attrs) {
switch($element_name) {
case "NOTE":
echo "-- Note --<br>";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}
// Function to use at the end of an element
function stop($parser,$element_name) {
echo "<br>";
}

// Function to use when finding character data


function char($parser,$data) {
echo $data;
}

// Specify element handler


xml_set_element_handler($parser,"start","stop");

// Specify data handler


xml_set_character_data_handler($parser,"char");

// Open XML file


$fp=fopen("note.xml","r");

// Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}

// Free the XML parser


xml_parser_free($parser);
?>

Example explained:

1. Initialize the XML parser with the xml_parser_create() function


2. Create functions to use with the different event handlers
3. Add the xml_set_element_handler() function to specify which function
will be executed when the parser encounters the opening and closing tags
4. Add the xml_set_character_data_handler() function to specify which
function will execute when the parser encounters character data
5. Parse the file "note.xml" with the xml_parse() function
6. In case of an error, add xml_error_string() function to convert an XML
error to a textual description
7. Call the xml_parser_free() function to release the memory allocated
with the xml_parser_create() function

PHP XML DOM Parser


The built-in DOM parser makes it possible to process XML documents in PHP.

The XML DOM Parser


The DOM parser is a tree-based parser.

Look at the following XML document fraction:

<?xml version="1.0" encoding="UTF-8"?>


<from>Jani</from>

The DOM sees the XML above as a tree structure:

 Level 1: XML Document


 Level 2: Root element: <from>
 Level 3: Text element: "Jani"

Installation
The DOM parser functions are part of the PHP core. There is no installation
needed to use these functions.

The XML File


The XML file below ("note.xml") will be used in our example:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Load and Output XML


We want to initialize the XML parser, load the xml, and output it:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>

The output of the code above will be:

Tove Jani Reminder Don't forget me this weekend!

If you select "View source" in the browser window, you will see the following
HTML:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example above creates a DOMDocument-Object and loads the XML from
"note.xml" into it.

Then the saveXML() function puts the internal XML document into a string, so
we can output it.

Looping through XML


We want to initialize the XML parser, load the XML, and loop through all
elements of the <note> element:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>

The output of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =

In the example above you see that there are empty text nodes between each
element.

When XML generates, it often contains white-spaces between the nodes. The
XML DOM parser treats these as ordinary elements, and if you are not aware of
them, they sometimes cause problems.
AJAX Introduction
AJAX is about updating parts of a web page, without reloading the whole
page.

What is AJAX?
AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small


amounts of data with the server behind the scenes. This means that it is
possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and


Facebook tabs.

How AJAX Works


AJAX is Based on Internet Standards
AJAX is based on internet standards, and uses a combination of:

 XMLHttpRequest object (to exchange data asynchronously with a server)


 JavaScript/DOM (to display/interact with the information)
 CSS (to style the data)
 XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!

Google Suggest
AJAX was made popular in 2005 by Google, with Google Suggest.

Google Suggest is using AJAX to create a very dynamic web interface: When
you start typing in Google's search box, a JavaScript sends the letters off to a
server and the server returns a list of suggestions.

Start Using AJAX Today


In our PHP tutorial, we will demonstrate how AJAX can update parts of a web
page, without reloading the whole page. The server script will be written in PHP.

PHP - AJAX and PHP


AJAX is used to create more interactive applications.

AJAX PHP Example


The following example will demonstrate how a web page can communicate with
a web server while a user type characters in an input field:
Example
Start typing a name in the input field below:

First name:

Suggestions:

Example Explained
In the example above, when a user types a character in the input field, a
function called "showHint()" is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

Example
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {

document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>


<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the
content of the txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
 Notice that q parameter is added to the url (gethint.php?q="+str)
 And the str variable holds the content of the input field

 The PHP File - "gethint.php"


 The PHP file checks an array of names, and returns the corresponding
name(s) to the browser:
 <?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL


$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct


values
echo $hint === "" ? "no suggestion" : $hint;
?>

PHP - AJAX and MySQL


AJAX can be used for interactive communication with a database.
AJAX Database Example
The following example will demonstrate how a web page can fetch information
from a database with AJAX:

Example

Person info will be listed here...

Example Explained - The MySQL Database


The database table we use in the example above looks like this:

id FirstName LastName Age Hometown Job

1 Peter Griffin 41 Quahog Brewery

2 Lois Griffin 40 Newport Piano Teacher

3 Joseph Swanson 39 Quahog Police Officer

4 Glenn Quagmire 41 Quahog Pilot


Example Explained
In the example above, when a user selects a person in the dropdown list above,
a function called "showUser()" is executed.

The function is triggered by the onchange event.

Here is the HTML code:

Example
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {

document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

Code explanation:

First, check if person is selected. If no person is selected (str == ""), clear the
content of txtHint and exit the function. If a person is selected, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the
dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called
"getuser.php".

The source code in "getuser.php" runs a query against a MySQL database, and
returns the result in an HTML table:

<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Explanation: When the query is sent from the JavaScript to the PHP file, the
following happens:

1. PHP opens a connection to a MySQL server


2. The correct person is found
3. An HTML table is created, filled with data, and sent back to the "txtHint"
placeholder

PHP Example - AJAX and XML


AJAX can be used for interactive communication with an XML file.

AJAX XML Example


The following example will demonstrate how a web page can fetch information
from an XML file with AJAX:

Example

CD info will be listed here...

Example Explained - The HTML Page


When a user selects a CD in the dropdown list above, a function called
"showCD()" is executed. The function is triggered by the "onchange" event:

<html>
<head>
<script>
function showCD(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcd.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>

</body>
</html>

The showCD() function does the following:

 Check if a CD is selected
 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the
dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called
"getcd.php".

The PHP script loads an XML document, "cd_catalog.xml", runs a query against
the XML file, and returns the result as HTML:

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();


$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++) {


//Process only element nodes
if ($x->item($i)->nodeType==1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y=($x->item($i)->parentNode);
}
}
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++) {
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>

When the CD query is sent from the JavaScript to the PHP page, the following
happens:

1. PHP creates an XML DOM object


2. Find all <artist> elements that matches the name sent from the
JavaScript
3. Output the album information (send to the "txtHint" placeholder)

PHP Example - AJAX Live Search


AJAX can be used to create more user-friendly and interactive searches.

AJAX Live Search


The following example will demonstrate a live search, where you get search
results while you type.

Live search has many benefits compared to traditional searching:

 Results are shown as you type


 Results narrow as you continue typing
 If results become too narrow, remove characters to see a broader result

Search for a W3Schools page in the input field below:

The results in the example above are found in an XML file (links.xml). To make
this example small and simple, only six results are available.

Example Explained - The HTML Page


When a user types a character in the input field above, the function
"showResult()" is executed. The function is triggered by the "onkeyup" event:

<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseTex
t;
document.getElementById("livesearch").style.border="1px solid
#A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>

Source code explanation:

If the input field is empty (str.length==0), the function clears the content of the
livesearch placeholder and exits the function.

If the input field is not empty, the showResult() function executes the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the
input field)
The PHP File
The page on the server called by the JavaScript above is a PHP file called
"livesearch.php".

The source code in "livesearch.php" searches an XML file for titles matching the
search string and returns the result:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL


$q=$_GET["q"];

//lookup all links from the xml file if length of q>0


if (strlen($q)>0) {
$hint="";
for($i=0; $i<($x->length); $i++) {
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1) {
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
if ($hint=="") {
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
} else {
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}

// Set output to "no suggestion" if no hint was found


// or to the correct values
if ($hint=="") {
$response="no suggestion";
} else {
$response=$hint;
}

//output the response


echo $response;
?>

If there is any text sent from the JavaScript (strlen($q) > 0), the following
happens:

 Load an XML file into a new XML DOM object


 Loop through all <title> elements to find matches from the text sent from
the JavaScript
 Sets the correct url and title in the "$response" variable. If more than one
match is found, all matches are added to the variable
 If no matches are found, the $response variable is set to "no suggestion"

PHP Example - AJAX RSS Reader


An RSS Reader is used to read RSS Feeds.

AJAX RSS Reader


The following example will demonstrate an RSS reader, where the RSS-feed is
loaded into a webpage without reloading:

RSS-feed will be listed here...

Example Explained - The HTML Page


When a user selects an RSS-feed in the dropdown list above, a function called
"showRSS()" is executed. The function is triggered by the "onchange" event:
<html>
<head>
<script>
function showRSS(str) {
if (str.length==0) {
document.getElementById("rssOutput").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("rssOutput").innerHTML=this.responseText
;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>

The showRSS() function does the following:

 Check if an RSS-feed is selected


 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the
dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called
"getrss.php":

<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected


if($q=="Google") {
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
} elseif($q=="ZDN") {
$xml=("https://www.zdnet.com/news/rss.xml");
}

$xmlDoc = new DOMDocument();


$xmlDoc->load($xml);

//get elements from "<channel>"


$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"


echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");

//get and output "<item>" elements


$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "</p>");
}
?>

When a request for an RSS feed is sent from the JavaScript, the following
happens:

 Check which feed was selected


 Create a new XML DOM object
 Load the RSS document in the xml variable
 Extract and output elements from the channel element
 Extract and output elements from the item elements

PHP Example - AJAX Poll


AJAX Poll
The following example will demonstrate a poll where the result is shown without
reloading.

Do you like PHP and AJAX so far?


Yes:
No:

Example Explained - The HTML Page


When a user chooses an option above, a function called "getVote()" is executed.
The function is triggered by the "onclick" event:

<html>
<head>
<script>
function getVote(int) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("poll").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>

The getVote() function does the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (vote) is added to the URL (with the value of the
yes or no option)

The PHP File


The page on the server called by the JavaScript above is a PHP file called
"poll_vote.php":
<?php
$vote = $_REQUEST['vote'];

//get content of textfile


$filename = "poll_result.txt";
$content = file($filename);

//put content in array


$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}

//insert votes to txt file


$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

The value is sent from the JavaScript, and the following happens:

1. Get the content of the "poll_result.txt" file


2. Put the content of the file in variables and add one to the selected
variable
3. Write the result to the "poll_result.txt" file
4. Output a graphical representation of the poll result

The Text File


The text file (poll_result.txt) is where we store the data from the poll.

It is stored like this:

0||0

The first number represents the "Yes" votes, the second number represents the
"No" votes.

Note: Remember to allow your web server to edit the text file. Do NOT give
everyone access, just the web server (PHP).
PHP 5 Array Functions
PHP Array Introduction
The array functions allow you to access and manipulate arrays.

Simple and multi-dimensional arrays are supported.

Installation
The array functions are part of the PHP core. There is no installation needed to
use these functions.

PHP 5 Array Functions

Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or


uppercase

array_chunk() Splits an array into chunks of arrays

array_column() Returns the values from a single column in the input


array
array_combine() Creates an array by using the elements from one
"keys" array and one "values" array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare


values only)

array_diff_assoc() Compare arrays, and returns the differences (compare


keys and values)

array_diff_key() Compare arrays, and returns the differences (compare


keys only)

array_diff_uassoc() Compare arrays, and returns the differences (compare


keys and values, using a user-defined key comparison
function)

array_diff_ukey() Compare arrays, and returns the differences (compare


keys only, using a user-defined key comparison
function)

array_fill() Fills an array with values

array_fill_keys() Fills an array with values, specifying keys


array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values


in an array

array_intersect() Compare arrays, and returns the matches (compare


values only)

array_intersect_assoc() Compare arrays and returns the matches (compare


keys and values)

array_intersect_key() Compare arrays, and returns the matches (compare


keys only)

array_intersect_uassoc() Compare arrays, and returns the matches (compare


keys and values, using a user-defined key comparison
function)

array_intersect_ukey() Compare arrays, and returns the matches (compare


keys only, using a user-defined key comparison
function)

array_key_exists() Checks if the specified key exists in the array

array_keys() Returns all the keys of an array


array_map() Sends each value of an array to a user-made function,
which returns new values

array_merge() Merges one or more arrays into one array

array_merge_recursive() Merges one or more arrays into one array recursively

array_multisort() Sorts multiple or multi-dimensional arrays

array_pad() Inserts a specified number of items, with a specified


value, to an array

array_pop() Deletes the last element of an array

array_product() Calculates the product of the values in an array

array_push() Inserts one or more elements to the end of an array

array_rand() Returns one or more random keys from an array

array_reduce() Returns an array as a string, using a user-defined


function
array_replace() Replaces the values of the first array with the values
from following arrays

array_replace_recursive() Replaces the values of the first array with the values
from following arrays recursively

array_reverse() Returns an array in the reverse order

array_search() Searches an array for a given value and returns the


key

array_shift() Removes the first element from an array, and returns


the value of the removed element

array_slice() Returns selected parts of an array

array_splice() Removes and replaces specified elements of an array

array_sum() Returns the sum of the values in an array

array_udiff() Compare arrays, and returns the differences (compare


values only, using a user-defined key comparison
function)

array_udiff_assoc() Compare arrays, and returns the differences (compare


keys and values, using a built-in function to compare
the keys and a user-defined function to compare the
values)

array_udiff_uassoc() Compare arrays, and returns the differences (compare


keys and values, using two user-defined key
comparison functions)

array_uintersect() Compare arrays, and returns the matches (compare


values only, using a user-defined key comparison
function)

array_uintersect_assoc() Compare arrays, and returns the matches (compare


keys and values, using a built-in function to compare
the keys and a user-defined function to compare the
values)

array_uintersect_uassoc() Compare arrays, and returns the matches (compare


keys and values, using two user-defined key
comparison functions)

array_unique() Removes duplicate values from an array

array_unshift() Adds one or more elements to the beginning of an


array

array_values() Returns all the values of an array

array_walk() Applies a user function to every member of an array


array_walk_recursive() Applies a user function recursively to every member of
an array

arsort() Sorts an associative array in descending order,


according to the value

asort() Sorts an associative array in ascending order,


according to the value

compact() Create array containing variables and their values

count() Returns the number of elements in an array

current() Returns the current element in an array

each() Returns the current key and value pair from an array

end() Sets the internal pointer of an array to its last element

extract() Imports variables into the current symbol table from


an array

in_array() Checks if a specified value exists in an array


key() Fetches a key from an array

krsort() Sorts an associative array in descending order,


according to the key

ksort() Sorts an associative array in ascending order,


according to the key

list() Assigns variables as if they were an array

natcasesort() Sorts an array using a case insensitive "natural order"


algorithm

natsort() Sorts an array using a "natural order" algorithm

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer

range() Creates an array containing a range of elements


reset() Sets the internal pointer of an array to its first element

rsort() Sorts an indexed array in descending order

shuffle() Shuffles an array

sizeof() Alias of count()

sort() Sorts an indexed array in ascending order

uasort() Sorts an array by values using a user-defined


comparison function

uksort() Sorts an array by keys using a user-defined


comparison function

usort() Sorts an array using a user-defined comparison


function

Calendar Functions
PHP Calendar Introduction
The calendar extension contains functions that simplifies converting between
different calendar formats.
It is based on the Julian Day Count, which is a count of days starting
from January 1st, 4713 B.C.

Note: To convert between calendar formats, you must first convert to Julian
Day Count, then to the calendar of your choice.

Note: The Julian Day Count is not the same as the Julian Calendar!

Installation
For these functions to work, you have to compile PHP with --enable-calendar.

The Windows version of PHP has built-in support for this extension.

PHP 5 Calendar Functions

Function Description

cal_days_in_month() Returns the number of days in a month for a specified


year and calendar

cal_from_jd() Converts a Julian Day Count into a date of a specified


calendar

cal_info() Returns information about a specified calendar

cal_to_jd() Converts a date in a specified calendar to Julian Day


Count
easter_date() Returns the Unix timestamp for midnight on Easter of
a specified year

easter_days() Returns the number of days after March 21, that the
Easter Day is in a specified year

frenchtojd() Converts a French Republican date to a Julian Day


Count

gregoriantojd() Converts a Gregorian date to a Julian Day Count

jddayofweek() Returns the day of the week

jdmonthname() Returns a month name

jdtofrench() Converts a Julian Day Count to a French Republican


date

jdtogregorian() Converts a Julian Day Count to a Gregorian date

jdtojewish() Converts a Julian Day Count to a Jewish date

jdtojulian() Converts a Julian Day Count to a Julian date


jdtounix() Converts Julian Day Count to Unix timestamp

jewishtojd() Converts a Jewish date to a Julian Day Count

juliantojd() Converts a Julian date to a Julian Day Count

unixtojd() Converts Unix timestamp to Julian Day Count

PHP 5 Predefined Calendar Constants

Constant Type PHP Version

CAL_GREGORIAN Integer PHP 4

CAL_JULIAN Integer PHP 4

CAL_JEWISH Integer PHP 4

CAL_FRENCH Integer PHP 4

CAL_NUM_CALS Integer PHP 4


CAL_DOW_DAYNO Integer PHP 4

CAL_DOW_SHORT Integer PHP 4

CAL_DOW_LONG Integer PHP 4

CAL_MONTH_GREGORIAN_SHORT Integer PHP 4

CAL_MONTH_GREGORIAN_LONG Integer PHP 4

CAL_MONTH_JULIAN_SHORT Integer PHP 4

CAL_MONTH_JULIAN_LONG Integer PHP 4

CAL_MONTH_JEWISH Integer PHP 4

CAL_MONTH_FRENCH Integer PHP 4

CAL_EASTER_DEFAULT Integer PHP 4.3

CAL_EASTER_ROMAN Integer PHP 4.3


CAL_EASTER_ALWAYS_GREGORIAN Integer PHP 4.3

CAL_EASTER_ALWAYS_JULIAN Integer PHP 4.3

CAL_JEWISH_ADD_ALAFIM_GERESH Integer PHP 5.0

CAL_JEWISH_ADD_ALAFIM Integer PHP 5.0

CAL_JEWISH_ADD_GERESHAYIM Integer PHP 5.0

PHP 5 Date/Time Functions


PHP Date/Time Introduction
The date/time functions allow you to get the date and time from the server
where your PHP script runs. You can then use the date/time functions to format
the date and time in several ways.

Note: These functions depend on the locale settings of your server. Remember
to take daylight saving time and leap years into consideration when working
with these functions.

Installation
The PHP date/time functions are part of the PHP core. No installation is required
to use these functions.
Runtime Configuration
The behavior of these functions is affected by settings in php.ini:

Name Description Default PHP


Version

date.timezone The default timezone (used by all date/time "" PHP 5.1
functions)

date.default_latitude The default latitude (used by date_sunrise() and "31.7667" PHP 5.0
date_sunset())

date.default_longitude The default longitude (used by date_sunrise() "35.2333" PHP 5.0


and date_sunset())

date.sunrise_zenith The default sunrise zenith (used by "90.83" PHP 5.0


date_sunrise() and date_sunset())

date.sunset_zenith The default sunset zenith (used by "90.83" PHP 5.0


date_sunrise() and date_sunset())

PHP 5 Date/Time Functions

Function Description
checkdate() Validates a Gregorian date

date_add() Adds days, months, years, hours, minutes, and


seconds to a date

date_create_from_format() Returns a new DateTime object formatted


according to a specified format

date_create() Returns a new DateTime object

date_date_set() Sets a new date

date_default_timezone_get() Returns the default timezone used by all date/time


functions

date_default_timezone_set() Sets the default timezone used by all date/time


functions

date_diff() Returns the difference between two dates

date_format() Returns a date formatted according to a specified


format

date_get_last_errors() Returns the warnings/errors found in a date string


date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of
the string

date_interval_format() Formats the interval

date_isodate_set() Sets the ISO date

date_modify() Modifies the timestamp

date_offset_get() Returns the timezone offset

date_parse_from_format() Returns an associative array with detailed info


about a specified date, according to a specified
format

date_parse() Returns an associative array with detailed info


about a specified date

date_sub() Subtracts days, months, years, hours, minutes, and


seconds from a date

date_sun_info() Returns an array containing info about


sunset/sunrise and twilight begin/end, for a
specified day and location
date_sunrise() Returns the sunrise time for a specified day and
location

date_sunset() Returns the sunset time for a specified day and


location

date_time_set() Sets the time

date_timestamp_get() Returns the Unix timestamp

date_timestamp_set() Sets the date and time based on a Unix timestamp

date_timezone_get() Returns the time zone of the given DateTime


object

date_timezone_set() Sets the time zone for the DateTime object

date() Formats a local date and time

getdate() Returns date/time information of a timestamp or


the current local date/time

gettimeofday() Returns the current time


gmdate() Formats a GMT/UTC date and time

gmmktime() Returns the Unix timestamp for a GMT date

gmstrftime() Formats a GMT/UTC date and time according to


locale settings

idate() Formats a local time/date as integer

localtime() Returns the local time

microtime() Returns the current Unix timestamp with


microseconds

mktime() Returns the Unix timestamp for a date

strftime() Formats a local time and/or date according to


locale settings

strptime() Parses a time/date generated with strftime()

strtotime() Parses an English textual datetime into a Unix


timestamp
time() Returns the current time as a Unix timestamp

timezone_abbreviations_list() Returns an associative array containing dst, offset,


and the timezone name

timezone_identifiers_list() Returns an indexed array with all timezone


identifiers

timezone_location_get() Returns location information for a specified


timezone

timezone_name_from_ abbr() Returns the timezone name from abbreviation

timezone_name_get() Returns the name of the timezone

timezone_offset_get() Returns the timezone offset from GMT

timezone_open() Creates new DateTimeZone object

timezone_transitions_get() Returns all transitions for the timezone

timezone_version_get() Returns the version of the timezone db


PHP 5 Predefined Date/Time Constants

Constant Description

DATE_ATOM Atom (example: 2005-08-15T16:13:03+0000)

DATE_COOKIE HTTP Cookies (example: Sun, 14 Aug 2005


16:13:03 UTC)

DATE_ISO8601 ISO-8601 (example: 2005-08-


14T16:13:03+0000)

DATE_RFC822 RFC 822 (example: Sun, 14 Aug 2005 16:13:03


UTC)

DATE_RFC850 RFC 850 (example: Sunday, 14-Aug-05 16:13:03


UTC)

DATE_RFC1036 RFC 1036 (example: Sunday, 14-Aug-05


16:13:03 UTC)

DATE_RFC1123 RFC 1123 (example: Sun, 14 Aug 2005 16:13:03


UTC)

DATE_RFC2822 RFC 2822 (Sun, 14 Aug 2005 16:13:03 +0000)


DATE_RSS RSS (Sun, 14 Aug 2005 16:13:03 UTC)

DATE_W3C World Wide Web Consortium (example: 2005-08-


14T16:13:03+0000)

PHP 5 Directory Functions


PHP Directory Introduction
The directory functions allow you to retrieve information about directories and
their contents.

Installation
The PHP directory functions are part of the PHP core. No installation is required
to use these functions.

PHP 5 Directory Functions

Function Description

chdir() Changes the current directory


chroot() Changes the root directory

closedir() Closes a directory handle

dir() Returns an instance of the Directory class

getcwd() Returns the current working directory

opendir() Opens a directory handle

readdir() Returns an entry from a directory handle

rewinddir() Resets a directory handle

scandir() Returns an array of files and directories of a specified directory

PHP 5 Error Functions


PHP Error Introduction
The error functions are used to deal with error handling and logging.

The error functions allow us to define own error handling rules, and modify the
way the errors can be logged.

The logging functions allow us to send messages directly to other machines,


emails, or system logs.
The error reporting functions allow us to customize what level and kind of error
feedback is given.

Installation
The PHP error functions are part of the PHP core. No installation is required to
use these functions.

Runtime Configuration
The behavior of the error functions is affected by settings in php.ini.

Errors and logging configuration options:

Name Default Description Changeable

error_reporting NULL Sets the error reporting level (either an PHP_INI_ALL


integer or named constants)

display_errors "1" Specifies whether errors should be PHP_INI_ALL


printed to the screen, or if they should be
hidden from the user.
Note: This feature should never be used
on production systems (only to support
your development)

display_startup_errors "0" Even when display_errors is on, errors PHP_INI_ALL


that occur during PHP's startup sequence
are not displayed
Note: It is strongly recommended to keep
display_startup_errors off, except for
debugging

log_errors "0" Defines whether script error messages PHP_INI_ALL


should be logged to the server's error log
or error_log.
Note: It is strongly advised to use error
logging instead of error displaying on
production web sites

log_errors_max_len "1024" Sets the maximum length of log_errors in PHP_INI_ALL


bytes. The value "0" can be used to not
apply any maximum length at all. This
length is applied to logged errors,
displayed errors, and also to
$php_errormsg (available since PHP 4.3)

ignore_repeated_errors "0" Specifies whether to log repeated error PHP_INI_ALL


messages. When set to "1" it will not log
errors with repeated errors from the same
file on the same line (available since PHP
4.3)

ignore_repeated_source "0" Specifies whether to log repeated error PHP_INI_ALL


messages. When set to "1" it will not log
errors with repeated errors from different
files or source lines (available since PHP
4.3)

report_memleaks "1" If set to "1" (the default), this parameter PHP_INI_ALL


will show a report of memory leaks
detected by the Zend memory manager
(available since PHP 4.3)
track_errors "0" If set to "1", the last error message will PHP_INI_ALL
always be present in the variable
$php_errormsg

html_errors "1" Turns off HTML tags in error messages PHP_INI_ALL


PHP_INI_SYSTEM
in PHP <= 4.2.3.

xmlrpc_errors "0" Turns off normal error reporting and PHP_INI_SYSTEM


formats errors as XML-RPC error
message (available since PHP 4.1)

xmlrpc_error_number "0" Used as the value of the XML-RPC PHP_INI_ALL


faultCode element (available since PHP
4.1)

docref_root "" (available since PHP 4.3) PHP_INI_ALL

docref_ext "" (available since PHP 4.3.2) PHP_INI_ALL

error_prepend_string NULL Specifies a string to output before an PHP_INI_ALL


error message

error_append_string NULL Specifies a string to output after an error PHP_INI_ALL


message

error_log NULL Specifies the name of the file where PHP_INI_ALL


script errors should be logged. The file
should be writable by the web server's
user. If the special value syslog is used,
the errors are sent to the system logger
instead

PHP Error and Logging Functions

Function Description

debug_backtrace() Generates a backtrace

debug_print_backtrace() Prints a backtrace

error_get_last() Returns the last error that occurred

error_log() Sends an error message to a log, to a file, or to


a mail account

error_reporting() Specifies which errors are reported

restore_error_handler() Restores the previous error handler

restore_exception_handler() Restores the previous exception handler

set_error_handler() Sets a user-defined error handler function


set_exception_handler() Sets a user-defined exception handler function

trigger_error() Creates a user-level error message

user_error() Alias of trigger_error()

PHP 5 Predefined Error and Logging Constants

Value Constant Description

1 E_ERROR Fatal run-time errors. Errors that cannot be recovered from.


Execution of the script is halted

2 E_WARNING Run-time warnings (non-fatal errors). Execution of the


script is not halted

4 E_PARSE Compile-time parse errors. Parse errors should only be


generated by the parser

8 E_NOTICE Run-time notices. The script found something that might be


an error, but could also happen when running a script
normally

16 E_CORE_ERROR Fatal errors at PHP startup. This is like E_ERROR, except


it is generated by the core of PHP
32 E_CORE_WARNING Non-fatal errors at PHP startup. This is like E_WARNING,
except it is generated by the core of PHP

64 E_COMPILE_ERROR Fatal compile-time errors. This is like E_ERROR, except it


is generated by the Zend Scripting Engine

128 E_COMPILE_WARNING Non-fatal compile-time errors. This is like E_WARNING,


except it is generated by the Zend Scripting Engine

256 E_USER_ERROR Fatal user-generated error. This is like E_ERROR, except it


is generated in PHP code by using the PHP function
trigger_error()

512 E_USER_WARNING Non-fatal user-generated warning. This is like


E_WARNING, except it is generated in PHP code by using
the PHP function trigger_error()

1024 E_USER_NOTICE User-generated notice. This is like E_NOTICE, except it is


generated in PHP code by using the PHP function
trigger_error()

2048 E_STRICT Enable to have PHP suggest changes to your code which
will ensure the best interoperability and forward
compatibility of your code (Since PHP 5 but not included
in E_ALL until PHP 5.4)

4096 E_RECOVERABLE_ERROR Catchable fatal error. Indicates that a probably dangerous


error occurred, but did not leave the Engine in an unstable
state. If the error is not caught by a user defined handle, the
application aborts as it was an E_ERROR (Since PHP 5.2)

8192 E_DEPRECATED Run-time notices. Enable this to receive warnings about


code that will not work in future versions (Since PHP 5.3)

16384 E_USER_DEPRECATED User-generated warning message. This is like


E_DEPRECATED, except it is generated in PHP code by
using the PHP function trigger_error() (Since PHP 5.3)

32767 E_ALL Enable all PHP errors and warnings (except E_STRICT in
versions < 5.4)

Filesystem Functions
PHP Filesystem Introduction
The filesystem functions allow you to access and manipulate the filesystem.

Installation
The filesystem functions are part of the PHP core. There is no installation
needed to use these functions.

Unix / Windows Compatibility


When specifying a path on Unix platforms, a forward slash (/) is used as
directory separator.

On Windows platforms, both forward slash (/) and backslash (\) can be used.
Runtime Configuration
The behavior of the filesystem functions is affected by settings in php.ini.

Filesystem configuration options:

Name Default Description Changeable

allow_url_fopen "1" Allows fopen()-type functions to work PHP_INI_SYSTEM


with URLs (available since PHP 4.0.4)

user_agent NULL Defines the user agent for PHP to send PHP_INI_ALL
(available since PHP 4.3)

default_socket_timeout "60" Sets the default timeout, in seconds, for PHP_INI_ALL


socket based streams (available since
PHP 4.3)

from "" Defines the anonymous FTP password PHP_INI_ALL


(your email address)

auto_detect_line_endings "0" When set to "1", PHP will examine the PHP_INI_ALL
data read by fgets() and file() to see if it
is using Unix, MS-Dos or Mac line-
ending characters (available since PHP
4.3)
PHP 5 Filesystem Functions

Function Description

basename() Returns the filename component of a path

chgrp() Changes the file group

chmod() Changes the file mode

chown() Changes the file owner

clearstatcache() Clears the file status cache

copy() Copies a file

delete() See unlink() or unset()

dirname() Returns the directory name component of a path

disk_free_space() Returns the free space of a directory


disk_total_space() Returns the total size of a directory

diskfreespace() Alias of disk_free_space()

fclose() Closes an open file

feof() Tests for end-of-file on an open file

fflush() Flushes buffered output to an open file

fgetc() Returns a character from an open file

fgetcsv() Parses a line from an open file, checking for CSV fields

fgets() Returns a line from an open file

fgetss() Returns a line, with HTML and PHP tags removed, from
an open file

file() Reads a file into an array

file_exists() Checks whether or not a file or directory exists


file_get_contents() Reads a file into a string

file_put_contents() Writes a string to a file

fileatime() Returns the last access time of a file

filectime() Returns the last change time of a file

filegroup() Returns the group ID of a file

fileinode() Returns the inode number of a file

filemtime() Returns the last modification time of a file

fileowner() Returns the user ID (owner) of a file

fileperms() Returns the permissions of a file

filesize() Returns the file size

filetype() Returns the file type


flock() Locks or releases a file

fnmatch() Matches a filename or string against a specified


pattern

fopen() Opens a file or URL

fpassthru() Reads from an open file, until EOF, and writes the
result to the output buffer

fputcsv() Formats a line as CSV and writes it to an open file

fputs() Alias of fwrite()

fread() Reads from an open file

fscanf() Parses input from an open file according to a specified


format

fseek() Seeks in an open file

fstat() Returns information about an open file


ftell() Returns the current position in an open file

ftruncate() Truncates an open file to a specified length

fwrite() Writes to an open file

glob() Returns an array of filenames / directories matching a


specified pattern

is_dir() Checks whether a file is a directory

is_executable() Checks whether a file is executable

is_file() Checks whether a file is a regular file

is_link() Checks whether a file is a link

is_readable() Checks whether a file is readable

is_uploaded_file() Checks whether a file was uploaded via HTTP POST

is_writable() Checks whether a file is writeable


is_writeable() Alias of is_writable()

lchgrp() Changes group ownership of symlink

lchown() Changes user ownership of symlink

link() Creates a hard link

linkinfo() Returns information about a hard link

lstat() Returns information about a file or symbolic link

mkdir() Creates a directory

move_uploaded_file() Moves an uploaded file to a new location

parse_ini_file() Parses a configuration file

parse_ini_string() Parses a configuration string

pathinfo() Returns information about a file path


pclose() Closes a pipe opened by popen()

popen() Opens a pipe

readfile() Reads a file and writes it to the output buffer

readlink() Returns the target of a symbolic link

realpath() Returns the absolute pathname

realpath_cache_get() Returns realpath cache entries

realpath_cache_size() Returns realpath cache size

rename() Renames a file or directory

rewind() Rewinds a file pointer

rmdir() Removes an empty directory

set_file_buffer() Sets the buffer size of an open file


stat() Returns information about a file

symlink() Creates a symbolic link

tempnam() Creates a unique temporary file

tmpfile() Creates a unique temporary file

touch() Sets access and modification time of a file

umask() Changes file permissions for files

unlink() Deletes a file

Filter Functions
PHP Filter Introduction
This PHP filters is used to validate and filter data coming from insecure sources,
like user input.

Installation
As of PHP 5.2.0, the filter functions are enabled by default. There is no
installation needed to use these functions.
Runtime Configurations
The behavior of these functions is affected by settings in php.ini:

Name Description

filter.default Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. A
the filter you like to use by default. See the filter list for the list of the filter names

filter.default_flags Default flags to apply when the default filter is set. This is set to FILTER_FLAG_NO_ENC
default for backwards compatibility reasons

PHP 5 Filter Functions

Function Description

filter_has_var() Checks if a variable of a specified input type exist

filter_id() Returns the filter ID of a specified filter name

filter_input() Gets an external variable (e.g. from form input) and


optionally filters it

filter_input_array() Gets external variables (e.g. from form input) and optionally
filters them

filter_list() Returns a list of all supported filters

filter_var_array() Gets multiple variables and filter them

filter_var() Filters a variable with a specified filter

PHP 5 Predefined Filter Constants

Constant ID Description

FILTER_VALIDATE_BOOLEAN 258 Validates a boolean

FILTER_VALIDATE_EMAIL 274 Validates an e-mail address

FILTER_VALIDATE_FLOAT 259 Validates a float

FILTER_VALIDATE_INT 257 Validates an integer

FILTER_VALIDATE_IP 275 Validates an IP address

FILTER_VALIDATE_REGEXP 272 Validates a regular expression


FILTER_VALIDATE_URL 273 Validates a URL

FILTER_SANITIZE_EMAIL 517 Removes all illegal characters from an e-


mail address

FILTER_SANITIZE_ENCODED 514 Removes/Encodes special characters

FILTER_SANITIZE_MAGIC_QUOTES 521 Apply addslashes()

FILTER_SANITIZE_NUMBER_FLOAT 520 Remove all characters, except digits, +-


and optionally .,eE

FILTER_SANITIZE_NUMBER_INT 519 Removes all characters except digits and +


-

FILTER_SANITIZE_SPECIAL_CHARS 515 Removes special characters

FILTER_SANITIZE_FULL_SPECIAL_CHARS

FILTER_SANITIZE_STRING 513 Removes tags/special characters from a


string

FILTER_SANITIZE_STRIPPED 513 Alias of FILTER_SANITIZE_STRING


FILTER_SANITIZE_URL 518 Removes all illegal character from s URL

FILTER_UNSAFE_RAW 516 Do nothing, optionally strip/encode


special characters

FILTER_CALLBACK 1024 Call a user-defined function to filter data

FTP Functions
PHP FTP Introduction
The FTP functions give client access to file servers through the File Transfer
Protocol (FTP).

The FTP functions are used to open, login and close connections, as well as
upload, download, rename, delete, and get information on files from file
servers. Not all of the FTP functions will work with every server or return the
same results. The FTP functions became available with PHP 3.

If you only wish to read from or write to a file on an FTP server, consider using
the ftp:// wrapper with the Filesystem functions which provide a simpler and
more intuitive interface.

Installation
For these functions to work, you have to compile PHP with --enable-ftp.

The Windows version of PHP has built-in support for this extension.
PHP 5 FTP Functions

Function Description

ftp_alloc() Allocates space for a file to be uploaded to the FTP


server

ftp_cdup() Changes to the parent directory on the FTP server

ftp_chdir() Changes the current directory on the FTP server

ftp_chmod() Sets permissions on a file via FTP

ftp_close() Closes an FTP connection

ftp_connect() Opens an FTP connection

ftp_delete() Deletes a file on the FTP server

ftp_exec() Executes a command on the FTP server

ftp_fget() Downloads a file from the FTP server and saves it


into an open local file
ftp_fput() Uploads from an open file and saves it to a file on the
FTP server

ftp_get_option() Returns runtime options of the FTP connection

ftp_get() Downloads a file from the FTP server

ftp_login() Logs in to the FTP connection

ftp_mdtm() Returns the last modified time of a specified file

ftp_mkdir() Creates a new directory on the FTP server

ftp_nb_continue() Continues retrieving/sending a file (non-blocking)

ftp_nb_fget() Downloads a file from the FTP server and saves it


into an open file (non-blocking)

ftp_nb_fput() Uploads from an open file and saves it to a file on the


FTP server (non-blocking)

ftp_nb_get() Downloads a file from the FTP server (non-blocking)


ftp_nb_put() Uploads a file to the FTP server (non-blocking)

ftp_nlist() Returns a list of files in the specified directory on the


FTP server

ftp_pasv() Turns passive mode on or off

ftp_put() Uploads a file to the FTP server

ftp_pwd() Returns the current directory name

ftp_quit() An alias of ftp_close()

ftp_raw() Sends a raw command to the FTP server

ftp_rawlist() Returns a list of files with file information from a


specified directory

ftp_rename() Renames a file or directory on the FTP server

ftp_rmdir() Deletes an empty directory on the FTP server

ftp_set_option() Sets runtime options for the FTP connection


ftp_site() Sends an FTP SITE command to the FTP server

ftp_size() Returns the size of the specified file

ftp_ssl_connect() Opens a secure SSL-FTP connection

ftp_systype() Returns the system type identifier of the FTP server

PHP 5 Predefined FTP Constants

Constant Type PHP

FTP_ASCII Integer PHP 3

FTP_TEXT Integer PHP 3

FTP_BINARY Integer PHP 3

FTP_IMAGE Integer PHP 3

FTP_TIMEOUT_SEC Integer PHP 3


FTP_AUTOSEEK Integer PHP 4.3

FTP_AUTORESUME Integer PHP 4.3

FTP_FAILED Integer PHP 4.3

FTP_FINISHED Integer PHP 4.3

FTP_MOREDATA Integer PHP 4.3

HTTP Functions
PHP HTTP Introduction
The HTTP functions let you manipulate information sent to the browser by the
Web server, before any other output has been sent.

Installation
The HTTP functions are part of the PHP core. There is no installation needed to
use these functions.

PHP 5 HTTP Functions


PHP: indicates the earliest version of PHP that supports the function.
Function Description

header() Sends a raw HTTP header to a client

headers_list() Returns a list of response headers sent (or ready to send)

headers_sent() Checks if / where the HTTP headers have been sent

setcookie() Defines a cookie to be sent along with the rest of the HTTP
headers

setrawcookie() Defines a cookie (without URL encoding) to be sent along


with the rest of the HTTP headers

libxml Functions
PHP libxml Introduction
The libxml functions and constants are used together with SimpleXML, XSLT and
DOM functions.

Installation
These functions require the libxml package. Download at xmlsoft.org
PHP libxml Functions
PHP: indicates the earliest version of PHP that supports the function.

Function Description

libxml_clear_errors() Clear libxml error buffer

libxml_get_errors() Retrieve array of errors

libxml_get_last_error() Retrieve last error from libxml

libxml_set_streams_context() Set the streams context for the next libxml


document load or write

libxml_use_internal_errors() Disable libxml errors and allow user to fetch


error information as needed

PHP 5 Predefined libxml Constants

Function Description

LIBXML_COMPACT Set small nodes allocation optimization. This may


improve the application performance
LIBXML_DTDATTR Set default DTD attributes

LIBXML_DTDLOAD Load external subset

LIBXML_DTDVALID Validate with the DTD

LIBXML_NOBLANKS Remove blank nodes

LIBXML_NOCDATA Set CDATA as text nodes

LIBXML_NOEMPTYTAG Change empty tags (e.g. <br/> to <br></br>),


only available in the DOMDocument->save() and
DOMDocument->saveXML() functions

LIBXML_NOENT Substitute entities

LIBXML_NOERROR Do not show error reports

LIBXML_NONET Stop network access while loading documents

LIBXML_NOWARNING Do not show warning reports

LIBXML_NOXMLDECL Drop the XML declaration when saving a


document

LIBXML_NSCLEAN Remove excess namespace declarations

LIBXML_XINCLUDE Use XInclude substitution

LIBXML_ERR_ERROR Get recoverable errors

LIBXML_ERR_FATAL Get fatal errors

LIBXML_ERR_NONE Get no errors

LIBXML_ERR_WARNING Get simple warnings

LIBXML_VERSION Get libxml version (e.g. 20605 or 20617)

LIBXML_DOTTED_VERSION Get dotted libxml version (e.g. 2.6.5 or 2.6.17)

Mail Functions
PHP Mail Introduction
The mail() function allows you to send emails directly from a script.
Requirements
For the mail functions to be available, PHP requires an installed and working
email system. The program to be used is defined by the configuration settings
in the php.ini file.

Installation
The mail functions are part of the PHP core. There is no installation needed to
use these functions.

Runtime Configuration
The behavior of the mail functions is affected by settings in php.ini:

Name Default Description Changeable

mail.add_x_header "0" Add X-PHP-Originating-Script PHP_INI_PERDIR


that will include UID of the
script followed by the filename.
For PHP 5.3.0 and above

mail.log NULL The path to a log file that will PHP_INI_PERDIR


log all mail() calls. Log include
full path of script, line number,
To address and headers. For
PHP 5.3.0 and above
SMTP "localhost" Windows only: The DNS name PHP_INI_ALL
or IP address of the SMTP
server

smtp_port "25" Windows only: The SMTP port PHP_INI_ALL


number. For PHP 4.3.0 and
above

sendmail_from NULL Windows only: Specifies the PHP_INI_ALL


"from" address to be used when
sending mail from mail()

sendmail_path "/usr/sbin/sendmail - Specifies where the sendmail PHP_INI_SYSTEM


t -i" program can be found. This
directive works also under
Windows. If set, SMTP,
smtp_port and sendmail_from
are ignored

PHP 5 Mail Functions

Function Description

ezmlm_hash() Calculates the hash value needed by EZMLM

mail() Allows you to send emails directly from a script


Math Functions
PHP Math Introduction
The math functions can handle values within the range of integer and float
types.

Installation
The PHP math functions are part of the PHP core. No installation is required to
use these functions.

PHP 5 Math Functions

Function Description

abs() Returns the absolute (positive) value of a number

acos() Returns the arc cosine of a number

acosh() Returns the inverse hyperbolic cosine of a number

asin() Returns the arc sine of a number


asinh() Returns the inverse hyperbolic sine of a number

atan() Returns the arc tangent of a number in radians

atan2() Returns the arc tangent of two variables x and y

atanh() Returns the inverse hyperbolic tangent of a number

base_convert() Converts a number from one number base to another

bindec() Converts a binary number to a decimal number

ceil() Rounds a number up to the nearest integer

cos() Returns the cosine of a number

cosh() Returns the hyperbolic cosine of a number

decbin() Converts a decimal number to a binary number

dechex() Converts a decimal number to a hexadecimal number


decoct() Converts a decimal number to an octal number

deg2rad() Converts a degree value to a radian value

exp() Calculates the exponent of e

expm1() Returns exp(x) - 1

floor() Rounds a number down to the nearest integer

fmod() Returns the remainder of x/y

getrandmax() Returns the largest possible value returned by rand()

hexdec() Converts a hexadecimal number to a decimal number

hypot() Calculates the hypotenuse of a right-angle triangle

is_finite() Checks whether a value is finite or not

is_infinite() Checks whether a value is infinite or not


is_nan() Checks whether a value is 'not-a-number'

lcg_value() Returns a pseudo random number in a range between 0


and 1

log() Returns the natural logarithm of a number

log10() Returns the base-10 logarithm of a number

log1p() Returns log(1+number)

max() Returns the highest value in an array, or the highest value


of several specified values

min() Returns the lowest value in an array, or the lowest value of


several specified values

mt_getrandmax() Returns the largest possible value returned by mt_rand()

mt_rand() Generates a random integer using Mersenne Twister


algorithm

mt_srand() Seeds the Mersenne Twister random number generator


octdec() Converts an octal number to a decimal number

pi() Returns the value of PI

pow() Returns x raised to the power of y

rad2deg() Converts a radian value to a degree value

rand() Generates a random integer

round() Rounds a floating-point number

sin() Returns the sine of a number

sinh() Returns the hyperbolic sine of a number

sqrt() Returns the square root of a number

srand() Seeds the random number generator

tan() Returns the tangent of a number


tanh() Returns the hyperbolic tangent of a number

PHP 5 Predefined Math Constants

Constant Value Description PHP


Version

INF INF The infinite PHP 4

M_E 2.7182818284590452354 Returns e PHP 4

M_EULER 0.57721566490153286061 Returns Euler PHP 4


constant

M_LNPI 1.14472988584940017414 Returns the natural PHP 5.2


logarithm of PI:
log_e(pi)

M_LN2 0.69314718055994530942 Returns the natural PHP 4


logarithm of 2: log_e
2

M_LN10 2.30258509299404568402 Returns the natural PHP 4


logarithm of 10:
log_e 10
M_LOG2E 1.4426950408889634074 Returns the base-2 PHP 4
logarithm of E: log_2
e

M_LOG10E 0.43429448190325182765 Returns the base-10 PHP 4


logarithm of E:
log_10 e

M_PI 3.14159265358979323846 Returns Pi PHP 4

M_PI_2 1.57079632679489661923 Returns Pi/2 PHP 4

M_PI_4 0.78539816339744830962 Returns Pi/4 PHP 4

M_1_PI 0.31830988618379067154 Returns 1/Pi PHP 4

M_2_PI 0.63661977236758134308 Returns 2/Pi PHP 4

M_SQRTPI 1.77245385090551602729 Returns the square PHP 5.2


root of PI: sqrt(pi)

M_2_SQRTPI 1.12837916709551257390 Returns 2/square root PHP 4


of PI: 2/sqrt(pi)

M_SQRT1_2 0.70710678118654752440 Returns the square PHP 4


root of 1/2: 1/sqrt(2)

M_SQRT2 1.41421356237309504880 Returns the square PHP 4


root of 2: sqrt(2)

M_SQRT3 1.73205080756887729352 Returns the square PHP 5.2


root of 3: sqrt(3)

NAN NAN Not A Number PHP 4

PHP_ROUND_HALF_UP 1 Round halves up PHP 5.3

PHP_ROUND_HALF_DOWN 2 Round halves down PHP 5.3

PHP_ROUND_HALF_EVEN 3 Round halves to even PHP 5.3


numbers

PHP_ROUND_HALF_ODD 4 Round halves to odd PHP 5.3


numbers

Misc. Functions
PHP Miscellaneous Introduction
The misc. functions were only placed here because none of the other categories
seemed to fit.
Installation
The misc. functions are part of the PHP core. No installation is required to use
these functions.

Runtime Configuration
The behavior of the misc. functions is affected by settings in the php.ini file.

Misc. configuration options:

Name Description Default Changeable

ignore_user_abort FALSE indicates that scripts will be "0" PHP_INI_ALL


terminated as soon as they try to output
something after a client has aborted their
connection

highlight.string Color for highlighting a string in PHP "#DD0000" PHP_INI_ALL


syntax

highlight.comment Color for highlighting PHP comments "#FF8000" PHP_INI_ALL

highlight.keyword Color for syntax highlighting PHP "#007700" PHP_INI_ALL


keywords (e.g. parenthesis and semicolon)
highlight.bg Removed in PHP 5.4.0. Color for "#FFFFFF" PHP_INI_ALL
background

highlight.default Default color for PHP syntax "#0000BB" PHP_INI_ALL

highlight.html Color for HTML code "#000000" PHP_INI_ALL

browscap Name and location of browser-capabilities NULL PHP_INI_SYSTEM


file (e.g. browscap.ini)

PHP Miscellaneous Functions

Function Description

connection_aborted() Checks whether the client has disconnected

connection_status() Returns the current connection status

connection_timeout() Deprecated in PHP 4.0.5. Checks whether the script


has timed out

constant() Returns the value of a constant


define() Defines a constant

defined() Checks whether a constant exists

die() Prints a message and exits the current script

eval() Evaluates a string as PHP code

exit() Prints a message and exits the current script

get_browser() Returns the capabilities of the user's browser

__halt_compiler() Halts the compiler execution

highlight_file() Outputs a file with the PHP syntax highlighted

highlight_string() Outputs a string with the PHP syntax highlighted

ignore_user_abort() Sets whether a remote client can abort the running


of a script
pack() Packs data into a binary string

php_check_syntax() Deprecated in PHP 5.0.5

php_strip_whitespace() Returns the source code of a file with PHP


comments and whitespace removed

show_source() Alias of highlight_file()

sleep() Delays code execution for a number of seconds

sys_getloadavg() Gets system load average

time_nanosleep() Delays code execution for a number of seconds and


nanoseconds

time_sleep_until() Delays code execution until a specified time

uniqid() Generates a unique ID

unpack() Unpacks data from a binary string


usleep() Delays code execution for a number of
microseconds

PHP 5 Predefined Misc. Constants


PHP: indicates the earliest version of PHP that supports the constant.

Constant Description PHP

CONNECTION_ABORTED

CONNECTION_NORMAL

CONNECTION_TIMEOUT

__COMPILER_HALT_OFFSET__ 5

MySQLi Functions
PHP MySQLi Introduction
PHP MySQLi = PHP MySQL Improved!

The MySQLi functions allows you to access MySQL database servers.

Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or
newer.
Installation / Runtime Configuration
For the MySQLi functions to be available, you must compile PHP with support for
the MySQLi extension.

The MySQLi extension was introduced with PHP version 5.0.0. The MySQL
Native Driver was included in PHP version 5.3.0.

For installation details, go to: http://php.net/manual/en/mysqli.installation.php

For runtime configuration details, go


to: http://php.net/manual/en/mysqli.configuration.php

PHP 5 MySQLi Functions

Function Description

mysqli_affected_rows() Returns the number of affected rows in the previous MySQL


operation

mysqli_autocommit() Turns on or off auto-committing database modifications

mysqli_change_user() Changes the user of the specified database connection

mysqli_character_set_name() Returns the default character set for the database connection
mysqli_close() Closes a previously opened database connection

mysqli_commit() Commits the current transaction

mysqli_connect_errno() Returns the error code from the last connection error

mysqli_connect_error() Returns the error description from the last connection error

mysqli_connect() Opens a new connection to the MySQL server

mysqli_data_seek() Adjusts the result pointer to an arbitrary row in the result-set

mysqli_debug() Performs debugging operations

mysqli_dump_debug_info() Dumps debugging info into the log

mysqli_errno() Returns the last error code for the most recent function call

mysqli_error_list() Returns a list of errors for the most recent function call

mysqli_error() Returns the last error description for the most recent function call
mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or
both

mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both

mysqli_fetch_assoc() Fetches a result row as an associative array

mysqli_fetch_field_direct() Returns meta-data for a single field in the result set, as an object

mysqli_fetch_field() Returns the next field in the result set, as an object

mysqli_fetch_fields() Returns an array of objects that represent the fields in a result set

mysqli_fetch_lengths() Returns the lengths of the columns of the current row in the result
set

mysqli_fetch_object() Returns the current row of a result set, as an object

mysqli_fetch_row() Fetches one row from a result-set and returns it as an enumerated


array

mysqli_field_count() Returns the number of columns for the most recent query
mysqli_field_seek() Sets the field cursor to the given field offset

mysqli_field_tell() Returns the position of the field cursor

mysqli_free_result() Frees the memory associated with a result

mysqli_get_charset() Returns a character set object

mysqli_get_client_info() Returns the MySQL client library version

mysqli_get_client_stats() Returns statistics about client per-process

mysqli_get_client_version() Returns the MySQL client library version as an integer

mysqli_get_connection_stats() Returns statistics about the client connection

mysqli_get_host_info() Returns the MySQL server hostname and the connection type

mysqli_get_proto_info() Returns the MySQL protocol version

mysqli_get_server_info() Returns the MySQL server version


mysqli_get_server_version() Returns the MySQL server version as an integer

mysqli_info() Returns information about the most recently executed query

mysqli_init() Initializes MySQLi and returns a resource for use with


mysqli_real_connect()

mysqli_insert_id() Returns the auto-generated id used in the last query

mysqli_kill() Asks the server to kill a MySQL thread

mysqli_more_results() Checks if there are more results from a multi query

mysqli_multi_query() Performs one or more queries on the database

mysqli_next_result() Prepares the next result set from mysqli_multi_query()

mysqli_num_fields() Returns the number of fields in a result set

mysqli_num_rows() Returns the number of rows in a result set


mysqli_options() Sets extra connect options and affect behavior for a connection

mysqli_ping() Pings a server connection, or tries to reconnect if the connection


has gone down

mysqli_prepare() Prepares an SQL statement for execution

mysqli_query() Performs a query against the database

mysqli_real_connect() Opens a new connection to the MySQL server

mysqli_real_escape_string() Escapes special characters in a string for use in an SQL statement

mysqli_real_query() Executes an SQL query

mysqli_reap_async_query() Returns the result from async query

mysqli_refresh() Refreshes tables or caches, or resets the replication server


information

mysqli_rollback() Rolls back the current transaction for the database


mysqli_select_db() Changes the default database for the connection

mysqli_set_charset() Sets the default client character set

mysqli_set_local_infile_default() Unsets user defined handler for load local infile command

mysqli_set_local_infile_handler() Set callback function for LOAD DATA LOCAL INFILE command

mysqli_sqlstate() Returns the SQLSTATE error code for the last MySQL operation

mysqli_ssl_set() Used to establish secure connections using SSL

mysqli_stat() Returns the current system status

mysqli_stmt_init() Initializes a statement and returns an object for use with


mysqli_stmt_prepare()

mysqli_store_result() Transfers a result set from the last query

mysqli_thread_id() Returns the thread ID for the current connection


mysqli_thread_safe() Returns whether the client library is compiled as thread-safe

mysqli_use_result() Initiates the retrieval of a result set from the last query executed
using the mysqli_real_query()

mysqli_warning_count() Returns the number of warnings from the last query in the
connection

SimpleXML Functions
PHP SimpleXML Introduction
SimpleXML is an extension that allows us to easily manipulate and get XML
data.

SimpleXML provides an easy way of getting an element's name, attributes and


textual content if you know the XML document's structure or layout.

SimpleXML turns an XML document into a data structure you can iterate
through like a collection of arrays and objects.

Installation
As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is
required to use these functions.

PHP 5 SimpleXML Functions


Function Description

__construct() Creates a new SimpleXMLElement object

addAttribute() Adds an attribute to the SimpleXML element

addChild() Adds a child element the SimpleXML element

asXML() Returns a well-formed XML string (XML version 1.0) from a


SimpleXML object

attributes() Returns the attributes/values of an element

children() Returns the children of a specified node

count() Counts the children of a specified node

getDocNamespaces() Returns the namespaces DECLARED in document

getName() Returns the name of the XML tag referenced by the SimpleXML
element
getNamespaces() Returns the namespaces USED in document

registerXPathNamespace() Creates a namespace context for the next XPath query

saveXML() Alias of asXML()

simplexml_import_dom() Returns a SimpleXMLElement object from a DOM node

simplexml_load_file() Converts an XML file into a SimpleXMLElement object

simplexml_load_string() Converts an XML string into a SimpleXMLElement object

xpath() Runs an XPath query on XML data

PHP 5 SimpleXML Iteration Functions

Function Description

current() Returns the current element

getChildren() Returns the child elements of the current element


hasChildren() Checks whether the current element has children

key() Return the current key

next() Moves to the next element

rewind() Rewind to the first element

valid() Check whether the current element is valid

String Functions
PHP 5 String Functions
The PHP string functions are part of the PHP core. No installation is required to
use these functions.

Function Description

addcslashes() Returns a string with backslashes in front of the specified


characters

addslashes() Returns a string with backslashes in front of predefined characters


bin2hex() Converts a string of ASCII characters to hexadecimal values

chop() Removes whitespace or other characters from the right end of a


string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts

convert_cyr_string() Converts a string from one Cyrillic character-set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Returns information about characters used in a string

crc32() Calculates a 32-bit CRC for a string

crypt() One-way string hashing


echo() Outputs one or more strings

explode() Breaks a string into an array

fprintf() Writes a formatted string to a specified output stream

get_html_translation_table() Returns the translation table used by htmlspecialchars() and


htmlentities()

hebrev() Converts Hebrew text to visual text

hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>

hex2bin() Converts a string of hexadecimal values to ASCII characters

html_entity_decode() Converts HTML entities to characters

htmlentities() Converts characters to HTML entities

htmlspecialchars_decode() Converts some predefined HTML entities to characters


htmlspecialchars() Converts some predefined characters to HTML entities

implode() Returns a string from the elements of an array

join() Alias of implode()

lcfirst() Converts the first character of a string to lowercase

levenshtein() Returns the Levenshtein distance between two strings

localeconv() Returns locale numeric and monetary formatting information

ltrim() Removes whitespace or other characters from the left side of a


string

md5() Calculates the MD5 hash of a string

md5_file() Calculates the MD5 hash of a file

metaphone() Calculates the metaphone key of a string


money_format() Returns a string formatted as a currency string

nl_langinfo() Returns specific local information

nl2br() Inserts HTML line breaks in front of each newline in a string

number_format() Formats a number with grouped thousands

ord() Returns the ASCII value of the first character of a string

parse_str() Parses a query string into variables

print() Outputs one or more strings

printf() Outputs a formatted string

quoted_printable_decode() Converts a quoted-printable string to an 8-bit string

quoted_printable_encode() Converts an 8-bit string to a quoted printable string

quotemeta() Quotes meta characters


rtrim() Removes whitespace or other characters from the right side of a
string

setlocale() Sets locale information

sha1() Calculates the SHA-1 hash of a string

sha1_file() Calculates the SHA-1 hash of a file

similar_text() Calculates the similarity between two strings

soundex() Calculates the soundex key of a string

sprintf() Writes a formatted string to a variable

sscanf() Parses input from a string according to a format

str_getcsv() Parses a CSV string into an array

str_ireplace() Replaces some characters in a string (case-insensitive)


str_pad() Pads a string to a new length

str_repeat() Repeats a string a specified number of times

str_replace() Replaces some characters in a string (case-sensitive)

str_rot13() Performs the ROT13 encoding on a string

str_shuffle() Randomly shuffles all characters in a string

str_split() Splits a string into an array

str_word_count() Count the number of words in a string

strcasecmp() Compares two strings (case-insensitive)

strchr() Finds the first occurrence of a string inside another string (alias of
strstr())

strcmp() Compares two strings (case-sensitive)


strcoll() Compares two strings (locale based string comparison)

strcspn() Returns the number of characters found in a string before any part
of some specified characters are found

strip_tags() Strips HTML and PHP tags from a string

stripcslashes() Unquotes a string quoted with addcslashes()

stripslashes() Unquotes a string quoted with addslashes()

stripos() Returns the position of the first occurrence of a string inside


another string (case-insensitive)

stristr() Finds the first occurrence of a string inside another string (case-
insensitive)

strlen() Returns the length of a string

strnatcasecmp() Compares two strings using a "natural order" algorithm (case-


insensitive)

strnatcmp() Compares two strings using a "natural order" algorithm (case-


sensitive)

strncasecmp() String comparison of the first n characters (case-insensitive)

strncmp() String comparison of the first n characters (case-sensitive)

strpbrk() Searches a string for any of a set of characters

strpos() Returns the position of the first occurrence of a string inside


another string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string

strrev() Reverses a string

strripos() Finds the position of the last occurrence of a string inside another
string (case-insensitive)

strrpos() Finds the position of the last occurrence of a string inside another
string (case-sensitive)

strspn() Returns the number of characters found in a string that contains


only characters from a specified charlist
strstr() Finds the first occurrence of a string inside another string (case-
sensitive)

strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

strtr() Translates certain characters in a string

substr() Returns a part of a string

substr_compare() Compares two strings from a specified start position (binary safe
and optionally case-sensitive)

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

trim() Removes whitespace or other characters from both sides of a


string
ucfirst() Converts the first character of a string to uppercase

ucwords() Converts the first character of each word in a string to uppercase

vfprintf() Writes a formatted string to a specified output stream

vprintf() Outputs a formatted string

vsprintf() Writes a formatted string to a variable

wordwrap() Wraps a string to a given number of characters

XML Parser Functions


PHP XML Parser Introduction
The XML functions lets you parse, but not validate, XML documents.

XML is a data format for standardized structured document exchange. More


information on XML can be found in our XML Tutorial.

This extension uses the Expat XML parser.

Expat is an event-based parser, it views an XML document as a series of events.


When an event occurs, it calls a specified function to handle it.
Expat is a non-validating parser, and ignores any DTDs linked to a document.
However, if the document is not well formed it will end with an error message.

Because it is an event-based, non validating parser, Expat is fast and well suited
for web applications.

The XML parser functions lets you create XML parsers and define handlers for
XML events.

Installation
The XML functions are part of the PHP core. There is no installation needed to
use these functions.

PHP XML Parser Functions


PHP: indicates the earliest version of PHP that supports the function.

Function Description PHP

utf8_decode() Decodes an UTF-8 3


string to ISO-8859-
1

utf8_encode() Encodes an ISO- 3


8859-1 string to
UTF-8

xml_error_string() Gets an error string 3


from the XML
parser

xml_get_current_byte_index() Gets the current 3


byte index from
the XML parser

xml_get_current_column_number() Gets the current 3


column number
from the XML
parser

xml_get_current_line_number() Gets the current 3


line number from
the XML parser

xml_get_error_code() Gets an error code 3


from the XML
parser

xml_parse() Parses an XML 3


document

xml_parse_into_struct() Parse XML data 3


into an array

xml_parser_create_ns() Create an XML 4


parser with
namespace
support

xml_parser_create() Create an XML 3


parser

xml_parser_free() Free an XML parser 3

xml_parser_get_option() Get options from 3


an XML parser

xml_parser_set_option() Set options in an 3


XML parser

xml_set_character_data_handler() Set handler 3


function for
character data

xml_set_default_handler() Set default handler 3


function

xml_set_element_handler() Set handler 3


function for start
and end element of
elements

xml_set_end_namespace_decl_handler() Set handler 4


function for the
end of namespace
declarations

xml_set_external_entity_ref_handler() Set handler 3


function for
external entities

xml_set_notation_decl_handler() Set handler 3


function for
notation
declarations

xml_set_object() Use XML Parser 4


within an object

xml_set_processing_instruction_handler() Set handler 3


function for
processing
instruction

xml_set_start_namespace_decl_handler() Set handler 4


function for the
start of namespace
declarations

xml_set_unparsed_entity_decl_handler() Set handler 3


function for
unparsed entity
declarations
PHP XML Parser Constants

Constant

XML_ERROR_NONE (integer)

XML_ERROR_NO_MEMORY (integer)

XML_ERROR_SYNTAX (integer)

XML_ERROR_NO_ELEMENTS (integer)

XML_ERROR_INVALID_TOKEN (integer)

XML_ERROR_UNCLOSED_TOKEN (integer)

XML_ERROR_PARTIAL_CHAR (integer)

XML_ERROR_TAG_MISMATCH (integer)

XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)

XML_ERROR_PARAM_ENTITY_REF (integer)

XML_ERROR_UNDEFINED_ENTITY (integer)

XML_ERROR_RECURSIVE_ENTITY_REF (integer)

XML_ERROR_ASYNC_ENTITY (integer)

XML_ERROR_BAD_CHAR_REF (integer)

XML_ERROR_BINARY_ENTITY_REF (integer)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)

XML_ERROR_MISPLACED_XML_PI (integer)

XML_ERROR_UNKNOWN_ENCODING (integer)

XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)

XML_OPTION_CASE_FOLDING (integer)

XML_OPTION_TARGET_ENCODING (integer)

XML_OPTION_SKIP_TAGSTART (integer)

XML_OPTION_SKIP_WHITE (integer)

Zip File Functions


PHP Zip File Introduction
The Zip files functions allows you to read ZIP files.

Installation
For the Zip file functions to work on your server, these libraries must be
installed:

 The ZZIPlib library by Guido Draheim: Download the ZZIPlib library


 The Zip PECL extension: Download the Zip PECL extension
Installation on Linux Systems

PHP 5+: Zip functions and the Zip library is not enabled by default and must be
downloaded from the links above. Use the --with-zip=DIRconfigure option to
include Zip support.

Installation on Windows Systems

PHP 5+: Zip functions is not enabled by default, so the php_zip.dll and the
ZZIPlib library must be downloaded from the link above. php_zip.dll must be
enabled inside of php.ini.

To enable any PHP extension, the PHP extension_dir setting (in the php.ini file)
should be set to the directory where the PHP extensions are located. An
example extension_dir value is c:\php\ext.

PHP Zip File Functions


PHP: indicates the earliest version of PHP that supports the function.

Function Description PHP

zip_close() Closes a ZIP file 4

zip_entry_close() Closes an entry in the ZIP file 4

zip_entry_compressedsize() Returns the compressed size of an entry in the 4


ZIP file

zip_entry_compressionmethod() Returns the compression method of an entry in 4


the ZIP file
zip_entry_filesize() Returns the actual file size of an entry in the ZIP 4
file

zip_entry_name() Returns the name of an entry in the ZIP file 4

zip_entry_open() Opens an entry in the ZIP file for reading 4

zip_entry_read() Reads from an open entry in the ZIP file 4

zip_open() Opens a ZIP file 4

zip_read() Reads the next entry in a ZIP file 4

PHP 5 Timezones
PHP Supported Timezones
Below is a complete list of the timezones supported by PHP, which are useful
with several PHP date functions.

 Africa
 America
 Antarctica
 Arctic
 Asia
 Atlantic
 Australia
 Europe
 Indian
 Pacific

Africa

Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara

Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau

Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca

Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti

Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare

Africa/Johannesburg Africa/Juba Africa/Kampala Africa/Khartoum Africa/Kigali

Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda

Africa/Lubumbashi Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru

Africa/Mbabane Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena


Africa/Niamey Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome

Africa/Timbuktu Africa/Tripoli Africa/Tunis Africa/Windhoek

America

America/Adak America/Anchorage America/Anguilla

America/Antigua America/Araguaina America/Argentina/Buenos_Ai


res

America/Argentina/Catamar America/Argentina/ComodRiva America/Argentina/Cordoba


ca davia

America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza

America/Argentina/Rio_Gall America/Argentina/Salta America/Argentina/San_Juan


egos

America/Argentina/San_Lui America/Argentina/Tucuman America/Argentina/Ushuaia


s

America/Aruba America/Asuncion America/Atikokan


America/Atka America/Bahia America/Bahia_Banderas

America/Barbados America/Belem America/Belize

America/Blanc-Sablon America/Boa_Vista America/Bogota

America/Boise America/Buenos_Aires America/Cambridge_Bay

America/Campo_Grande America/Cancun America/Caracas

America/Catamarca America/Cayenne America/Cayman

America/Chicago America/Chihuahua America/Coral_Harbour

America/Cordoba America/Costa_Rica America/Creston

America/Cuiaba America/Curacao America/Danmarkshavn

America/Dawson America/Dawson_Creek America/Denver

America/Detroit America/Dominica America/Edmonton


America/Eirunepe America/El_Salvador America/Ensenada

America/Fort_Wayne America/Fortaleza America/Glace_Bay

America/Godthab America/Goose_Bay America/Grand_Turk

America/Grenada America/Guadeloupe America/Guatemala

America/Guayaquil America/Guyana America/Halifax

America/Havana America/Hermosillo America/Indiana/Indianapolis

America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg

America/Indiana/Tell_City America/Indiana/Vevay America/Indiana/Vincennes

America/Indiana/Winamac America/Indianapolis America/Inuvik

America/Iqaluit America/Jamaica America/Jujuy

America/Juneau America/Kentucky/Louisville America/Kentucky/Monticello


America/Knox_IN America/Kralendijk America/La_Paz

America/Lima America/Los_Angeles America/Louisville

America/Lower_Princes America/Maceio America/Managua

America/Manaus America/Marigot America/Martinique

America/Matamoros America/Mazatlan America/Mendoza

America/Menominee America/Merida America/Metlakatla

America/Mexico_City America/Miquelon America/Moncton

America/Monterrey America/Montevideo America/Montreal

America/Montserrat America/Nassau America/New_York

America/Nipigon America/Nome America/Noronha

America/North_Dakota/Beul America/North_Dakota/Center America/North_Dakota/New_S


ah alem
America/Ojinaga America/Panama America/Pangnirtung

America/Paramaribo America/Phoenix America/Port-au-Prince

America/Port_of_Spain America/Porto_Acre America/Porto_Velho

America/Puerto_Rico America/Rainy_River America/Rankin_Inlet

America/Recife America/Regina America/Resolute

America/Rio_Branco America/Rosario America/Santa_Isabel

America/Santarem America/Santiago America/Santo_Domingo

America/Sao_Paulo America/Scoresbysund America/Shiprock

America/Sitka America/St_Barthelemy America/St_Johns

America/St_Kitts America/St_Lucia America/St_Thomas

America/St_Vincent America/Swift_Current America/Tegucigalpa


America/Thule America/Thunder_Bay America/Tijuana

America/Toronto America/Tortola America/Vancouver

America/Virgin America/Whitehorse America/Winnipeg

America/Yakutat America/Yellowknife

Antarctica

Antarctica/Casey Antarctica/Da Antarctica/DumontDU Antarctica/Macqu Antarctica/Maw


vis rville arie son

Antarctica/McM Antarctica/Pal Antarctica/Rothera Antarctica/South_ Antarctica/Syo


urdo mer Pole wa

Antarctica/Vosto
k

Arctic

Arctic/Longyearbyen
Asia

Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau

Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain

Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei

Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo

Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai

Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Hebron Asia/Ho_Chi_Minh

Asia/Hong_Kong Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta

Asia/Jayapura Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi

Asia/Kashgar Asia/Kathmandu Asia/Katmandu Asia/Khandyga Asia/Kolkata

Asia/Krasnoyarsk Asia/Kuala_Lumpur Asia/Kuching Asia/Kuwait Asia/Macao


Asia/Macau Asia/Magadan Asia/Makassar Asia/Manila Asia/Muscat

Asia/Nicosia Asia/Novokuznetsk Asia/Novosibirsk Asia/Omsk Asia/Oral

Asia/Phnom_Penh Asia/Pontianak Asia/Pyongyang Asia/Qatar Asia/Qyzylorda

Asia/Rangoon Asia/Riyadh Asia/Saigon Asia/Sakhalin Asia/Samarkand

Asia/Seoul Asia/Shanghai Asia/Singapore Asia/Taipei Asia/Tashkent

Asia/Tbilisi Asia/Tehran Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu

Asia/Tokyo Asia/Ujung_Pandang Asia/Ulaanbaatar Asia/Ulan_Bator Asia/Urumqi

Asia/Ust-Nera Asia/Vientiane Asia/Vladivostok Asia/Yakutsk Asia/Yekaterinburg

Asia/Yerevan

Atlantic

Atlantic/Azores Atlantic/Bermuda Atlantic/Canar Atlantic/Cape_Ver Atlantic/Faeroe


y de
Atlantic/Faroe Atlantic/Jan_May Atlantic/Madei Atlantic/Reykjavi Atlantic/South_Geor
en ra k gia

Atlantic/St_Hele Atlantic/Stanley
na

Australia

Australia/ACT Australia/Adelaid Australia/Brisbane Australia/Broken_ Australia/Canbe


e Hill rra

Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI

Australia/Linde Australia/Lord_H Australia/Melbour Australia/North Australia/NSW


man owe ne

Australia/Perth Australia/Queensl Australia/South Australia/Sydney Australia/Tasma


and nia

Australia/Victori Australia/West Australia/Yancowi


a nna

Europe

Europe/Amsterda Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade


m
Europe/Berlin Europe/Bratisla Europe/Brussels Europe/Bucharest Europe/Budapest
va

Europe/Busingen Europe/Chisina Europe/Copenhage Europe/Dublin Europe/Gibraltar


u n

Europe/Guernsey Europe/Helsinki Europe/Isle_of_M Europe/Istanbul Europe/Jersey


an

Europe/Kaliningra Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London


d

Europe/Luxembou Europe/Madrid Europe/Malta Europe/Marieha Europe/Minsk


rg mn

Europe/Monaco Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris

Europe/Podgorica Europe/Prague Europe/Riga Europe/Rome Europe/Samara

Europe/San_Marin Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia


o

Europe/Stockholm Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgoro


d
Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgogr
ad

Europe/Warsaw Europe/Zagreb Europe/Zaporozhy Europe/Zurich


e

Indian

Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro

Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte

Indian/Reunion

Pacific

Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Chuuk Pacific/Easter

Pacific/Efate Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti

Pacific/Galapagos Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu

Pacific/Johnston Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro


Pacific/Marquesas Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk

Pacific/Noumea Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Pohnpei

Pacific/Ponape Pacific/Port_Moresby Pacific/Rarotonga Pacific/Saipan Pacific/Samoa

Pacific/Tahiti Pacific/Tarawa Pacific/Tongatapu Pacific/Truk Pacific/Wake

Pacific/Wallis Pacific/Yap

Javatpoint :

PHP $ and $$ Variables


The $var (single dollar) is a normal variable with the name var that stores any value like
string, integer, float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable
inside it.

To understand the difference better, let's see some examples.

Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>

Output:

In the above example, we have assigned a value to the variable x as abc. Value of
reference variable $$x is assigned as 200.

Now we have printed the values $x, $$x and $abc.

Example2
1. <?php
2. $x="U.P";
3. $$x="Lucknow";
4. echo $x. "<br>";
5. echo $$x. "<br>";
6. echo "Capital of $x is " . $$x;
7. ?>

Output:

In the above example, we have assigned a value to the variable x as U.P. Value of
reference variable $$x is assigned as Lucknow.

Now we have printed the values $x, $$x and a string.


Example3
1. <?php
2. $name="Cat";
3. ${$name}="Dog";
4. ${${$name}}="Monkey";
5. echo $name. "<br>";
6. echo ${$name}. "<br>";
7. echo $Cat. "<br>";
8. echo ${${$name}}. "<br>";
9. echo $Dog. "<br>";
10. ?>

Output:

In the above example, we have assigned a value to the variable name Cat. Value of
reference variable ${$name} is assigned as Dog and ${${$name}} as Monkey.

Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.

PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the
script. PHP constants can be defined by 2 ways:

1. Using define() function


2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with letter
or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()


Let's see the syntax of define() function in PHP.

1. define(name, value, case-insensitive)


1. name: specifies the constant name
2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>

Output:

Hello JavaTpoint PHP


File: constant2.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>

Output:

Hello JavaTpoint PHPHello JavaTpoint PHP


File: constant3.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>

Output:

Hello JavaTpoint PHP


Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message
PHP constant: const keyword
The const keyword defines constants at compile time. It is a language construct not a
function.

It is bit faster than define().

It is always case sensitive.

File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>

Output:

Hello const by JavaTpoint PHP

Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of their
use. They start with double underscore (__) and ends with double underscore.

They are similar to other predefined constants but as they change their values with the
context, they are called magic constants.

There are eight magical constants defined in the below table. They are case-insensitive.

Name Description

__LINE__ Represents current line number where it is used.

__FILE__ Represents full path and file name of the file. If it is used inside an
include, name of included file is returned.

__DIR__ Represents full directory path of the file. Equivalent to


dirname(__file__). It does not have a trailing slash unless it is a root
directory. It also resolves symbolic link.

__FUNCTION__ Represents the function name where it is used. If it is used outside of


any function, then it will return blank.
__CLASS__ Represents the class name where it is used. If it is used outside of any
function, then it will return blank.

__TRAIT__ Represents the trait name where it is used. If it is used outside of any
function, then it will return blank. It includes namespace it was
declared in.

__METHOD__ Represents the name of the class method where it is used. The method
name is returned as it was declared.

__NAMESPACE__ Represents the name of the current namespace.

Example
Let's see an example for each of the above magical constants.

File Name: magic.php

1. <?php
2. echo "<h3>Example for __LINE__</h3>";
3. echo "You are at line number " . __LINE__ . "<br><br>";// print Your current line number
i.e;3
4. echo "<h3>Example for __FILE__</h3>";
5. echo __FILE__ . "<br><br>";//print full path of file with .php extension
6. echo "<h3>Example for __DIR__</h3>";
7. echo __DIR__ . "<br><br>";//print full path of directory where script will be placed
8. echo dirname(__FILE__) . "<br><br>"; //its output is equivalent to above one.
9. echo "<h3>Example for __FUNCTION__</h3>";
10. //Using magic constant inside function.
11. function cash(){
12. echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is cash.
13. }
14. cash();
15. //Using magic constant outside function gives the blank output.
16. function test_function(){
17. echo 'HYIIII';
18. }
19. test_function();
20. echo __FUNCTION__ . "<br><br>";//gives the blank output.
21.
22. echo "<h3>Example for __CLASS__</h3>";
23. class abc
24. {
25. public function __construct() {
26. ;
27. }
28. function abc_method(){
29. echo __CLASS__ . "<br><br>";//print name of the class abc.
30. }
31. }
32. $t = new abc;
33. $t->abc_method();
34. class first{
35. function test_first(){
36. echo __CLASS__;//will always print parent class which is first here.
37. }
38. }
39. class second extends first
40. {
41. public function __construct() {
42. ;
43. }
44. }
45. $t = new second;
46. $t->test_first();
47. echo "<h3>Example for __TRAIT__</h3>";
48. trait created_trait{
49. function abc(){
50. echo __TRAIT__;//will print name of the trait created_trait
51. }
52. }
53. class anew{
54. use created_trait;
55. }
56. $a = new anew;
57. $a->abc();
58. echo "<h3>Example for __METHOD__</h3>";
59. class meth{
60. public function __construct() {
61. echo __METHOD__ . "<br><br>";//print meth::__construct
62. }
63. public function meth_fun(){
64. echo __METHOD__;//print meth::meth_fun
65. }
66. }
67. $a = new meth;
68. $a->meth_fun();
69.
70. echo "<h3>Example for __NAMESPACE__</h3>";
71. class name{
72. public function __construct() {
73. echo 'This line will be printed on calling namespace';
74. }
75. }
76. $clas_name= __NAMESPACE__ .'\name';
77. $a = new $clas_name;
78. ?>

Output:
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times,
like in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to


understand the flow of the application because every logic is divided in the form of
functions.

PHP User-defined Functions


We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

Syntax
1. function functionname(){
2. //code to be executed
3. }

Note: Function name must be start with letter and underscore only like other labels in PHP. It can't
be start with numbers or special symbols.

PHP Functions Example


File: function1.php
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:

Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by
comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>

Output:

Hello Sonoo
Hello Vimal
Hello John

Let's see the example to pass two argument in PHP function.

File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>

Output:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But
we can do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.

Let's see a simple example of call by reference in PHP.

File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

Output:

Hello Call By Reference

PHP Function: Default Argument Value


We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.

File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>

Output:
Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value


Let's see an example of PHP function that returns value.

File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>

Output:

Cube of 3 is: 27

PHP Parameterized Function


PHP Parameterized functions are the functions with parameters. You can pass any number
of parameters inside a function. These passed parameters act as variables inside your
function.

They are specified inside the parentheses, after the function name.

The output depends upon the dynamic values passed as the parameters into the function.

PHP Parameterized Example 1


Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two


functions add() and sub().

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Parameter Addition and Subtraction Example</title>
5. </head>
6. <body>
7. <?php
8. //Adding two numbers
9. function add($x, $y) {
10. $sum = $x + $y;
11. echo "Sum of two numbers is = $sum <br><br>";
12. }
13. add(467, 943);
14.
15. //Subtracting two numbers
16. function sub($x, $y) {
17. $diff = $x - $y;
18. echo "Difference between two numbers is = $diff";
19. }
20. sub(943, 467);
21. ?>
22. </body>
23. </html>

Output:

PHP Parameterized Example 2


Addition and Subtraction with Dynamic number

In this example, we have passed two parameters $x and $y inside two


functions add() and sub().

1. <?php
2. //add() function with two parameter
3. function add($x,$y)
4. {
5. $sum=$x+$y;
6. echo "Sum = $sum <br><br>";
7. }
8. //sub() function with two parameter
9. function sub($x,$y)
10. {
11. $sub=$x-$y;
12. echo "Diff = $sub <br><br>";
13. }
14. //call function, get two argument through input box and click on add or sub button
15. if(isset($_POST['add']))
16. {
17. //call add() function
18. add($_POST['first'],$_POST['second']);
19. }
20. if(isset($_POST['sub']))
21. {
22. //call add() function
23. sub($_POST['first'],$_POST['second']);
24. }
25. ?>
26. <form method="post">
27. Enter first number: <input type="number" name="first"/><br><br>
28. Enter second number: <input type="number" name="second"/><br><br>
29. <input type="submit" name="add" value="ADDITION"/>
30. <input type="submit" name="sub" value="SUBTRACTION"/>
31. </form>

Output:

We passed the following number,


Now clicking on ADDITION button, we get the following output.

Now clicking on SUBTRACTION button, we get the following output.

PHP Call By Value


PHP allows you to call function by value and reference both. In case of PHP call by value,
actual value is not modified if it is modified inside the function.

Let's understand the concept of call by value by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes
are done in the local variable $str2 only. It doesn't reflect to $str variable.
1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

Output:

Hello

Example 2
Let's understand PHP call by value concept through another example.

1. <?php
2. function increment($i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>

Output:

10

PHP Call By Reference


In case of PHP call by reference, actual value is modified if it is modified inside the function.
In such case, you need to use & (ampersand) symbol with formal arguments. The &
represents reference of the variable.

Let's understand the concept of call by reference by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'This is ';
7. adder($str);
8. echo $str;
9. ?>

Output:

This is Call By Reference

Example 2
Let's understand PHP call by reference concept through another example.

1. <?php
2. function increment(&$i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>

Output:

11

PHP Default Argument Values Function


PHP allows you to define C++ style default argument values. In such case, if you don't pass
any value to the function, it will use default argument value.

Let' see the simple example of using PHP default arguments in function.

Example 1
1. <?php
2. function sayHello($name="Ram"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello();//passing no value
7. sayHello("Vimal");
8. ?>

Output:

Hello Sonoo
Hello Ram
Hello Vimal

Since PHP 5, you can use the concept of default argument value with call by reference also.

Example 2
1. <?php
2. function greeting($first="Sonoo",$last="Jaiswal"){
3. echo "Greeting: $first $last<br/>";
4. }
5. greeting();
6. greeting("Rahul");
7. greeting("Michael","Clark");
8. ?>

Output:

Greeting: Sonoo Jaiswal


Greeting: Rahul Jaiswal
Greeting: Michael Clark

Example 3
1. <?php
2. function add($n1=10,$n2=10){
3. $n3=$n1+$n2;
4. echo "Addition is: $n3<br/>";
5. }
6. add();
7. add(20);
8. add(40,40);
9. ?>

Output:
Addition is: 20
Addition is: 30
Addition is: 80

PHP Variable Length Argument Function


PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument
name.

The 3 dot concept is implemented for variable length argument since PHP 5.6.

Let's see a simple example of PHP variable length argument function.

1. <?php
2. function add(...$numbers) {
3. $sum = 0;
4. foreach ($numbers as $n) {
5. $sum += $n;
6. }
7. return $sum;
8. }
9.
10. echo add(1, 2, 3, 4);
11. ?>

Output:

10

PHP Recursive Function


PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.

Example 1: Printing number


1. <?php
2. function display($number) {
3. if($number<=5){
4. echo "$number <br/>";
5. display($number+1);
6. }
7. }
8.
9. display(1);
10. ?>

Output:

1
2
3
4
5

Example 2 : Factorial Number


1. <?php
2. function factorial($n)
3. {
4. if ($n < 0)
5. return -1; /*Wrong value*/
6. if ($n == 0)
7. return 1; /*Terminating condition*/
8. return ($n * factorial ($n -1));
9. }
10.
11. echo factorial(5);
12. ?>

Output:

120

PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.


PHP Array Types
There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");

2nd way:

1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";

Example
File: array1.php

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output:

Season are: summer, winter, spring and autumn

File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>

Output:

Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:

1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";

Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

PHP Indexed Array


PHP indexed array is an array which is represented by an index number by default. All
elements of array are represented by an index number which starts from 0.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array.

Definition
There are two ways to define indexed array:

1st way:

1. $size=array("Big","Medium","Short");

2nd way:

1. $size[0]="Big";
2. $size[1]="Medium";
3. $size[2]="Short";

PHP Indexed Array Example


File: array1.php
1. <?php
2. $size=array("Big","Medium","Short");
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>
Output:

Size: Big, Medium and Short


File: array2.php
1. <?php
2. $size[0]="Big";
3. $size[1]="Medium";
4. $size[2]="Short";
5. echo "Size: $size[0], $size[1] and $size[2]";
6. ?>

Output:

Size: Big, Medium and Short

Traversing PHP Indexed Array


We can easily traverse array in PHP using foreach loop. Let's see a simple example to
traverse all the elements of PHP array.

File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>

Output:

Size is: Big


Size is: Medium
Size is: Short

Count Length of PHP Indexed Array


PHP provides count() function which returns length of an array.

1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:

PHP Associative Array


PHP allows you to associate name/label with each array elements in PHP using => symbol.
Such way, you can easily remember the element because each element is represented by
label than an incremented number.

Definition
There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

2nd way:

1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";

Example
File: arrayassociative1.php

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>

Output:

Sonoo salary: 550000


Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php

1. <?php
2. $salary["Sonoo"]="550000";
3. $salary["Vimal"]="250000";
4. $salary["Ratan"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
7. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
8. ?>

Output:

Sonoo salary: 550000


Vimal salary: 250000
Ratan salary: 200000

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP associative
array.

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>

Output:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix which
is represented by row * column.

Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
PHP Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display following tabular data.
In this example, we are displaying 3 rows and 3 columns.

Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

File: multiarray.php

1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>

Output:

1 sonoo 400000
2 john 500000
3 rahul 300000
PHP Array Functions
PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed,
associative and multidimensional arrays.

Syntax

1. array array ([ mixed $... ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>

Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>

Output:

Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

3) PHP array_chunk() function


PHP array_chunk() function splits array into chunks. By using array_chunk() method, you
can divide array into many parts.

Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

3. print_r(array_chunk($salary,2));
4. ?>

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

4) PHP count() function


PHP count() function counts all elements in an array.

Syntax

1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )


Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

Output:

5) PHP sort() function


PHP sort() function sorts all the elements in an array.

Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )


Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
winter
summer

7) PHP array_search() function


PHP array_search() function searches the specified value in an array. It returns key if
search is successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>

Output:

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other words, it
returns the matching elements of two array.

Syntax
1. array array_intersect ( array $array1 , array $array2 [, array $... ] )

Example

1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>

Output:

sonoo
smith

PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.

o single quoted
o double quoted
o heredoc syntax
o newdoc syntax (since PHP 5.3)

Single Quoted PHP String


We can create a string in PHP by enclosing text in a single quote. It is the easiest way to
specify string in PHP.

1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>

Output:

Hello text within single quote


We can store multiple line text, special characters and escape sequences in a single quoted
PHP string.

1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>

Output:

Hello text multiple line text within single quoted string


Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string

Note: In single quoted PHP strings, most escape sequences and variables will not be interpreted.
But, we can use single quote through \' and backslash through \\ inside single quoted PHP strings.

1. <?php
2. $num1=10;
3. $str1='trying variable $num1';
4. $str2='trying backslash n and backslash t inside single quoted string \n \t';
5. $str3='Using single quote \'my quote\' and \\backslash';
6. echo "$str1 <br/> $str2 <br/> $str3";
7. ?>

Output:

trying variable $num1


trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash

Double Quoted PHP String


In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.

1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Output:

Hello text within double quote

Now, you can't use double quote directly inside double quoted string.

1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>

Output:

Parse error: syntax error, unexpected 'quote' (T_STRING) in


C:\wamp\www\string1.php on line 2

We can store multiple line text, special characters and escape sequences in a double
quoted PHP string.

1. <?php
2. $str1="Hello text
3. multiple line
4. text within double quoted string";
5. $str2="Using double \"quote\" with backslash inside double quoted string";
6. $str3="Using escape sequences \n in double quoted string";
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>

Output:

Hello text multiple line text within double quoted string


Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string

In double quoted strings, variable will be interpreted.

1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>

Output:

Number is: 10

PHP STRING FUNTIONS


addcslashes() It is used to return a string with backslashes.

addslashes() It is used to return a string with backslashes.

bin2hex() It is used to converts a string of ASCII characters to hexadecimal


values.

chop() It removes whitespace or other characters from the right end of a


string

chr() It is used to return a character from a specified ASCII value.

chunk_split() It is used to split a string into a series of smaller parts.

convert_cyr_string() It is used to convert a string from one Cyrillic character-set to


another.

convert_uudecode() It is used to decode a uuencoded string.

convert_uuencode() It is used to encode a string using the uuencode algorithm.

count_chars() It is used to return information about characters used in a string.

crc32() It is used to calculate a 32-bit CRC for a string.

crypt() It is used to create hashing string One-way.

echo() It is used for output one or more strings.

explode() It is used to break a string into an array.


hebrev() It is used to convert Hebrew text to visual text.

hebrevc() It is used to convert Hebrew text to visual text and new lines (\n)
into <br>.

hex2bin() It is used to convert string of hexadecimal values to ASCII


characters.

print() It is used for output one or more strings.

fprint() It is used to write a formatted string to a stream.

nl2br() It is used to insert HTML line breaks in front of each newline in a


string.

number_format() It is used to format a number with grouped thousands.

htmlentities() It is used to convert character to HTML entities.

html_entity_decode() It is used to convert HTML entities to characters.

ord() It is used to return ASCII value of the first character of a string.

parse_str() It is used to parse a query string into variables.

Implode() It is used to return a string from the elements of an array.

Lcfirst() It is used to convert the first character of a string to lowercase.

Join() It is the Alias of implode() function.


Levenshtein() It is used to return the Levenshtein distance between two strings.

trim() It is used to remove whitespace.

ltrim() It is used to remove whitespace from the left side of a string.

rtrim() It is used to remove whitespace from the right side of a string.

md5() It is used to calculate the MD5 hash of a string.

md5_files() It is used to calculate MD5 hash of a file.

metaphone() It is used to calculate the metaphone key of a string.

Soundex() It is is used to calculate the soundex key of a string.

setlocale() It is used to set locale information.

money_format() It is used to return a string formatted as a currency string.

printf() It is used to show output as a formatted string.

sha1() It is used to return the SHA-1 hash of a string.

sscanf() It is used to parse input from a string according to a format.

str_getcsv() It is used to parse a CSV string into an array.

sha1_file() It is used to return the SHA-1 hash of a file.

similar_text() It is used to compare the similarity between two strings.


str_pad() It is used to pad a string to a new length.

str_ireplace() It is used to replace some characters in a string (case-insensitive).

str_repeat() It is used to repeat a string a specified number of times.

str_rot13() It is used to perform the ROT13 encoding on a string.

str_shuffle() It is used to randomly shuffle all characters in a string.

str_split() It is used to split a string into an array.

str_word_count() It is used to count the number of words in a string.

strcasecmp() It is used to compare two strings.

strchr() It is used to find the first occurrence of a string inside another


string.

stscroll() It is locale based string comparison.

strcmp() It is binary safe string comparison.

strcspn() It is used to reverses a string.

strip_tags() It is used to strip HTML and PHP tags from a string.

stripcslashes() It is used to unquote a string quoted with addcslashes().

stripos() It is used to return the position of the first occurrence of a string


inside another string.
strlen() It is used to return the length of a string.

strnatcasecmp() It is used to compare two strings using a "natural order" algorithm.

strnatcmp() It is used to compare two strings using a "natural order" algorithm.

strncmp() It is used to compare of the first n characters.

strpbrk() It is used to search a string for any of a set of characters.

strpos() It is used to return the position of the first occurrence of a string


inside another string.

strrchr() It is used to find the last occurrence of a string inside another


string.

strrev() It is used to reverse a string.

PHP String Functions


PHP provides various string functions to access and manipulate strings. A list of important
PHP string functions are given below.

PHP STRING FUNTIONS

addcslashes() It is used to return a string with backslashes.

addslashes() It is used to return a string with backslashes.

bin2hex() It is used to converts a string of ASCII characters to hexadecimal


values.
chop() It removes whitespace or other characters from the right end of a
string

chr() It is used to return a character from a specified ASCII value.

chunk_split() It is used to split a string into a series of smaller parts.

convert_cyr_string() It is used to convert a string from one Cyrillic character-set to


another.

convert_uudecode() It is used to decode a uuencoded string.

convert_uuencode() It is used to encode a string using the uuencode algorithm.

count_chars() It is used to return information about characters used in a string.

crc32() It is used to calculate a 32-bit CRC for a string.

crypt() It is used to create hashing string One-way.

echo() It is used for output one or more strings.

explode() It is used to break a string into an array.

hebrev() It is used to convert Hebrew text to visual text.

hebrevc() It is used to convert Hebrew text to visual text and new lines (\n)
into <br>.

hex2bin() It is used to convert string of hexadecimal values to ASCII


characters.
print() It is used for output one or more strings.

fprint() It is used to write a formatted string to a stream.

nl2br() It is used to insert HTML line breaks in front of each newline in a


string.

number_format() It is used to format a number with grouped thousands.

htmlentities() It is used to convert character to HTML entities.

html_entity_decode() It is used to convert HTML entities to characters.

ord() It is used to return ASCII value of the first character of a string.

parse_str() It is used to parse a query string into variables.

Implode() It is used to return a string from the elements of an array.

Lcfirst() It is used to convert the first character of a string to lowercase.

Join() It is the Alias of implode() function.

Levenshtein() It is used to return the Levenshtein distance between two strings.

trim() It is used to remove whitespace.

ltrim() It is used to remove whitespace from the left side of a string.

rtrim() It is used to remove whitespace from the right side of a string.


md5() It is used to calculate the MD5 hash of a string.

md5_files() It is used to calculate MD5 hash of a file.

metaphone() It is used to calculate the metaphone key of a string.

Soundex() It is is used to calculate the soundex key of a string.

setlocale() It is used to set locale information.

money_format() It is used to return a string formatted as a currency string.

printf() It is used to show output as a formatted string.

sha1() It is used to return the SHA-1 hash of a string.

sscanf() It is used to parse input from a string according to a format.

str_getcsv() It is used to parse a CSV string into an array.

sha1_file() It is used to return the SHA-1 hash of a file.

similar_text() It is used to compare the similarity between two strings.

str_pad() It is used to pad a string to a new length.

str_ireplace() It is used to replace some characters in a string (case-insensitive).

str_repeat() It is used to repeat a string a specified number of times.

str_rot13() It is used to perform the ROT13 encoding on a string.


str_shuffle() It is used to randomly shuffle all characters in a string.

str_split() It is used to split a string into an array.

str_word_count() It is used to count the number of words in a string.

strcasecmp() It is used to compare two strings.

strchr() It is used to find the first occurrence of a string inside another


string.

stscroll() It is locale based string comparison.

strcmp() It is binary safe string comparison.

strcspn() It is used to reverses a string.

strip_tags() It is used to strip HTML and PHP tags from a string.

stripcslashes() It is used to unquote a string quoted with addcslashes().

stripos() It is used to return the position of the first occurrence of a string


inside another string.

strlen() It is used to return the length of a string.

strnatcasecmp() It is used to compare two strings using a "natural order" algorithm.

strnatcmp() It is used to compare two strings using a "natural order" algorithm.

strncmp() It is used to compare of the first n characters.


strpbrk() It is used to search a string for any of a set of characters.

strpos() It is used to return the position of the first occurrence of a string


inside another string.

strrchr() It is used to find the last occurrence of a string inside another


string.

strrev() It is used to reverse a string.

1) PHP strtolower() function


The strtolower() function returns string in lowercase letter.

Syntax

1. string strtolower ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>

Output:

my name is khan

2) PHP strtoupper() function


The strtoupper() function returns string in uppercase letter.

Syntax

1. string strtoupper ( string $string )

Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>

Output:

MY NAME IS KHAN

3) PHP ucfirst() function


The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.

Syntax

1. string ucfirst ( string $str )

Example

1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>

Output:

My name is KHAN

4) PHP lcfirst() function


The lcfirst() function returns string converting first character into lowercase. It doesn't
change the case of other characters.

Syntax

1. string lcfirst ( string $str )

Example

1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>

Output:

mY name IS KHAN

5) PHP ucwords() function


The ucwords() function returns string converting first character of each word into
uppercase.

Syntax

1. string ucwords ( string $str )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>

Output:

My Name Is Sonoo Jaiswal

6) PHP strrev() function


The strrev() function returns reversed string.

Syntax

1. string strrev ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:

lawsiaj oonoS si eman ym

7) PHP strlen() function


The strlen() function returns length of the string.

Syntax

1. int strlen ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>

Output:

24

PHP Math
PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.

PHP Math: abs() function


The abs() function returns absolute value of given number. It returns an integer value but if
you pass floating point value, it returns a float value.

Syntax

1. number abs ( mixed $number )


Example

1. <?php
2. echo (abs(-7)."<br/>"); // 7 (integer)
3. echo (abs(7)."<br/>"); //7 (integer)
4. echo (abs(-7.2)."<br/>"); //7.2 (float/double)
5. ?>
Output:

7
7
7.2

PHP Math: ceil() function


The ceil() function rounds fractions up.

Syntax

1. float ceil ( float $value )


Example

1. <?php
2. echo (ceil(3.3)."<br/>");// 4
3. echo (ceil(7.333)."<br/>");// 8
4. echo (ceil(-4.8)."<br/>");// -4
5. ?>

Output:

4
8
-4

PHP Math: floor() function


The floor() function rounds fractions down.

Syntax

1. float floor ( float $value )


Example

1. <?php
2. echo (floor(3.3)."<br/>");// 3
3. echo (floor(7.333)."<br/>");// 7
4. echo (floor(-4.8)."<br/>");// -5
5. ?>

Output:

3
7
-5
PHP Math: sqrt() function
The sqrt() function returns square root of given argument.

Syntax

1. float sqrt ( float $arg )


Example

1. <?php
2. echo (sqrt(16)."<br/>");// 4
3. echo (sqrt(25)."<br/>");// 5
4. echo (sqrt(7)."<br/>");// 2.6457513110646
5. ?>

Output:

4
5
2.6457513110646

PHP Math: decbin() function


The decbin() function converts decimal number into binary. It returns binary number as a
string.

Syntax

1. string decbin ( int $number )


Example

1. <?php
2. echo (decbin(2)."<br/>");// 10
3. echo (decbin(10)."<br/>");// 1010
4. echo (decbin(22)."<br/>");// 10110
5. ?>

Output:

10
1010
10110

PHP Math: dechex() function


The dechex() function converts decimal number into hexadecimal. It returns hexadecimal
representation of given number as a string.

Syntax

1. string dechex ( int $number )


Example

1. <?php
2. echo (dechex(2)."<br/>");// 2
3. echo (dechex(10)."<br/>");// a
4. echo (dechex(22)."<br/>");// 16
5. ?>

Output:

2
a
16

PHP Math: decoct() function


The decoct() function converts decimal number into octal. It returns octal representation of
given number as a string.

Syntax

1. string decoct ( int $number )


Example

1. <?php
2. echo (decoct(2)."<br/>");// 2
3. echo (decoct(10)."<br/>");// 12
4. echo (decoct(22)."<br/>");// 26
5. ?>

Output:

2
12
26

PHP Math: base_convert() function


The base_convert() function allows you to convert any base number to any base number.
For example, you can convert hexadecimal number to binary, hexadecimal to octal, binary
to octal, octal to hexadecimal, binary to decimal etc.
Syntax

1. string base_convert ( string $number , int $frombase , int $tobase )


Example

1. <?php
2. $n1=10;
3. echo (base_convert($n1,10,2)."<br/>");// 1010
4. ?>

Output:

1010

PHP Math: bindec() function


The bindec() function converts binary number into decimal.

Syntax

1. number bindec ( string $binary_string )


Example

1. <?php
2. echo (bindec(10)."<br/>");// 2
3. echo (bindec(1010)."<br/>");// 10
4. echo (bindec(1011)."<br/>");// 11
5. ?>

Output:

2
10
11

PHP Math Functions


Let's see the list of important PHP math functions.

Function Description

abs() It is used to find the absolute (positive) value of a number.


sin() It is used to return the sine of a number.

sinh() It is used to return the hyperbolic sine of a number.

asin() It is used to find the arc sine of a number.

asinh() It is used to find the inverse hyperbolic sine of a number.

cos() It is used to find the cosine of a number.

cosh() It is used to return the cosh of a number.

acos() It is used to return the arc cosine of a number.

acosh() It is used to return the inverse hyperbolic cosine of a number.

tan() It is used to return the tangent of a number.

tanh() It is used to return the hyperbolic tangent of a number.

atan() It is used to return the arc tangent of a number in radians.

atan2() It is used to return the arc tangent of two variables x and y.

atanh() It is used to return the inverse hyperbolic tangent of a number.

base_convert() It is used to convert a number from one number base to another.

bindec() It is used to convert a binary number to a decimal number.

ceil() It is used to find round a number up to the nearest integer.


pi() It returns the approximation value of PI.

decbin() It converts a decimal number to a binary number.

dechex() It converts a decimal number to a hexadecimal number.

decoct() It converts a decimal number to an octal number

deg2rad() It converts a degree value to a radian value.

rad2deg() It converts a radian value to a degree value.

exp() It is used to calculate the exponent of e.

expm1() It is used to return exp(x) - 1.

floor() It converts round a number down to the nearest integer.

fmod() It returns the remainder of x/y.

getrandmax() It returns the largest possible value returned by rand().

hexadec() It is used to convert a hexadecimal number to a decimal number.

hypot() It is used to calculate the hypotenuse of a right-angle triangle.

is_finite() To check whether a value is finite or not.

is_infinite() It is used to check whether a value is infinite or not.

is_nan() It is used to check whether a value is 'not-a-number'.


lcg_value() It is used to return a pseudo random number in a range between 0
and 1.

log() It is used to return the natural logarithm of a number.

log10() It is used to return the base-10 logarithm of a number.

log1p() It is used to return log(1+number).

max() It is used to return the highest value in an array, or the highest value
of several specified values.

min() It returns the lowest value in an array, or the lowest value of several
specified values.

getrandmax() It is used to return the maximum value by using rand().

mt_getrandmax() Returns the largest possible value returned by mt_rand().

mt_rand() Generates a random integer using Mersenne Twister algorithm.

mt_srand() Seeds the Mersenne Twister random number generator.

octdec() It is used to converts an octal number to a decimal number.

pow() It is used to return x raised to the power of y.

intdiv It returns the integer quotient of the division of dividend by divisor.

rand() It is used to generates a random integer.


round() It is used to round a floating-point number.

fmod() It is used to return the floating point remainder of the division of the
argument.

sqrt() It is used to return the square root of a number.

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.

PHP Get Form


Get request is the default form request. The data passed through get request is visible on
the URL browser so it is not secured. You can send limited amount of data through get
request.

Let's see a simple example to receive data from get request in PHP.

File: form1.html

1. <form action="welcome.php" method="get">


2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php

1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>

PHP Post Form


Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You
can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html
1. <form action="login.php" method="post">
2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
4. <tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
6. </table>
7. </form>
File: login.php
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>

Output:

PHP Include File


PHP allows you to include file so that a page content can be reused many times. There are
two ways to include file in PHP.
1. include
2. require

Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or
PHP script in many PHP scripts.

PHP include example


PHP include is used to include file on the basis of given path. You may use relative or
absolute path of the file. Let's see a simple PHP include example.

File: menu.html

1. <a href="http://www.javatpoint.com">Home</a> |
2. <a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
3. <a href="http://www.javatpoint.com/java-tutorial">Java</a> |
4. <a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php

1. <?php include("menu.html"); ?>


2. <h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page


PHP require example
PHP require is similar to include. Let's see a simple PHP require example.

File: menu.html

1. <a href="http://www.javatpoint.com">Home</a> |
2. <a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
3. <a href="http://www.javatpoint.com/java-tutorial">Java</a> |
4. <a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: require1.php
1. <?php require("menu.html"); ?>
2. <h1>This is Main Page</h1>

Output:

Home | PHP | Java | HTML

This is Main Page


PHP include vs PHP require
If file is missing or inclusion fails, include allows the script to continue but require halts
the script producing a fatal E_COMPILE_ERROR level error.

PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.

Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received
at the server side.

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

PHP setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you
can access it by $_COOKIE superglobal variable.

Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Example

1. setcookie("CookieName", "CookieValue");/* defining name and value only*/


2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*6
0 seconds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1
);

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Example

1. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example


File: cookie1.php
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>

Output:

Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:

Cookie Value: Sonoo

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.

File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>

PHP Session
PHP session is used to store and pass information from one page to another temporarily
(until user close the website).

PHP session technique is widely used in shopping websites where we need to store and pass
cart information e.g. username, product code, product name, product price etc from one
page to another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.

PHP session_start() function


PHP session_start() function is used to start the session. It starts a new or resumes existing
session. It returns existing session if session is created already. If session is not available, it
creates and returns new session.

Syntax
1. bool session_start ( void )

Example

1. session_start();

PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.

Example: Store information

1. $_SESSION["user"] = "Sachin";

Example: Get information

1. echo $_SESSION["user"];

PHP Session Example


File: session1.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.php">Visit next page</a>
11. </body>
12. </html>
File: session2.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>

PHP Session Counter Example


File: sessioncounter.php
1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>

PHP Destroying Session


PHP session_destroy() function is used to destroy all session variables completely.

File: session3.php
1. <?php
2. session_start();
3. session_destroy();
4. ?>

PHP File Handling


PHP File System allows us to create file, read file line by line, read file character by
character, write file, append file, delete file and close file.

PHP Open File - fopen()


The PHP fopen() function is used to open a file.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
Example

1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>

PHP Close File - fclose()


The PHP fclose() function is used to close an open file pointer.

Syntax

1. ool fclose ( resource $handle )

Example

1. <?php
2. fclose($handle);
3. ?>

PHP Read File - fread()


The PHP fread() function is used to read the content of the file. It accepts two arguments:
resource and file size.

Syntax

1. string fread ( resource $handle , int $length )

Example

1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>

Output

hello php file


Click me for more details...

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example

1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output

File written successfully


Click me for more details...

PHP Delete File - unlink()


The PHP unlink() function is used to delete file.

Syntax

1. bool unlink ( string $filename [, resource $context ] )

Example

1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>

PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The fopen() function
accepts two arguments: $filename and $mode. The $filename represents the file to be
opended and $mode represents the file mode for example read-only, read-write, write-only
etc.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )

PHP Open File Mode

Mode Description

r Opens file in read-only mode. It places the file pointer at the beginning of the file.

r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.

w Opens file in write-only mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.

w+ Opens file in read-write mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.

a Opens file in write-only mode. It places the file pointer to the end of the file. If file
is not found, it creates a new file.

a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file
is not found, it creates a new file.

x Creates and opens file in write-only mode. It places the file pointer at the
beginning of the file. If file is found, fopen() function returns FALSE.
x+ It is same as x but it creates and opens file in read-write mode.

c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it
is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the
case with 'x'). The file pointer is positioned on the beginning of the file

c+ It is same as c but it opens file in read-write mode.

PHP Open File Example


1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>

PHP Read File


PHP provides various functions to read data from file. There are different functions that
allow you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

o fread()
o fgets()
o fgetc()

PHP Read File - fread()


The PHP fread() function is used to read data of the file. It requires two arguments: file
resource and file size.

Syntax
1. string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

Example
1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>

Output

this is first line


this is another line
this is third line

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

Syntax
1. string fgets ( resource $handle [, int $length ] )

Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>

Output

this is first line

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.

Syntax
1. string fgetc ( resource $handle )

Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>

Output

this is first line this is another line this is third line

PHP Write File


PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you
need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example

1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'welcome ');
4. fwrite($fp, 'to php file write');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output: data.txt

welcome to php file write


PHP Overwriting File
If you run the above code again, it will erase the previous data of the file and writes the
new data. Let's see the code that writes only new data into data.txt file.

1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'hello');
4. fclose($fp);
5.
6. echo "File written successfully";
7. ?>

Output: data.txt

hello

PHP Append to File


If you use a mode, it will not erase the data of the file. It will write the data at the end of
the file. Visit the next page to see the example of appending data into file.

PHP Append to File


You can append data into file by using a or a+ mode in fopen() function. Let's see a simple
example that appends data into data.txt file.

Let's see the data of file first.

data.txt

welcome to php file write

PHP Append to File - fwrite()


The PHP fwrite() function is used to write and append data into file.

Example

1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>

Output: data.txt

welcome to php file write this is additional text appending data

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.

Syntax

1. bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.

PHP Delete File Example


1. <?php
2. $status=unlink('data.txt');
3. if($status){
4. echo "File deleted successfully";
5. }else{
6. echo "Sorry!";
7. }
8. ?>

Output

File deleted successfully

PHP File Upload


PHP allows you to upload single and multiple files through few lines of code only.

PHP file upload features allows you to upload binary and text files both. Moreover, you can
have the full control over the file to be uploaded through PHP authentication and file
operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global,
we can get file name, file type, file size, temp file name and errors associated with file.

Here, we are assuming that file name is filename.

$_FILES['filename']['name']
returns file name.

$_FILES['filename']['type']
returns MIME type of the file.

$_FILES['filename']['size']
returns size of the file (in bytes).

$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.

$_FILES['filename']['error']
returns error code associated with this file.

move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.

Syntax

1. bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example


File: uploadform.html
1. <form action="uploader.php" method="post" enctype="multipart/form-data">
2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit"/>
5. </form>
File: uploader.php
1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10. ?>

PHP Download File


PHP enables you to download file easily using built-in readfile() function. The readfile()
function reads a file and writes it to the output buffer.

PHP readfile() function


Syntax

1. int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to


true to the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.

PHP Download File Example: Text File


File: download1.php
1. <?php
2. $file_url = 'http://www.javatpoint.com/f.txt';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: utf-8");
5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Download File Example: Binary File


File: download2.php
1. <?php
2. $file_url = 'http://www.myremoteserver.com/file.exe';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: Binary");
5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Mail
PHP mail() function is used to send email in PHP. You can send text message, html message
and attachment with message using PHP mail() function.

PHP mail() function


Syntax

1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, stri
ng $additional_parameters ]] )

$to: specifies receiver or receivers of the mail. The receiver must be specified one of the
following forms.

o user@example.com
o user@example.com, anotheruser@example.com
o User <user@example.com>
o User <user@example.com>, Another User <anotheruser@example.com>

$subject: represents subject of the mail.

$message: represents message of the mail to be sent.


Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not be
larger than 70 characters.

$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc. Extra additional headers should also be separated with CRLF ( \r\n ).

PHP Mail Example


File: mailer.php
1. <?php
2. ini_set("sendmail_from", "sonoojaiswal@javatpoint.com");
3. $to = "sonoojaiswal1987@gmail.com";//change receiver address
4. $subject = "This is subject";
5. $message = "This is simple text message.";
6. $header = "From:sonoojaiswal@javatpoint.com \r\n";
7.
8. $result = mail ($to,$subject,$message,$header);
9.
10. if( $result == true ){
11. echo "Message sent successfully...";
12. }else{
13. echo "Sorry, unable to send mail...";
14. }
15. ?>

If you run this code on the live server, it will send an email to the specified receiver.

PHP Mail: Send HTML Message


To send HTML message, you need to mention Content-type text/html in the message
header.

1. <?php
2. $to = "abc@example.com";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:xyz@example.com \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>

PHP Mail: Send Mail with Attachment


To send message with attachment, you need to mention many header information which is
used in the example given below.

1. <?php
2. $to = "abc@example.com";
3. $subject = "This is subject";
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("/tmp/test.txt", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("/tmp/test.txt");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert \r\n after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:xyz@example.com\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
43. $header .= "--$num--";
44.
45. # Send email now
46. $result = mail ( $to, $subject, "", $header );
47. if( $result == true ){
48. echo "Message sent successfully...";
49. }else{
50. echo "Sorry, unable to send mail...";
51. }
52. ?>

PHP MySQL Connect


Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use
one of the 2 alternatives.

o mysqli_connect()
o PDO::__construct()

PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null.

Syntax

1. resource mysqli_connect (server, username, password)

PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.

Syntax

1. bool mysqli_close(resource $resource_link)

PHP MySQL Connect Example


Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_error());
9. }
10. echo 'Connected successfully';
11. mysqli_close($conn);
12. ?>

Output:

Connected successfully

PHP MySQL Create Database


Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use
one of the 2 alternatives.

o mysqli_query()
o PDO::__query()
PHP MySQLi Create Database Example
Example

1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>

Output:

Connected successfully
Database mydb created successfully.

PHP MySQL Create Table


PHP mysql_query() function is used to create table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Create Table Example


Example

1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,
14. emp_salary INT NOT NULL,primary key (id))";
15. if(mysqli_query($conn, $sql)){
16. echo "Table emp5 created successfully";
17. }else{
18. echo "Could not create table: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>

Output:

Connected successfully
Table emp5 created successfully

PHP MySQL Insert Record


PHP mysql_query() function is used to insert record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Insert Record Example


Example

1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
14. if(mysqli_query($conn, $sql)){
15. echo "Record inserted successfully";
16. }else{
17. echo "Could not insert record: ". mysqli_error($conn);
18. }
19.
20. mysqli_close($conn);
21. ?>

Output:

Connected successfully
Record inserted successfully

PHP MySQL Update Record


PHP mysql_query() function is used to update record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Update Record Example


Example

1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $name="Rahul";
15. $salary=80000;
16. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
17. if(mysqli_query($conn, $sql)){
18. echo "Record updated successfully";
19. }else{
20. echo "Could not update record: ". mysqli_error($conn);
21. }
22.
23. mysqli_close($conn);
24. ?>

Output:

Connected successfully
Record updated successfully

PHP MySQL Delete Record


PHP mysql_query() function is used to delete record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Delete Record Example


Example

1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $sql = "delete from emp4 where id=$id";
15. if(mysqli_query($conn, $sql)){
16. echo "Record deleted successfully";
17. }else{
18. echo "Could not deleted record: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>

Output:

Connected successfully
Record deleted successfully

PHP MySQL Select Query


PHP mysql_query() function is used to execute select query. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

There are two other MySQLi functions used in select query.

o mysqli_num_rows(mysqli_result $result): returns number of rows.


o mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array.
Each key of the array represents the column name of the table. It return NULL if
there are no more rows.

PHP MySQLi Select Query Example


Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6. $conn = mysqli_connect($host, $user, $pass,$dbname);
7. if(!$conn){
8. die('Could not connect: '.mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'SELECT * FROM emp4';
13. $retval=mysqli_query($conn, $sql);
14.
15. if(mysqli_num_rows($retval) > 0){
16. while($row = mysqli_fetch_assoc($retval)){
17. echo "EMP ID :{$row['id']} <br> ".
18. "EMP NAME : {$row['name']} <br> ".
19. "EMP SALARY : {$row['salary']} <br> ".
20. "--------------------------------<br>";
21. } //end of while
22. }else{
23. echo "0 results";
24. }
25. mysqli_close($conn);
26. ?>

Output:

Connected successfully
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------

PHP MySQL Order By


PHP mysql_query() function is used to execute select query with order by clause. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()

The order by clause is used to fetch data in ascending order or descending order on the
basis of column.

Let's see the query to select data from emp4 table in ascending order on the basis of name
column.

1. SELECT * FROM emp4 order by name

Let's see the query to select data from emp4 table in descending order on the basis of name
column.

1. SELECT * FROM emp4 order by name desc

PHP MySQLi Order by Example


Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6. $conn = mysqli_connect($host, $user, $pass,$dbname);
7. if(!$conn){
8. die('Could not connect: '.mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'SELECT * FROM emp4 order by name';
13. $retval=mysqli_query($conn, $sql);
14.
15. if(mysqli_num_rows($retval) > 0){
16. while($row = mysqli_fetch_assoc($retval)){
17. echo "EMP ID :{$row['id']} <br> ".
18. "EMP NAME : {$row['name']} <br> ".
19. "EMP SALARY : {$row['salary']} <br> ".
20. "--------------------------------<br>";
21. } //end of while
22. }else{
23. echo "0 results";
24. }
25. mysqli_close($conn);
26. ?>

Output:

Connected successfully
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------

PHP Programs
Sum of Digits
To find sum of digits of a number just add all the digits.

For example,

1. 14597 = 1 + 4 + 5 + 9 + 7
2. 14597 = 26

Logic:

o Take the number.


o Divide the number by 10.
o Add the remainder to a variable.
o Repeat the process until remainder is 0.

Example:

Given program shows the sum of digits of 14597.

1. <?php
2. $num = 14597;
3. $sum=0; $rem=0;
4. for ($i =0; $i<=strlen($num);$i++)
5. {
6. $rem=$num%10;
7. $sum = $sum + $rem;
8. $num=$num/10;
9. }
10. echo "Sum of digits 14597 is $sum";
11. ?>

Output:

Even Odd Program


Even numbers are those which are divisible by 2. Numbers like 2,4,6,8,10, etc are even.

Odd numbers are those which are not divisible by 2. Numbers Like 1, 3, 5, 7, 9, 11, etc are
odd.

Logic:

o Take a number.
o Divide it by 2.
o If the remainder is 0, print number is even.

Even Odd Program in PHP


A program to check 1233456 is odd or even is shown.

Example:

1. <?php
2. $number=1233456;
3. if($number%2==0)
4. {
5. echo "$number is Even Number";
6. }
7. else
8. {
9. echo "$number is Odd Number";
10. }
11. ?>

Output:

Even Odd Program using Form in PHP


By inserting value in a form we can check that inserted value is even or odd.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter a number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST){
12. $number = $_POST['number'];
13. //divide entered number by 2
14. //if the reminder is 0 then the number is even otherwise the number is odd
15. if(($number % 2) == 0){
16. echo "$number is an Even number";
17. }else{
18. echo "$number is Odd number";
19. }
20. }
21. ?>
Output:

On entering the number 23456, following output appears.

On entering the number 285965, following output appears.

Prime Number
A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7,
11, 13, 17, etc. are prime numbers.

o 2 is the only even prime number.


o It is a natural number greater than 1 and so 0 and 1 are not prime numbers.

Prime number in PHP


Example:

Here is the Program to list the first 15 prime numbers.

1. <?php
2. $count = 0;
3. $num = 2;
4. while ($count < 15 )
5. {
6. $div_count=0;
7. for ( $i=1; $i<=$num; $i++)
8. {
9. if (($num%$i)==0)
10. {
11. $div_count++;
12. }
13. }
14. if ($div_count<3)
15. {
16. echo $num." , ";
17. $count=$count+1;
18. }
19. $num=$num+1;
20. }
21. ?>

Output:

Prime Number using Form in PHP


Example:

We'll show a form, which will check whether a number is prime or not.

1. <form method="post">
2. Enter a Number: <input type="text" name="input"><br><br>
3. <input type="submit" name="submit" value="Submit">
4. </form>
5. <?php
6. if($_POST)
7. {
8. $input=$_POST['input'];
9. for ($i = 2; $i <= $input-1; $i++) {
10. if ($input % $i == 0) {
11. $value= True;
12. }
13. }
14. if (isset($value) && $value) {
15. echo 'The Number '. $input . ' is not prime';
16. } else {
17. echo 'The Number '. $input . ' is prime';
18. }
19. }
20. ?>

Output:

On entering number 12, we get the following output. It states that 12 is not a prime
number.

On entering number 97, we get the following output. It states that 97 is a prime number.

Table of Number
A table of a number can be printed using a loop in program.

Logic:

o Define the number.


o Run for loop.
o Multiply the number with for loop output.

Example:

We'll print the table of 7.

1. <?php
2. define('a', 7);
3. for($i=1; $i<=10; $i++)
4. {
5. echo $i*a;
6. echo '<br>';
7. }
8. ?>

Output:

Factorial Program
The factorial of a number n is defined by the product of all the digits from 1 to n (including
1 and n).

For example,

1. 4! = 4*3*2*1 = 24
2. 6! = 6*5*4*3*2*1 = 720

Note:

o It is denoted by n! and is calculated only for positive integers.


o Factorial of 0 is always 1.

The simplest way to find the factorial of a number is by using a loop.

There are two ways to find factorial in PHP:

o Using loop
o Using recursive method
Logic:
o Take a number.
o Take the descending positive integers.
o Multiply them.

Factorial in PHP
Factorial of 4 using for loop is shown below.

Example:

1. <?php
2. $num = 4;
3. $factorial = 1;
4. for ($x=$num; $x>=1; $x--)
5. {
6. $factorial = $factorial * $x;
7. }
8. echo "Factorial of $num is $factorial";
9. ?>

Output:

Factorial using Form in PHP


Below program shows a form through which you can calculate factorial of any number.

Example:

1. <html>
2. <head>
3. <title>Factorial Program using loop in PHP</title>
4. </head>
5. <body>
6. <form method="post">
7. Enter the Number:<br>
8. <input type="number" name="number" id="number">
9. <input type="submit" name="submit" value="Submit" />
10. </form>
11. <?php
12. if($_POST){
13. $fact = 1;
14. //getting value from input text box 'number'
15. $number = $_POST['number'];
16. echo "Factorial of $number:<br><br>";
17. //start loop
18. for ($i = 1; $i <= $number; $i++){
19. $fact = $fact * $i;
20. }
21. echo $fact . "<br>";
22. }
23. ?>
24. </body>
25. </html>

Output:

Factorial using Recursion in PHP


Factorial of 6 using recursion method is shown.

Example:

1. <?php
2. function fact ($n)
3. {
4. if($n <= 1)
5. {
6. return 1;
7. }
8. else
9. {
10. return $n * fact($n - 1);
11. }
12. }
13.
14. echo "Factorial of 6 is " .fact(6);
15. ?>

Output:

Armstrong Number
An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.

0, 1, 153, 371, 407, 471, etc are Armstrong numbers.

For example,

1. 407 = (4*4*4) + (0*0*0) + (7*7*7)


2. = 64 + 0 + 343
3. 407 = 407

Logic:

o Take the number.


o Store it in a variable.
o Take a variable for sum.
o Divide the number with 10 until quotient is 0.
o Cube the remainder.
o Compare sum variable and number variable.
Armstrong number in PHP
Below program checks whether 407 is Armstrong or not.

Example:

1. <?php
2. $num=407;
3. $total=0;
4. $x=$num;
5. while($x!=0)
6. {
7. $rem=$x%10;
8. $total=$total+$rem*$rem*$rem;
9. $x=$x/10;
10. }
11. if($num==$total)
12. {
13. echo "Yes it is an Armstrong number";
14. }
15. else
16. {
17. echo "No it is not an armstrong number";
18. }
19. ?>

Output:

Look at the above snapshot, the output displays that 407 is an Armstrong number.

Armstrong number using Form in PHP


A number is Armstrong or can also be checked using a form.
Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter the Number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST)
12. {
13. //get the number entered
14. $number = $_POST['number'];
15. //store entered number in a variable
16. $a = $number;
17. $sum = 0;
18. //run loop till the quotient is 0
19. while( $a != 0 )
20. {
21. $rem = $a % 10; //find reminder
22. $sum = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum var
iable till the loop ends
23. $a = $a / 10; //find quotient. if 0 then loop again
24. }
25. //if the entered number and $sum value matches then it is an armstrong number
26. if( $number == $sum )
27. {
28. echo "Yes $number an Armstrong Number";
29. }else
30. {
31. echo "$number is not an Armstrong Number";
32. }
33. }
34. ?>

Output:

On entering the number 371, we got the following output.


On entering the number 9999, we got the following output.

Palindrome Number
A palindrome number is a number which remains same when its digits are reversed.

For example, number 24142 is a palindrome number. On reversing it we?ll get the same
number.

Logic:

o Take a number.
o Reverse the input number.
o Compare the two numbers.
o If equal, it means number is palindrome

Palindrome Number in PHP


Example:

1. <?php
2. function palindrome($n){
3. $number = $n;
4. $sum = 0;
5. while(floor($number)) {
6. $rem = $number % 10;
7. $sum = $sum * 10 + $rem;
8. $number = $number/10;
9. }
10. return $sum;
11. }
12. $input = 1235321;
13. $num = palindrome($input);
14. if($input==$num){
15. echo "$input is a Palindrome number";
16. } else {
17. echo "$input is not a Palindrome";
18. }
19. ?>

Output:

Palindrome Number using Form in PHP


Example:

We'll show the logic to check whether a number is palindrome or not.

1. <form method="post">
2. Enter a Number: <input type="text" name="num"/><br>
3. <button type="submit">Check</button>
4. </form>
5. <?php
6. if($_POST)
7. {
8. //get the value from form
9. $num = $_POST['num'];
10. //reversing the number
11. $reverse = strrev($num);
12.
13. //checking if the number and reverse is equal
14. if($num == $reverse){
15. echo "The number $num is Palindrome";
16. }else{
17. echo "The number $num is not a Palindrome";
18. }
19. }
20. ?>

Output:

On entering the number 23432, we get the following output.

On entering the number 12345, we get the following output.

Fibonacci Series
Fibonacci series is the one in which you will get your next term by adding previous two
numbers.

For example,

1. 0 1 1 2 3 5 8 13 21 34
2. Here, 0 + 1 = 1
3. 1+1=2
4. 3+2=5

and so on.

Logic:
o Initializing first and second number as 0 and 1.
o Print first and second number.
o From next number, start your loop. So third number will be the sum of the first two
numbers.

Example:

We'll show an example to print the first 12 numbers of a Fibonacci series.

1. <?php
2. $num = 0;
3. $n1 = 0;
4. $n2 = 1;
5. echo "<h3>Fibonacci series for first 12 numbers: </h3>";
6. echo "\n";
7. echo $n1.' '.$n2.' ';
8. while ($num < 10 )
9. {
10. $n3 = $n2 + $n1;
11. echo $n3.' ';
12. $n1 = $n2;
13. $n2 = $n3;
14. $num = $num + 1;
15. ?>

Output:

Fibonacci series using Recursive function


Recursion is a phenomenon in which the recursion function calls itself until the base
condition is reached.

1. <?php
2. /* Print fiboancci series upto 12 elements. */
3. $num = 12;
4. echo "<h3>Fibonacci series using recursive function:</h3>";
5. echo "\n";
6. /* Recursive function for fibonacci series. */
7. function series($num){
8. if($num == 0){
9. return 0;
10. }else if( $num == 1){
11. return 1;
12. } else {
13. return (series($num-1) + series($num-2));
14. }
15. }
16. /* Call Function. */
17. for ($i = 0; $i < $num; $i++){
18. echo series($i);
19. echo "\n";
20. }

Reverse number
A number can be written in reverse order.

For example

12345 = 54321

Logic:

o Declare a variable to store reverse number and initialize it with 0.


o Multiply the reverse number by 10, add the remainder which comes after dividing
the number by 10.

Reversing Number in PHP


Example:

Below progrem shows digits reversal of 23456.

1. <?php
2. $num = 23456;
3. $revnum = 0;
4. while ($num > 1)
5. {
6. $rem = $num % 10;
7. $revnum = ($revnum * 10) + $rem;
8. $num = ($num / 10);
9. }
10. echo "Reverse number of 23456 is: $revnum";
11. ?>

Output:

Reversing Number With strrev () in PHP


Example:

Function strrev() can also be used to reverse the digits of 23456.

1. <?php
2. function reverse($number)
3. {
4. /* writes number into string. */
5. $num = (string) $number;
6. /* Reverse the string. */
7. $revstr = strrev($num);
8. /* writes string into int. */
9. $reverse = (int) $revstr;
10. return $reverse;
11. }
12. echo reverse(23456);
13. ?>

Output:/strong>
Reverse String
A string can be reversed either using strrev() function or simple PHP code.

For example, on reversing JAVATPOINT it will become TNIOPTAVAJ.

Logic:

o Assign the string to a variable.


o Calculate length of the string.
o Declare variable to hold reverse string.
o Run for loop.
o Concatenate string inside for loop.
o Display reversed string.

Reverse String using strrev() function


A reverse string program using strrev() function is shown.

Example:

1. <?php
2. $string = "JAVATPOINT";
3. echo "Reverse string of $string is " .strrev ( $string );
4. ?>

Output:
Reverse String Without using strrev() function
A reverse string program without using strrev() function is shown.

Example:

1. <?php
2. $string = "JAVATPOINT";
3. $length = strlen($string);
4. for ($i=($length-1) ; $i >= 0 ; $i--)
5. {
6. echo $string[$i];
7. }
8. ?>

Output:

Swapping two numbers


Two numbers can be swapped or interchanged. It means first number will become second
and second number will become first.

For example

1. a = 20, b = 30
2. After swapping,
3. a = 30, b = 20

There are two methods for swapping:

o By using third variable.


o Without using third variable.

Swapping Using Third Variable


Swap two numbers 45 and 78 using a third variable.
Example:

1. <?php
2. $a = 45;
3. $b = 78;
4. // Swapping Logic
5. $third = $a;
6. $a = $b;
7. $b = $third;
8. echo "After swapping:<br><br>";
9. echo "a =".$a." b=".$b;
10. ?>

Output:

Swapping Without using Third Variable


Swap two numbers without using a third variable is done in two ways:

o Using arithmetic operation + and ?


o Using arithmetic operation * and /

Example for (+ and -):

1. <?php
2. $a=234;
3. $b=345;
4. //using arithmetic operation
5. $a=$a+$b;
6. $b=$a-$b;
7. $a=$a-$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>
Output:

Example for (* and /):

1. <?php
2. $a=234;
3. $b=345;
4. // using arithmetic operation
5. $a=$a*$b;
6. $b=$a/$b;
7. $a=$a/$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>

Output:

Adding Two Numbers


There are three methods to add two numbers:

o Adding in simple code in PHP


o Adding in form in PHP
o Adding without using arithmetic operator (+).

Adding in Simple Code


Addition of two numbers 15 and 30 is shown here.

Example:
1. <?php
2. $x=15;
3. $y=30;
4. $z=$x+$y;
5. echo "Sum: ",$z;
6. ?>

Output:

Adding in Form
Two numbers can be added by passing input value in the form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Add">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1+$number2;
16. echo "The sum of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>
Output:

Adding in Simple Code


Two numbers can be added by passing input value in the form but without using (+)
operator.

1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Add">
8. </form>
9. </body>
10. <?php
11. @$number1=$_GET['number1'];
12. @$number2=$_GET['number2'];
13. for ($i=1; $i<=$number2; $i++)
14. {
15. $number1++;
16. }
17. echo "Sum of $number1 and $number2 is=".$number2;
18. ?>

Output:
Subtracting Two Numbers
There are three methods to subtract two numbers:

o Subtraction in simple code in PHP


o Subtraction in form in PHP
o Subtraction without using arithmetic operator (+).

Subtraction in Simple Code


Subtraction of two numbers 30 and 15 is shown.

Example:

1. <?php
2. $x=30;
3. $y=15;
4. $z=$x-$y;
5. echo "Difference: ",$z;
6. ?>

Output:

Subtraction in Form
By inserting values in the form two numbers can be subtracted.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Subtract">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1-$number2;
16. echo "The difference of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>

Output:

Subtraction in Form without (-) Operator


By inserting values in the form two numbers can be subtracted but without using (-)
operator.

Example:
1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Subtract">
8. </form>
9. </body>
10. <?php
11.
12. @$number1=$_GET['number1'];
13. @$number2=$_GET['number2'];
14. for ($i=1; $i<=$number2; $i++)
15. {
16. $number1--;
17. }
18. echo "Difference=".$number1;
19. ?>

Output:

Area of Triangle
Area of a triangle is calculated by the following Mathematical formula,

1. (base * height) / 2 = Area

Area of Triangle in PHP


Program to calculate area of triangle with base as 10 and height as 15 is shown.

Example:
1. <?php
2. $base = 10;
3. $height = 15;
4. echo "area with base $base and height $height= " . ($base * $height) / 2;
5. ?>

Output:

Area of Triangle with Form in PHP


Program to calculate area of triangle by inserting values in the form is shown.

Example:

1. <html>
2. <body>
3. <form method = "post">
4. Base: <input type="number" name="base">
5. <br><br>
6. Height: <input type="number" name="height"><br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $base = $_POST['base'];
15. $height = $_POST['height'];
16. $area = ($base*$height) / 2;
17. echo "The area of a triangle with base as $base and height as $height is $area";
18. }
19. ?>

Output:
Area of a Rectangle
Area of a rectangle is calculated by the mathematical formula,

1. Length ∗ Breadth = Area

Logic:

o Take two variables.


o Multiply both of them.

Area of Rectangle in PHP


Program to calculate area of rectangle with length as 14 and width as 12 is shown.

Example:

1. <?php
2. $length = 14;
3. $width = 12;
4. echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
5. ?>

Output:

Area of Rectangle with Form in PHP


Program to calculate area of rectangle by inserting values in the form is shown.

Example:

1. <html>
2. <body>
3. <form method = "post">
4. Width: <input type="number" name="width">
5. <br><br>
6. Length: <input type="number" name="length"> <br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $width = $_POST['width'];
15. $length = $_POST['length'];
16. $area = $width*$length;
17. echo "The area of a rectangle with $width x $length is $area";
18. }
19. ?>

Output:

Leap Year Program


A leap year is the one which has 366 days in a year. A leap year comes after every four
years. Hence a leap year is always a multiple of four.

For example, 2016, 2020, 2024, etc are leap years.


Leap Year Program
This program states whether a year is leap year or not from the specified range of years
(1991 - 2016).

Example:

1. <?php
2. function isLeap($year)
3. {
4. return (date('L', mktime(0, 0, 0, 1, 1, $year))==1);
5. }
6. //For testing
7. for($year=1991; $year<2016; $year++)
8. {
9. If (isLeap($year))
10. {
11. echo "$year : LEAP YEAR<br />\n";
12. }
13. else
14. {
15. echo "$year : Not leap year<br />\n";
16. }
17. }
18. ?>

Output:
Leap Year Program in Form
This program states whether a year is leap year or not by inserting a year in the form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter the Year: <input type="text" name="year">
5. <input type="submit" name="submit" value="Submit">
6. </form>
7. </body>
8. </html>
9. <?php
10. if($_POST)
11. {
12. //get the year
13. $year = $_POST['year'];
14. //check if entered value is a number
15. if(!is_numeric($year))
16. {
17. echo "Strings not allowed, Input should be a number";
18. return;
19. }
20. //multiple conditions to check the leap year
21. if( (0 == $year % 4) and (0 != $year % 100) or (0 == $year % 400) )
22. {
23. echo "$year is a Leap Year";
24. }
25. else
26. {
27. echo "$year is not a Leap Year";
28. }
29. }
30. ?>

Output:

On entering year 2016, we get the following output.

On entering year 2019, we get the following output.

Alphabet Triangle Method


There are three methods to print the alphabets in a triangle or in a pyramid form.

o range() with for loop


o chr() with for loop
o range() with foreach loop

Logic:
o Two for loops are used.
o First for loop set conditions to print 1 to 5 rows.
o Second for loop set conditions in decreasing order.

Using range() function


This range function stores values in an array from A to Z. here, we use two for loops.

Example:

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Using chr() function


Here the chr() function returns the value of the ASCII code. The ASCII value of A, B, C, D, E
is 65, 66, 67, 68, 69 respectively. Here, also we use two for loops.

Example:

1. <?php
2. for( $i=65; $i<=69; $i++){
3. for($j=5; $j>=$i-64; $j--){
4. echo chr($i);
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Using range() function with foreach


In this methods we use foreach loop with range() function. The range() function contain
values in an array and returns it with $char variable. The for loop is used to print the
output.

Example:

1. <?php
2. $k=1;
3. foreach(range('A','Z') as $char){
4. for($i=5; $i>=$k; $i--){
5. echo $char;
6. }
7. echo "<br>";
8. $k=$k+1;

Output:

Alphabet Triangle Pattern


Some different alphabet triangle patterns using range() function in PHP are shown below.
Pattern 1

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 2

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 3

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 4

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=4; $j>=$i; $j--){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 5

1. <?php
2. $alpha = range('A', 'Z');
3. for ($i=5; $i>=1; $i--) {
4. for($j=0; $j<=$i; $j++) {
5. echo ' ';
6. }
7. $j--;
8. for ($k=0; $k<=(5-$j); $k++) {
9. echo $alpha[$k];
10. }
11. echo "<br>\n";
12. }
13. ?>

Output:

Number Triangle
Number triangle in PHP can be printed using for and foreach loop. There are a lot of
patterns in number triangle. Some of them are show here.

Pattern1

1. <?php
2. $k=1;
3. for($i=0;$i<4;$i++){
4. for($j=0;$j<=$i;$j++){
5. echo $k." ";
6. $k++;
7. }
8. echo "<br>";
9. }
10. ?>

Output:

Pattern 2

1. <?php
2. $k=1;
3. for($i=0;$i<5;$i++){
4. for($j=0;$j<=$i;$j++){
5. if($j%2==0)
6. {
7. $k=0;
8. }
9. else
10. {
11. $k=1;
12. }
13. echo $k." ";
14. }
15. echo "<br>";
16. }
17. ?>

Output:

Pattern 3

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 4
1. <?php
2. for($i=0;$i>=5;$i++){
3. for($j=1;$j>=$i;$j++){
4. echo $i;
5. }
6. echo "<br>";
7. }
8. ?<

Output:

Pattern 5

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 6

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 7

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 8

1. <?php
2. for($i=5;$i>=1;$i--){
3. for($j=$i;$j>=1;$j--){
4. echo $i." ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Star Triangle
The star triangle in PHP is made using for and foreach loop. There are a lot of star patterns.
We'll show some of them here.

Pattern 1

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 2

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Pattern 3

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($k=5;$k>=$i;$k--){
4. echo " ";
5. }
6. for($j=1;$j<=$i;$j++){
7. echo "* ";
8. }
9. echo "<br>";
10. }
11. for($i=4;$i>=1;$i--){
12. for($k=5;$k>=$i;$k--){
13. echo " ";
14. }
15. for($j=1;$j<=$i;$j++){
16. echo "* ";
17. }
18. echo "<br>";
19. }
20. ?>

Output:

Pattern 4

1. <?php
2. for($i=1; $i<=5; $i++){
3. for($j=1; $j<=$i; $j++){
4. echo ' * ';
5. }
6. echo '<br>';
7. }
8. for($i=5; $i>=1; $i--){
9. for($j=1; $j<=$i; $j++){
10. echo ' * ';
11. }
12. echo '<br>';
13. }
14. ?>

Output:

Pattern 5

1. <?php
2. for ($i=1; $i<=5; $i++)
3. {
4. for ($j=1; $j<=5; $j++)
5. {
6. echo '* ';
7. }
8. echo "</br>";
9. }
10. ?>

Output:
Pattern 6

1. <?php
2. for($i=5; $i>=1; $i--)
3. {
4. if($i%2 != 0)
5. {
6. for($j=5; $j>=$i; $j--)
7. {
8. echo "* ";
9. }
10. echo "<br>";
11. }
12. }
13. for($i=2; $i<=5; $i++)
14. {
15. if($i%2 != 0)
16. {
17. for($j=5; $j>=$i; $j--)
18. {
19. echo "* ";
20. }
21. echo "<br>";
22. }
23. }
24. ?>

Output:

Vous aimerez peut-être aussi