Master PHP Over Night
Master PHP Over Night
Master PHP Over Night
PHP is a server scripting language, and a powerful tool for making dynamic and
interactive Web pages.
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 References
Array functions
Calendar functions
Date functions
Directory functions
Error functions
Filesystem functions
Filter functions
FTP functions
HTTP functions
LibXML functions
Mail functions
Math functions
Misc functions
MySQLi functions
SimpleXML functions
String functions
Zip functions
PHP Exercises
Exercise:
Insert the missing part of the code below to output "Hello World".
"Hello World";
The perfect solution for professionals who need to balance work, family, and career
building.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
PHP 5 Introduction
PHP scripts are executed on the server.
Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
If you want to study these subjects first, find the tutorials on our Home page.
What is PHP?
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!
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?
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 5 Installation
What Do I Need?
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.
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.
<?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>
<?php
echo "Hello World!";
?>
</body>
</html>
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.
<!DOCTYPE html>
<html>
<body>
<?php
// This is 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>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
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>
Exercise:
Insert the missing part of the code below to output "Hello World".
"Hello World";
PHP 5 Variables
Variables are "containers" for storing information.
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.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
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)
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 . "!";
?>
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.
The scope of a variable is the part of the script where the variable can be
referenced/used.
local
global
static
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();
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();
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.
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.
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
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.
Exercise:
=" ";
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.
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;
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;
Variables can store data of different types, and different data types can do different
things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
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
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
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
$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
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.
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();
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.
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.
We will not talk about the resource type here, since it is an advanced topic.
PHP 5 Strings
The example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Reverse a String
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
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 PHP str_replace() function replaces some characters with some other characters in a
string.
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
The output of the code above will be: Hello Dolly!
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!
Exercise:
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
Syntax
Parameters:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
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
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.
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.
The PHP comparison operators are used to compare two values (number or string):
PHP has two operators that are specially designed for strings.
Exercise:
echo 10 5;
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.
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");
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");
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");
Exercise:
$a = 50;
$b = 10;
> {
echo "Hello World";
}
The switch statement is used to perform different actions based on different conditions.
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 break to 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!";
}
?>
Exercise:
Create a switch statement that will output "Hello" if $color is "red", and "welcome" if
$color is "green".
($color) {
"red":
echo "Hello";
break;
"green":
echo "Welcome";
break;
}
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.
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 while loop executes a block of code as long as the specified condition is true.
Syntax
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 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.
Exercise:
Output $i as long as $i is less than 6.
$i = 1;
($i < 6)
echo $i;
$i++;
The for loop is used when you know in advance how many times the script should run.
Syntax
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The foreach loop works only on arrays, and is used to loop through each key/value pair
in an array.
Syntax
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");
Exercise:
PHP 5 Functions
The real power of PHP comes from its functions; it has more than 1000 built-in
functions.
Besides the built-in PHP functions, we can create our own functions.
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!
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:
Example
<?php
function writeMsg() {
echo "Hello world!";
}
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");
?>
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);
?>
Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
Exercise:
{
echo "Hello World!";
}
PHP 5 Arrays
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?
An array can hold many values under a single name, and you can access the values by
referring to an index number.
array();
The index can be assigned automatically (index always starts at 0), like this:
$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] . ".";
?>
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);
?>
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);
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
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");
Multidimensional Arrays
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!
Exercise:
In this chapter, we will go through the following PHP array sort functions:
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);
?>
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);
?>
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);
?>
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);
?>
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);
?>
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);
?>
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!
Exercise:
Use the correct array method to sort the $colors array alphabetically.
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.
$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
Returns the filename of the currently executing
$_SERVER['PHP_SELF']
script
Returns the version of the Common Gateway
$_SERVER['GATEWAY_INTERFACE']
Interface (CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
Returns the name of the host server (such as
$_SERVER['SERVER_NAME']
www.w3schools.com)
Returns the server identification string (such as
$_SERVER['SERVER_SOFTWARE']
Apache/2.2.24)
Returns the name and revision of the information
$_SERVER['SERVER_PROTOCOL']
protocol (such as HTTP/1.1)
Returns the request method used to access the
$_SERVER['REQUEST_METHOD']
page (such as POST)
Returns the timestamp of the start of the request
$_SERVER['REQUEST_TIME']
(such as 1377687496)
Returns the query string if the page is accessed via
$_SERVER['QUERY_STRING']
a query string
Returns the Accept header from the current
$_SERVER['HTTP_ACCEPT']
request
Returns the Accept_Charset header from the
$_SERVER['HTTP_ACCEPT_CHARSET']
current request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
Returns the complete URL of the page from which
$_SERVER['HTTP_REFERER']
the current page was called
Is the script queried through a secure HTTP
$_SERVER['HTTPS']
protocol
Returns the IP address from where the user is
$_SERVER['REMOTE_ADDR']
viewing the current page
Returns the Host name from where the user is
$_SERVER['REMOTE_HOST']
viewing the current page
Returns the port being used on the user's machine
$_SERVER['REMOTE_PORT']
to communicate with the web server
Returns the absolute pathname of the currently
$_SERVER['SCRIPT_FILENAME']
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)
Returns the port on the server machine being used
$_SERVER['SERVER_PORT']
by the web server for communication (such as 80)
Returns the server version and virtual host name
$_SERVER['SERVER_SIGNATURE']
which are added to server-generated pages
Returns the file system based path to the current
$_SERVER['PATH_TRANSLATED']
script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
PHP $_REQUEST
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>
<?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>
<?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".
<html>
<body>
</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.
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
Tip: You will learn more about $_POST and $_GET in the PHP Forms chapter.
PHP 5 Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
The example below displays a simple HTML form with two input fields and a submit
button:
Example
<html>
<body>
</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>
</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>
</body>
</html>
<html>
<body>
</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.
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!
Both GET and POST create an array (e.g. array( key => value, 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.
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.
Note: GET should NEVER be used for sending passwords or other sensitive information!
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.
Next, lets see how we can process PHP forms the secure way!
Exercise:
If the form in the white section below gets submitted, how can you, in welcome.php,
output the value from the "first name" field?
<html>
<body>
</body>
</html>
This and the next chapters show how to use PHP to validate form data.
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:
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:
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
When the form is submitted, the form data is sent with method="post".
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.
The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with < and >. This prevents
attackers from exploiting the code by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
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.
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:
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/script%3E
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.
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/"><script>alert('hacked')</script>">
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:
<script>location.href('http://www.hacked.com')</script>
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).
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.
This chapter shows how to make input fields required and create error messages if
needed.
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 @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
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"]);
}
}
?>
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>
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?".
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.
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";
}
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";
}
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"]);
}
}
?>
The next step is to show how to prevent the form from emptying all the input fields
when the user submits 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):
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
Example
* required field
Name: *
E-mail: *
Website:
Comment:
Your Input:
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.
The dimension of an array indicates the number of indices you need to select an
element.
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>";
}
?>
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 time
A timestamp is a sequence of characters, denoting the date and/or time at which a
certain event occurred.
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:
Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional formatting.
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");
?>
Use the date() function to automatically update the copyright year on your website:
Example
Here are some characters that are commonly used for times:
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!
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");
?>
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);
?>
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.
The example below outputs the dates for the next six Saturdays:
Example
<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $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!
Exercise:
Use the correct date function to output todays day of the week (monday, tuesday etc.).
echo ;
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.
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';
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
Example
<html>
<body>
</body>
</html>
Example 2
<?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>
</body>
</html>
Example 3
<?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>
</body>
</html>
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>
</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 the require statement returned a fatal
error:
Example
<html>
<body>
</body>
</html>
Use include when the file is not required and application should continue when file is
not found.
Exercise:
<?php ;?>
File handling is an important part of any web application. You often need to open and
process a file for different tasks.
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.
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:
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.
Test Yourself With Exercises
Exercise:
Assume we have a file named "webdict.txt", write the correct syntax to open and read
the file content.
echo ;
In this chapter we will teach you how to open, read, and close a file on the server.
A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function.
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.
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if
w
it doesn't exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File pointer
a
starts at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for write only. Returns FALSE and an error if file already
x
exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for read/write. Erases the contents of the file or creates a new file if
w+
it doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. The existing data in file is preserved. File pointer
a+
starts at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for read/write. Returns FALSE and an error if file already
x+
exists
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"));
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);
?>
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.
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);
?>
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.
Exercise:
Open a file, and write the correct syntax to output one character at the time, until end-
of-file.
while(! ($myfile)) {
echo ($myfile);
}
In this chapter we will teach you how to create and write to a file on the server.
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
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 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.
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
However, with ease comes danger, so always be careful when allowing file uploads!
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Without the requirements above, the file upload will not work.
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.
<?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;
}
}
?>
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.
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:
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:
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:
<?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.";
}
}
?>
PHP 5 Cookies
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.
Syntax
Only the name parameter is required. All other parameters are optional.
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).
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>
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>
For a complete reference of HTTP functions, go to our complete PHP HTTP Reference.
Exercise:
PHP 5 Sessions
A session is a way to store information (in variables) to be used across multiple pages.
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.
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.
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>
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.
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>
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();
</body>
</html>
Exercise:
PHP Filters
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>
Many web applications receive external input. External input/data can be:
The filter_var() function filters a single variable with a specified filter. It takes two pieces
of data:
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;
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;
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";
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";
// 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");
}
?>
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";
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
For a complete reference of all filter functions, go to our complete PHP Filter Reference.
Check each filter to see what options and flags are available.
The reference contains a brief description, and examples of use, for each function!
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;
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";
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";
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>";
For a complete reference of all filter functions, go to our complete PHP Filter Reference.
Check each filter to see what options and flags are available.
The reference contains a brief description, and examples of use, for each function!
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.
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.
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:
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:
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
Required. Specifies the error report level for the user-defined error.
error_level 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
Optional. Specifies an array containing every variable, and their values,
error_context
in use when the error occurred
These error report levels are the different types of error the user-defined error handler can be used for:
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.
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";
}
//trigger error
echo($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");
}
?>
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:
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();
}
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
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.
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");
}
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
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.
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.
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.
<?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);
?>
To avoid the error from the example above, we need to create the proper code to handle
an exception.
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Example explained:
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.
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.
<?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);
}
}
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:
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(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:
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);
}
}
Example explained:
The code above tests if the email-address contains the string "example" in it, if it does,
the exception is re-thrown:
If the exception is not caught in its current "try" block, it will search for a catch block on
"higher levels".
set_exception_handler('myException');
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.
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.
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.
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.
XMLReader
XML Expat Parser
PHP SimpleXML Parser
SimpleXML is a PHP extension that allows us to easily manipulate and get XML
data.
Installation
As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is
required to use these functions.
$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
SimpleXML is a PHP extension that allows us to easily manipulate and get XML
data.
The built-in XML Expat Parser makes it possible to process XML documents in PHP.
The XML Expat Parser
<from>Jani</from>
The XML Expat Parser functions are part of the PHP core. There is no installation needed
to use these functions.
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();
// 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)));
}
Example explained:
For more information about the PHP Expat functions, visit our PHP XML Parser
Reference.
Installation
The DOM parser functions are part of the PHP core. There is no installation needed to
use these functions.
We want to initialize the XML parser, load the xml, and output it:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
If you select "View source" in the browser window, you will see the following HTML:
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.
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>";
}
?>
#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.
If you want to learn more about the XML DOM, please visit our XML tutorial.
AJAX Introduction
AJAX is about updating parts of a web page, without reloading the whole page.
What is AJAX?
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.
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.
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.
If you want to learn more about AJAX, visit our AJAX tutorial.
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.
Example
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp. {
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" ></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.
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";
$hint = "";
The following example will demonstrate how a web page can fetch information from a
database with AJAX:
Example
The database table we use in the example above looks like this:
Hometow
id FirstName LastName Age Job
n
1 Peter Griffin 41 Quahog Brewery
Piano
2 Lois Griffin 40 Newport
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.
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. {
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" > <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:
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:
The following example will demonstrate how a web page can fetch information from an
XML file with AJAX:
Example
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. {
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" ><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>
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 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"];
$x=$xmlDoc->getElementsByTagName('ARTIST');
$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:
The following example will demonstrate a live search, where you get search results while
you type.
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.
<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. {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
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" ><div id="livesearch"></div>
</form>
</body>
</html>
If the input field is not empty, the showResult() function executes the following:
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');
If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
The following example will demonstrate an RSS reader, where the RSS-feed is loaded into
a webpage without reloading:
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. {
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 ><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 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"];
When a request for an RSS feed is sent from the JavaScript, the following happens:
AJAX Poll
The following example will demonstrate a poll where the result is shown without
reloading.
Yes:
No:
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. {
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" ><br>No:
<input type="radio" name="vote" value="1" ></form>
</div>
</body>
</html>
The page on the server called by the JavaScript above is a PHP file called
"poll_vote.php":
<?php
$vote = $_REQUEST['vote'];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
<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:
The text file (poll_result.txt) is where we store the data from the poll.
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).
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
Creates an array by using the elements from one "keys" array
array_combine()
and one "values" array
array_count_values() Counts all the values of an array
Compare arrays, and returns the differences (compare values
array_diff()
only)
Compare arrays, and returns the differences (compare keys and
array_diff_assoc()
values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
Compare arrays, and returns the differences (compare keys and
array_diff_uassoc()
values, using a user-defined key comparison function)
Compare arrays, and returns the differences (compare keys only,
array_diff_ukey()
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)
Compare arrays and returns the matches (compare keys and
array_intersect_assoc()
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)
Compare arrays, and returns the matches (compare keys only,
array_intersect_ukey()
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
Sends each value of an array to a user-made function, which
array_map()
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
Inserts a specified number of items, with a specified value, to an
array_pad()
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
Replaces the values of the first array with the values from
array_replace()
following arrays
array_replace_recursiv Replaces the values of the first array with the values from
e() 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
Removes the first element from an array, and returns the value
array_shift()
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
Compare arrays, and returns the differences (compare values
array_udiff()
only, using a user-defined key comparison function)
Compare arrays, and returns the differences (compare keys and
array_udiff_assoc() values, using a built-in function to compare the keys and a user-
defined function to compare the values)
Compare arrays, and returns the differences (compare keys and
array_udiff_uassoc()
values, using two user-defined key comparison functions)
Compare arrays, and returns the matches (compare values only,
array_uintersect()
using a user-defined key comparison function)
Compare arrays, and returns the matches (compare keys and
array_uintersect_assoc(
values, using a built-in function to compare the keys and a user-
)
defined function to compare the values)
array_uintersect_uasso Compare arrays, and returns the matches (compare keys and
c() 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
Sorts an associative array in descending order, according to the
arsort()
value
Sorts an associative array in ascending order, according to the
asort()
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
Sorts an associative array in descending order, according to the
krsort()
key
Sorts an associative array in ascending order, according to the
ksort()
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
Sorts an array by values using a user-defined comparison
uasort()
function
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function
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.
Function Description
Returns the number of days in a month for a specified year
cal_days_in_month()
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
Returns the Unix timestamp for midnight on Easter of a
easter_date()
specified year
Returns the number of days after March 21, that the Easter
easter_days()
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
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
PHP
Name Description Default
Version
The default timezone (used by all date/time
date.timezone "" PHP 5.1
functions)
date.default_latitud The default latitude (used by date_sunrise() and "31.7667
PHP 5.0
e date_sunset()) "
date.default_longitu The default longitude (used by date_sunrise()
"35.2333" PHP 5.0
de and date_sunset())
The default sunrise zenith (used by
date.sunrise_zenith "90.83" PHP 5.0
date_sunrise() and date_sunset())
The default sunset zenith (used by
date.sunset_zenith "90.83" PHP 5.0
date_sunrise() and date_sunset())
Function Description
checkdate() Validates a Gregorian date
Adds days, months, years, hours, minutes, and
date_add()
seconds to a date
Returns a new DateTime object formatted
date_create_from_format()
according to a specified format
date_create() Returns a new DateTime object
date_date_set() Sets a new date
Returns the default timezone used by all date/time
date_default_timezone_get()
functions
Sets the default timezone used by all date/time
date_default_timezone_set()
functions
date_diff() Returns the difference between two dates
Returns a date formatted according to a specified
date_format()
format
date_get_last_errors() Returns the warnings/errors found in a date string
date_interval_create_from_date_stri Sets up a DateInterval from the relative parts of the
ng() 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
Returns an associative array with detailed info
date_parse_from_format() about a specified date, according to a specified
format
Returns an associative array with detailed info
date_parse()
about a specified date
Subtracts days, months, years, hours, minutes, and
date_sub()
seconds from a date
Returns an array containing info about
date_sun_info() sunset/sunrise and twilight begin/end, for a
specified day and location
Returns the sunrise time for a specified day and
date_sunrise()
location
Returns the sunset time for a specified day and
date_sunset()
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
Returns date/time information of a timestamp or
getdate()
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
Formats a GMT/UTC date and time according to
gmstrftime()
locale settings
idate() Formats a local time/date as integer
localtime() Returns the local time
Returns the current Unix timestamp with
microtime()
microseconds
mktime() Returns the Unix timestamp for a date
Formats a local time and/or date according to
strftime()
locale settings
strptime() Parses a time/date generated with strftime()
Parses an English textual datetime into a Unix
strtotime()
timestamp
time() Returns the current time as a Unix timestamp
Returns an associative array containing dst, offset,
timezone_abbreviations_list()
and the timezone name
Returns an indexed array with all timezone
timezone_identifiers_list()
identifiers
Returns location information for a specified
timezone_location_get()
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
Constant Description
DATE_ATOM Atom (example: 2005-08-15T16:13:03+0000)
HTTP Cookies (example: Sun, 14 Aug 2005 16:13:03
DATE_COOKIE
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)
World Wide Web Consortium (example: 2005-08-
DATE_W3C
14T16:13:03+0000)
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.
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
Returns an array of files and directories of a specified
scandir()
directory
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
Defaul
Name Description Changeable
t
Sets the error reporting level (either an
error_reporting NULL 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)
Even when display_errors is on, errors
that occur during PHP's startup
display_startup_error sequence are not displayed
"0" PHP_INI_ALL
s Note: It is strongly recommended to
keep display_startup_errors off, except
for debugging
Defines whether script error messages
should be logged to the server's error
log or error_log.
log_errors "0" PHP_INI_ALL
Note: It is strongly advised to use error
logging instead of error displaying on
production web sites
Sets the maximum length of log_errors
in bytes. The value "0" can be used to
not apply any maximum length at all.
log_errors_max_len "1024" This length is applied to logged errors, PHP_INI_ALL
displayed errors, and also to
$php_errormsg (available since PHP
4.3)
Specifies whether to log repeated error
messages. When set to "1" it will not
ignore_repeated_erro
"0" log errors with repeated errors from PHP_INI_ALL
rs
the same file on the same line
(available since PHP 4.3)
Specifies whether to log repeated error
messages. When set to "1" it will not
ignore_repeated_sou
"0" log errors with repeated errors from PHP_INI_ALL
rce
different files or source lines (available
since PHP 4.3)
If set to "1" (the default), this
parameter will show a report of
report_memleaks "1" memory leaks detected by the Zend PHP_INI_ALL
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
PHP_INI_ALL
html_errors "1" Turns off HTML tags in error messages PHP_INI_SYSTEM
in PHP <= 4.2.3.
Turns off normal error reporting and
xmlrpc_errors "0" formats errors as XML-RPC error PHP_INI_SYSTEM
message (available since PHP 4.1)
Used as the value of the XML-RPC
xmlrpc_error_numbe
"0" faultCode element (available since PHP PHP_INI_ALL
r
4.1)
docref_root "" (available since PHP 4.3) PHP_INI_ALL
docref_ext "" (available since PHP 4.3.2) PHP_INI_ALL
Specifies a string to output before an
error_prepend_string NULL PHP_INI_ALL
error message
Specifies a string to output after an
error_append_string NULL PHP_INI_ALL
error message
Specifies the name of the file where
script errors should be logged. The file
should be writable by the web server's
error_log NULL PHP_INI_ALL
user. If the special value syslog is used,
the errors are sent to the system logger
instead
Function Description
debug_backtrace() Generates a backtrace
debug_print_backtrace() Prints a backtrace
error_get_last() Returns the last error that occurred
Sends an error message to a log, to a file, or to a mail
error_log()
account
error_reporting() Specifies which errors are reported
restore_error_handler() Restores the previous error handler
restore_exception_handle
Restores the previous exception handler
r()
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()
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.
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
Defaul
Name Description Changeable
t
Allows fopen()-type functions to work
allow_url_fopen "1" PHP_INI_SYSTEM
with URLs (available since PHP 4.0.4)
Defines the user agent for PHP to
user_agent NULL PHP_INI_ALL
send (available since PHP 4.3)
Sets the default timeout, in seconds,
default_socket_timeou
"60" for socket based streams (available PHP_INI_ALL
t
since PHP 4.3)
Defines the anonymous FTP password
from "" PHP_INI_ALL
(your email address)
When set to "1", PHP will examine the
data read by fgets() and file() to see if
auto_detect_line_endi
"0" it is using Unix, MS-Dos or Mac line- PHP_INI_ALL
ngs
ending characters (available since PHP
4.3)
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
Returns a line, with HTML and PHP tags removed, from an
fgetss()
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
Reads from an open file, until EOF, and writes the result to the
fpassthru()
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
Returns an array of filenames / directories matching a
glob()
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
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
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
Gets an external variable (e.g. from form input) and optionally
filter_input()
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
Removes all illegal characters from an
FILTER_SANITIZE_EMAIL 517
e-mail address
FILTER_SANITIZE_ENCODED 514 Removes/Encodes special characters
FILTER_SANITIZE_MAGIC_QUOTES 521 Apply addslashes()
Remove all characters, except digits,
FILTER_SANITIZE_NUMBER_FLOAT 520
+- and optionally .,eE
Removes all characters except digits
FILTER_SANITIZE_NUMBER_INT 519
and + -
FILTER_SANITIZE_SPECIAL_CHARS 515 Removes special characters
FILTER_SANITIZE_FULL_SPECIAL_CHARS
Removes tags/special characters from
FILTER_SANITIZE_STRING 513
a string
FILTER_SANITIZE_STRIPPED 513 Alias of FILTER_SANITIZE_STRING
Removes all illegal character from s
FILTER_SANITIZE_URL 518
URL
Do nothing, optionally strip/encode
FILTER_UNSAFE_RAW 516
special characters
102 Call a user-defined function to filter
FILTER_CALLBACK
4 data
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.
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
Downloads a file from the FTP server and saves it into an
ftp_fget()
open local file
Uploads from an open file and saves it to a file on the FTP
ftp_fput()
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)
Downloads a file from the FTP server and saves it into an
ftp_nb_fget()
open file (non-blocking)
Uploads from an open file and saves it to a file on the FTP
ftp_nb_fput()
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)
Returns a list of files in the specified directory on the FTP
ftp_nlist()
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
Returns a list of files with file information from a specified
ftp_rawlist()
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
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: 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
Defines a cookie to be sent along with the rest of the HTTP
setcookie()
headers
Defines a cookie (without URL encoding) to be sent along with the
setrawcookie()
rest of the HTTP headers
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
Function Description
Calculates the hash value needed by
ezmlm_hash()
EZMLM
Allows you to send emails directly from a
mail()
script
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.
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)
Returns the highest value in an array, or the highest value of
max()
several specified values
Returns the lowest value in an array, or the lowest value of several
min()
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
Constant Value Description
Version
INF INF The infinite PHP 4
2.718281828459045235
M_E Returns e PHP 4
4
0.577215664901532860
M_EULER Returns Euler constant PHP 4
61
1.144729885849400174 Returns the natural
M_LNPI PHP 5.2
14 logarithm of PI: log_e(pi)
0.693147180559945309 Returns the natural
M_LN2 PHP 4
42 logarithm of 2: log_e 2
2.302585092994045684 Returns the natural
M_LN10 PHP 4
02 logarithm of 10: log_e 10
1.442695040888963407 Returns the base-2
M_LOG2E PHP 4
4 logarithm of E: log_2 e
0.434294481903251827 Returns the base-10
M_LOG10E PHP 4
65 logarithm of E: log_10 e
3.141592653589793238
M_PI Returns Pi PHP 4
46
1.570796326794896619
M_PI_2 Returns Pi/2 PHP 4
23
0.785398163397448309
M_PI_4 Returns Pi/4 PHP 4
62
0.318309886183790671
M_1_PI Returns 1/Pi PHP 4
54
0.636619772367581343
M_2_PI Returns 2/Pi PHP 4
08
1.772453850905516027 Returns the square root of
M_SQRTPI PHP 5.2
29 PI: sqrt(pi)
1.128379167095512573 Returns 2/square root of
M_2_SQRTPI PHP 4
90 PI: 2/sqrt(pi)
0.707106781186547524 Returns the square root of
M_SQRT1_2 PHP 4
40 1/2: 1/sqrt(2)
1.414213562373095048 Returns the square root of
M_SQRT2 PHP 4
80 2: sqrt(2)
1.732050807568877293 Returns the square root of
M_SQRT3 PHP 5.2
52 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
Round halves to even
PHP_ROUND_HALF_EVEN 3 PHP 5.3
numbers
Round halves to odd
PHP_ROUND_HALF_ODD 4 PHP 5.3
numbers
Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.
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.
Function Description
Returns the number of affected rows in the previous
mysqli_affected_rows()
MySQL operation
mysqli_autocommit() Turns on or off auto-committing database modifications
mysqli_change_user() Changes the user of the specified database connection
Returns the default character set for the database
mysqli_character_set_name()
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
Returns the error description from the last connection
mysqli_connect_error()
error
mysqli_connect() Opens a new connection to the MySQL server
Adjusts the result pointer to an arbitrary row in the
mysqli_data_seek()
result-set
mysqli_debug() Performs debugging operations
mysqli_dump_debug_info() Dumps debugging info into the log
Returns the last error code for the most recent function
mysqli_errno()
call
mysqli_error_list() Returns a list of errors for the most recent function call
Returns the last error description for the most recent
mysqli_error()
function call
Fetches all result rows as an associative array, a numeric
mysqli_fetch_all()
array, or both
Fetches a result row as an associative, a numeric array, or
mysqli_fetch_array()
both
mysqli_fetch_assoc() Fetches a result row as an associative array
Returns meta-data for a single field in the result set, as an
mysqli_fetch_field_direct()
object
mysqli_fetch_field() Returns the next field in the result set, as an object
Returns an array of objects that represent the fields in a
mysqli_fetch_fields()
result set
Returns the lengths of the columns of the current row in
mysqli_fetch_lengths()
the result set
mysqli_fetch_object() Returns the current row of a result set, as an object
Fetches one row from a result-set and returns it as an
mysqli_fetch_row()
enumerated array
Returns the number of columns for the most recent
mysqli_field_count()
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
Returns the MySQL server hostname and the connection
mysqli_get_host_info()
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
Returns information about the most recently executed
mysqli_info()
query
Initializes MySQLi and returns a resource for use with
mysqli_init()
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
Sets extra connect options and affect behavior for a
mysqli_options()
connection
Pings a server connection, or tries to reconnect if the
mysqli_ping()
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
Escapes special characters in a string for use in an SQL
mysqli_real_escape_string()
statement
mysqli_real_query() Executes an SQL query
mysqli_reap_async_query() Returns the result from async query
Refreshes tables or caches, or resets the replication
mysqli_refresh()
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_handle Set callback function for LOAD DATA LOCAL INFILE
r() command
Returns the SQLSTATE error code for the last MySQL
mysqli_sqlstate()
operation
mysqli_ssl_set() Used to establish secure connections using SSL
mysqli_stat() Returns the current system status
Initializes a statement and returns an object for use with
mysqli_stmt_init()
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
Returns whether the client library is compiled as thread-
mysqli_thread_safe()
safe
Initiates the retrieval of a result set from the last query
mysqli_use_result()
executed using the mysqli_real_query()
Returns the number of warnings from the last query in
mysqli_warning_count()
the connection
The PHP string functions are part of the PHP core. No installation is required to use these
functions.
Function Description
Returns a string with backslashes in front of the specified
addcslashes()
characters
Returns a string with backslashes in front of predefined
addslashes()
characters
bin2hex() Converts a string of ASCII characters to hexadecimal values
Removes whitespace or other characters from the right end of
chop()
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_tabl Returns the translation table used by htmlspecialchars() and
e() htmlentities()
hebrev() Converts Hebrew text to visual text
Converts Hebrew text to visual text and new lines (\n) into
hebrevc()
<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
Removes whitespace or other characters from the left side of
ltrim()
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
Removes whitespace or other characters from the right side
rtrim()
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)
Finds the first occurrence of a string inside another string
strchr()
(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()
Returns the position of the first occurrence of a string inside
stripos()
another string (case-insensitive)
Finds the first occurrence of a string inside another string
stristr()
(case-insensitive)
strlen() Returns the length of a string
Compares two strings using a "natural order" algorithm (case-
strnatcasecmp()
insensitive)
Compares two strings using a "natural order" algorithm (case-
strnatcmp()
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
Returns the position of the first occurrence of a string inside
strpos()
another string (case-sensitive)
strrchr() Finds the last occurrence of a string inside another string
strrev() Reverses a string
Finds the position of the last occurrence of a string inside
strripos()
another string (case-insensitive)
Finds the position of the last occurrence of a string inside
strrpos()
another string (case-sensitive)
Returns the number of characters found in a string that
strspn()
contains only characters from a specified charlist
Finds the first occurrence of a string inside another string
strstr()
(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
Compares two strings from a specified start position (binary
substr_compare()
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
Converts the first character of each word in a string to
ucwords()
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
PHP 5 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/Addis_Aba
Africa/Abidjan Africa/Accra Africa/Algiers Africa/Asmara
ba
Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau
Africa/Brazzavill Africa/Casablan
Africa/Blantyre Africa/Bujumbura Africa/Cairo
e ca
Africa/Dar_es_Sala
Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Djibouti
am
Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare
Africa/Johannesb
Africa/Juba Africa/Kampala Africa/Khartoum Africa/Kigali
urg
Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda
Africa/Lubumbas
Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru
hi
Africa/Mogadis Africa/Ndjamen
Africa/Mbabane Africa/Monrovia Africa/Nairobi
hu a
Africa/Nouakch Africa/Ouagadou Africa/Sao_Tom
Africa/Niamey Africa/Porto-Novo
ott gou e
Africa/Timbuktu Africa/Tripoli Africa/Tunis Africa/Windhoek
America
Antarctica
Arctic
Arctic/Longyearbye
n
Asia
Atlantic
Australia
Europe
Europe/Amsterda
Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade
m
Europe/Bratisla Europe/Buchares Europe/Budapes
Europe/Berlin Europe/Brussels
va t t
Europe/Chisina Europe/Copenhag
Europe/Busingen Europe/Dublin Europe/Gibraltar
u en
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/Marieha
Europe/Madrid Europe/Malta Europe/Minsk
rg mn
Europe/Mosco
Europe/Monaco Europe/Nicosia Europe/Oslo Europe/Paris
w
Europe/Podgorica Europe/Prague Europe/Riga Europe/Rome Europe/Samara
Europe/San_Mari Europe/Sarajev Europe/Simferopo
Europe/Skopje Europe/Sofia
no o l
Europe/Uzhgoro
Europe/Stockholm Europe/Tallinn Europe/Tirane Europe/Tiraspol
d
Europe/Volgogra
Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Vilnius
d
Europe/Zaporozhy
Europe/Warsaw Europe/Zagreb Europe/Zurich
e
Indian
Indian/Antananari
Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
vo
Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte
Indian/Reunion
Pacific
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.
Function Description
connection_aborted() Checks whether the client has disconnected
connection_status() Returns the current connection status
Deprecated in PHP 4.0.5. Checks whether the script has
connection_timeout()
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
Sets whether a remote client can abort the running of a
ignore_user_abort()
script
pack() Packs data into a binary string
php_check_syntax() Deprecated in PHP 5.0.5
Returns the source code of a file with PHP comments and
php_strip_whitespace()
whitespace removed
show_source() Alias of highlight_file()
sleep() Delays code execution for a number of seconds
sys_getloadavg() Gets system load average
Delays code execution for a number of seconds and
time_nanosleep()
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.