Introduction To PHP
Introduction To PHP
Introduction To PHP
HTML
CSS
JavaScript
If you want to study these subjects first, find the tutorials on our Home page.
What is PHP?
PHP is an acronym for "PHP Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP costs nothing, it is free to download and use
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
PHP 5 Syntax
The PHP script is executed on the server, and the plain HTML result is sent back to the browser.
<?php
// PHP code goes here
?>
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>
Note: PHP statements are terminated by semicolon (;). The closing tag of a block of PHP code
also automatically implies a semicolon (so you do not have to have a semicolon terminating the
last line of a PHP block).
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 editing the code!
To let others understand what you are doing - Comments let other programmers
understand what you were doing in each step (if you work in a group)
To remind yourself what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single line comment
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
</body>
</html>
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>
PHP 5 Variables
Variables are "containers" for storing information:
Example
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
From the expression z=x+y above, we can calculate the value of z to be 11.
PHP Variables
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case sensitive ($y and $Y are two different variables)
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.
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.
local
global
static
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function.
The following example tests variables with local and global scope:
Example
<?php
$x=5; // global scope
function myTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
In the example above there are two variables $x and $y and a function myTest(). $x is a global
variable since it is declared outside the function and $y is a local variable since it is created
inside the function.
When we output the values of the two variables inside the myTest() function, it prints the value
of $y as it is the locally declared, but cannot print the value of $x since it is created outside the
function.
Then, when we output the values of the two variables outside the myTest() function, it prints the
value of $x, but cannot print the value of $y since it is a local variable and it is created inside the
myTest() function.
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.
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.
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.
Tip: echo is marginally faster compared to print as echo does not return any value.
Display Strings
The following example shows how to display different strings with the echo command (also
notice that the strings 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.";
?>
Result:
PHP is fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.
Display Variables
The following example shows how to display strings and variables with the echo command:
Example
<?php
$txt1="Learn PHP";
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
echo $txt1;
echo "<br>";
echo "Study PHP at $txt2";
echo "My car is a {$cars[0]}";
?>
Result:
Learn PHP
Study PHP at W3Schools.com
My car is a Volvo
Display Strings
The following example shows how to display different strings with the print command (also
notice that the strings 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 display strings and variables with the print command:
Example
<?php
$txt1="Learn PHP";
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
print $txt1;
print "<br>";
print "Study PHP at $txt2";
print "My car is a {$cars[0]}";
?>
PHP Strings
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>
Result:
Hello world!
Hello world!
PHP Integers
An integer is a number without decimals.
In the following example we will test different numbers. The PHP var_dump() function returns
the data type and value of variables:
Example
<?php
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x);
echo "<br>";
$x = 047; // octal number
var_dump($x);
?>
Result:
int(5985)
int(-345)
int(140)
int(39)
In the following example we will test different numbers. The PHP var_dump() function returns
the data type and value of variables:
Example
<?php
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
echo "<br>";
$x = 8E-5;
var_dump($x);
?>
Result:
float(10.365)
float(2400)
float(8.0E-5)
PHP Booleans
Booleans can be either TRUE or FALSE.
$x=true;
$y=false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Arrays
An array stores multiple values in one single variable.
In the following example we create an array, and then use the PHP var_dump() function to return
the data type and value of the array:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Result:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Objects
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.
We then define the data type in the object class, and then we use the data type in instances of that
class:
Example
<?php
class Car
{
var $color;
function Car($color="green")
{
$this->color = $color;
}
function what_color()
{
return $this->color;
}
}
function print_vars($obj)
{
foreach (get_object_vars($obj) as $prop => $val)
{
echo "\t$prop = $val\n";
}
}
Result :
\herbie: Properties color = white
You will learn more about objects in a later chapter of this tutorial.
The NULL value identifies whether a variable is empty or not. Also useful to differentiate
between the empty string and null values of databases.
Example
<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>
The example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!");
?>
Result:
12
Tip: strlen() is often used in loops or other functions, when it is important to know when a string
ends. (i.e. in a loop, we might want to stop the loop after the last character in a string).
If a match is found, it will return 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");
?>
Result:
6
Tip: The position of the string "world" in the example above is 6. The reason that it is 6 (and not
7), is that the first character position in the string is 0, and not 1.
The PHP string reference contains description and example of use, for each function!
PHP 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.
The example below creates a case-sensitive constant, with the value of "Welcome to
W3Schools.com!":
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Result:
Welcome to W3Schools.com!
greeting
The example below creates a case-insensitive constant, with the value of "Welcome to
W3Schools.com!":
Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Result:
Welcome to W3Schools.com!
Welcome to W3Schools.com!
PHP Operators
This chapter shows the different operators that can be used in PHP scripts.
The example below shows the different results of using the different arithmetic operators:
Example
<?php
$x=10;
$y=6;
echo ($x + $y); // outputs 16
echo ($x - $y); // outputs 4
echo ($x * $y); // outputs 60
echo ($x / $y); // outputs 1.6666666666667
echo ($x % $y); // outputs 4
?>
PHP Assignment Operators
The PHP assignment operators is used 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.
Assignment Same as... Description
The left operand gets set to the value of the expression
x=y x=y
on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
The example below shows the different results of using the different assignment operators:
Example
<?php
$x=10;
echo $x; // outputs 10
$y=20;
$y += 100;
echo $y; // outputs 120
$z=50;
$z -= 25;
echo $z; // outputs 25
$i=5;
$i *= 6;
echo $i; // outputs 30
$j=10;
$j /= 5;
echo $j; // outputs 2
$k=15;
$k %= 4;
echo $k; // outputs 3
?>
The example below shows the results of using the string operators:
Example
<?php
$a = "Hello";
$b = $a . " world!";
echo $b; // outputs Hello world!
$x="Hello";
$x .= " world!";
echo $x; // outputs Hello world!
?>
The example below shows the different results of using the different increment/decrement
operators:
Example
<?php
$x=10;
echo ++$x; // outputs 11
$y=10;
echo $y++; // outputs 10
$z=5;
echo --$z; // outputs 4
$i=5;
echo $i--; // outputs 5
?>
The example below shows the different results of using some of the comparison operators:
Example
<?php
$x=100;
$y="100";
var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x !== $y);
echo "<br>";
$a=50;
$b=90;
Result:
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
The example below shows the different results of using the different array operators:
Example
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
var_dump($z);
var_dump($x == $y);
var_dump($x === $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);
?>
Result:
array(4) { ["a"]=> string(3) "red" ["b"]=> string(5) "green" ["c"]=> string(4) "blue" ["d"]=>
string(6) "yellow" }
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
PHP if...else...elseif Statements
« Previous
Next Chapter »
Conditional statements are used to perform different actions based on different conditions.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
Result:
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Result:
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Run example »
Syntax
if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":
Example
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
elseif ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Next Chapter »
The switch statement is used to perform different actions based on different conditions.
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, or green!";
}
?>
Result:
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
Syntax
while (condition is true)
{
code to be executed;
}
The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run
as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):
Example
<?php
$x=1;
while($x<=5)
{
echo "The number is: $x <br>";
$x++;
}
?>
Result:
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)
?>
Result:
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 fails
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)
?>
Result:
Syntax
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
Example
<?php
for ($x=0; $x<=10; $x++)
{
echo "The number is: $x <br>";
}
?>
Result:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array
($colors):
Example
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
Result:
red
green
blue
yellow
PHP Functions
The real power of PHP comes from its functions; it has more than 1000 built-in 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!";
}
Result:
Hello world!
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just seperate 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");
?>
Result:
Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
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");
?>
Result:
Hege Refsnes. Born in 1975
Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
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);
?>
Result:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
Example
<?php
function sum($x,$y)
{
$z=$x+$y;
return $z;
}
Result:
5 + 10 = 15
7 + 13 = 20
2+4=6
PHP Arrays
An array stores multiple values in one single variable:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Result:
I like Volvo, BMW and Toyota.
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();
$cars=array("Volvo","BMW","Toyota");
$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] . ".";
?>
Run example »
Run example »
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Run example »
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
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.";
?>
Result:
Peter is 35 years old.
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Result:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Multidimensional Arrays
Multidimensional arrays will be explained in the PHP advanced section.
Complete PHP Array Reference
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
Example
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
Result:
BMW
Toyota
Volvo
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);
?>
Run example »
Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
Run example »
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);
?>
Run example »
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>
Run example »
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
Run example »
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
Run example »
Sort Array in Descending Order, According to Key - krsort()
The following example sorts an associative array in descending order, according to the key:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
Run example »
The reference contains a brief description, and examples of use, for each function!
$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 $GLOBAL
$GLOBAL 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 $GLOBAL:
Example
<?php
$x = 75;
$y = 25;
function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
Result:
100
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'];
?>
Result:
/php/demo_global_server.php
www.w3schools.com
www.w3schools.com
http://www.w3schools.com/php/showphp.asp?filename=demo_global_server
Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1
/php/demo_global_server.php
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 page
$_SERVER['REQUEST_METHOD']
(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 a
$_SERVER['QUERY_STRING']
query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
Returns the Accept_Charset header from the current
$_SERVER['HTTP_ACCEPT_CHARSET']
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 current page (not
$_SERVER['HTTP_REFERER']
reliable because not all user-agents support it)
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 to
$_SERVER['REMOTE_PORT']
communicate with the web server
Returns the absolute pathname of the currently
$_SERVER['SCRIPT_FILENAME']
executing script
Returns the value given to the SERVER_ADMIN
directive in the web server configuration file (if
$_SERVER['SERVER_ADMIN'] 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
PHP $_REQUEST is used to collect data after submitting an HTML form.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to this file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_REQUEST to collect the value of the input field:
Example
<html>
<body>
<?php
$name = $_REQUEST['fname'];
echo $name;
?>
</body>
</html>
Run example »
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 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 $_POST to collect the value of the input field:
Example
<html>
<body>
<?php
$name = $_POST['fname'];
echo $name;
?>
</body>
</html>
Run example »
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" is sent to
"test_get.php", and you can then acces their values in "test_get.php" with $_GET.
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
Run example »
Tip: You will learn more about $_POST and $_GET in the PHP Forms chapter.
However, sometimes you want to store values with more than one key.
PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
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>";
?>
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
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
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Row number 0
Volvo
22
18
Row number 1
BMW
15
13
Row number 2
Saab
5
2
Row number 3
Land Rover
17
15
Next Chapter »
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.
Syntax
date(format,timestamp)
Parameter Description
timestamp Optional. Specifies a timestamp. Default is the current date and time
A list of all the characters that can be used in the format parameter, can be found in our PHP
Date reference, date() function.
Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional
formatting:
<?php
echo date("Y/m/d") . "<br>";
echo date("Y.m.d") . "<br>";
echo date("Y-m-d");
?>
2009/05/11
2009.05.11
2009-05-11
The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970
00:00:00 GMT) and the time specified.
To go one day in the future we simply add one to the day argument of mktime():
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
Tomorrow is 2009/05/12
The reference contains a brief description, and examples of use, for each function!
Next Chapter »
PHP include and require Statements
In PHP, you can insert the content of one PHP file into another PHP file before the server
executes it.
The include and require statements are used to insert useful codes written in other files, in the
flow of execution.
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 include. Otherwise, in case of FrameWork, CMS or a complex PHP application
coding, always use require 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';
Assume that you have a standard header file, called "header.php". To include the header file in a
page, use include/require:
<html>
<body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 2
Assume we have a standard menu file that should be used on all pages.
"menu.php":
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
</body>
</html>
Example 3
<?php
$color='red';
$car='BMW';
?>
<html>
<body>
</body>
</html>
Next Chapter »
Opening a File
The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
Modes Description
Write only. Opens and clears the contents of file; or creates a new file if it doesn't
w
exist
Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't
w+
exist
Append. Opens and writes to the end of the file or creates a new file if it doesn't
a
exist
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).
Example
The following example generates a message if the fopen() function is unable to open the
specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
Check End-of-file
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.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
Next Chapter »
<html>
<body>
</body>
</html>
The enctype attribute of the <form> tag specifies which content-type to use when submitting
the form. "multipart/form-data" is used when a form requires binary data, like the contents of a
file, to be uploaded
The type="file" attribute of the <input> tag specifies that the input should be processed as a file.
For example, when viewed in a browser, there will be a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform
file uploads.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
By using the global PHP $_FILES array you can upload files from a client computer to the
remote server.
The first parameter is the form's input name and the second index can be either "name", "type",
"size", "tmp_name" or "error". Like this:
This is a very simple way of uploading files. For security reasons, you should add restrictions on
what the user is allowed to upload.
Restrictions on Upload
In this script we add some restrictions to the file upload. The user may upload .gif, .jpeg, and
.png files; and the file size must be under 20 kB:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
The temporary copied files disappears when the script ends. To store the uploaded file we need
to copy it to a different location:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
The script above checks if the file already exists, if it does not, it copies the file to a folder called
"upload".
PHP Cookies
« Previous
Next Chapter »
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the example below, we will create a cookie named "user" and assign the value "Alex Porter"
to it. We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30
days).
In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
In the following example we use the isset() function to find out if a cookie has been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
</body>
</html>
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
The form below passes the user input to "welcome.php" when the user clicks on the "Submit"
button:
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
PHP Sessions
« Previous
Next Chapter »
A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.
A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may want
to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this
UID. The UID is either stored in a cookie or is propagated in the URL.
Note: The session_start() function must appear BEFORE the <html> tag:
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
<?php
session_start();
if(isset($_SESSION['views']))
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.
Next Chapter »
Use the PHP mysqli_connect() function to open a new connection to the MySQL server.
Open a Connection to the MySQL Server
Before we can access data in a database, we must open a connection to the MySQL server.
Syntax
mysqli_connect(host,username,password,dbname);
Parameter Description
Note: There are more available parameters, but the ones listed above are the most important.
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Close a Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the mysqli_close() function:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
AJAX Introduction
« Previous
Next Chapter »
AJAX is about updating parts of a web page, without reloading the whole page.
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data
with the server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should
change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
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.
If you want to learn more about AJAX, visit our AJAX tutorial.
Next Chapter »
Example
Start typing a name in the input field below:
First name:
Suggestions:
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp. > {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.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>
If the input field is empty (str.length==0), the function clears the content of the txtHint
placeholder and exits the function.
If the input field is not empty, the showHint() function executes the following:
The source code in "gethint.php" checks an array of names, and returns the corresponding
name(s) to the browser:
<?php
// Fill up 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";
Next Chapter »
Example
<html>
<head>
<script>
function showUser(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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.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">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
The source code in "getuser.php" runs a query against a MySQL database, and returns the result
in an HTML table:
<?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);
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);
?>
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
AJAX Example
« Previous
Next Chapter »
Example
Let AJAX change this text
Try it yourself »
The div section will be used to display information returned from a server. The button calls a
function named loadXMLDoc(), if it is clicked:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Next, add a <script> tag to the page's head section. The script section contains the
loadXMLDoc() function:
<head>
<script>
function loadXMLDoc()
{
.... AJAX script goes here ...
}
</script>
</head>