4.-PHP
4.-PHP
PHP stands for Hypertext Preprocessor. PHP is a very popular and widely-used open source server-side
scripting language to write dynamically generated web pages. PHP was originally created by Rasmus
Lerdorf in 1994. It was initially known as Personal Home Page.
PHP scripts are executed on the server and the result is sent to the web browser as plain HTML. PHP can
be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Microsoft SQL
Server, Sybase, and so on. The current major version of PHP is 7.
The list does not end here, there are many other interesting things that you can do with PHP.
• Easy to learn: PHP is easy to learn and use. For beginner programmers who just started out in web
development, PHP is often considered as the preferable choice of language to learn.
• Open source: PHP is an open-source project. It is developed and maintained by a worldwide community
of developers who make its source code freely available to download and use.
• Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac OS, etc. and it is
compatible with almost all servers used today such Apache, IIS, etc.
• Fast Performance: Scripts written in PHP usually execute or runs faster than those written in other
scripting languages like ASP, Ruby, Python, Java, etc.
• Vast Community: Since PHP is supported by the worldwide community, finding help or documentation
related to PHP online is extremely easy.
You can either install them individually or choose a pre-configured package for your operating system like
Linux and Windows. Popular pre-configured package are XAMPP and WampServer.
WampServer is a Windows web development environment. It allows you to create web applications with
Apache2, PHP and a MySQL database. It will also provide the MySQL administrative tool PhpMyAdmin to
easily manage your databases using a web browser.
Now open up your favorite code editor and create a new PHP file then type the following code:
Example:
<?php
// Display greeting message
echo "Hello, world!";
?>
Now save this file as "hello.php" in your project folder (located at C:\wamp\www\project), and view the
result in your browser through visiting this URL: http://localhost/project/hello.php.
Alternatively, you can access the "hello.php" file through selecting the localhost option and then select the
project folder from the WampSever menu on the taskbar.
PHP can be embedded within a normal HTML web page. That means inside your HTML document you can
write the PHP statements, as demonstrated in the follwoing example:
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Application</title>
</head>
<body>
<?php
// Display greeting message
echo 'Hello World!';
?>
</body>
</html>
The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed
code block as PHP code, rather than simple HTML.
Example:
<?php
// Some code to be executed
echo "Hello, world!";
?>
Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current
statement has been reached.
What happend here is? when you run this code the PHP engine exacuted the instructions between
the <?php … ?> tags and leave rest of the thing as it is. At the end the web server send the final output
back to your browser which is completely in HTML.
PHP Comments
A comment is simply text that is ignored by the PHP engine. The purpose of comments is to make the
code more readable. It may help other developer (or you in the future when you edit the source code) to
understand what you were trying to do with the PHP.
PHP support single-line as well as multi-line comments. To write a single-line comment either start the
line with either two slashes (//) or a hash symbol (#). For example:
Example
<?php
// This is a single line comment
# This is also a single line comment
echo "Hello, world!";
?>
However to write multi-line comments, start the comment with a slash followed by an asterisk (/*) and
end the comment with an asterisk followed by a slash ( */), like this:
Example
<?php
/*
This is a multiple line comment block
that spans across more than
one line
*/
echo "Hello, world!";
?>
Example
<?php
// Assign value to variable
$color = "blue";
However the keywords, function and classes names are case-insensitive. As a result calling
the gettype() or GETTYPE() produce the same result.
Example
<?php
// Assign value to variable
$color = "blue";
▪ In PHP, a variable does not need to be declared before adding a value to it. PHP automatically
converts the variable to the correct data type, depending on its value.
▪ After declaring a variable it can be reused throughout the code.
▪ The assignment operator (=) used to assign value to a variable.
Example
<?php
// Declaring variables
$txt = "Hello World!";
$number = 10;
• All variables in PHP start with a $ 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 in PHP can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
• A variable name cannot contain spaces.
PHP Constants
In this tutorial you will learn how use constants for storing fixed values in PHP.
Constants are defined using PHP's define() function, which accepts two arguments: the name of the
constant, and its value. Once defined the constant value can be accessed at any time just by referring to
its name. Here is a simple example:
Example
<?php
// Defining constant
define("SITE_URL", "https://www.tutorialrepublic.com/");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>
The output of the above code will be:
The PHP echo statement is often used to display or output data to the web browser. We will learn more
about this statement in the next chapter.
Since echo is a language construct not actually a function (like if statement), you can use it without
parentheses e.g. echo or echo(). However, if you want to pass more than one parameter to echo, the
parameters must not be enclosed within parentheses.
Example
<?php
// Displaying string of text
echo "Hello World!";
?>
The output of the above PHP code will look something like this:
Hello World!
Display HTML Code
The following example will show you how to display HTML code using the echo statement:
Example
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The output of the above PHP code will look something like this:
This is a simple heading.
This is heading with style.
Display Variables
The following example will show you how to display variable using the echo statement:
Example
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
echo $txt;
echo "<br>";
echo $num;
echo "<br>";
echo $colors[0];
?>
The output of the above PHP code will look something like this:
Hello World!
123456789
Red
Both echo and print statement works exactly the same way except that the print statement can only
output one string, and always returns 1. That's why the echo statement considered marginally faster than
the print statement since it doesn't return any value.
Example
<?php
// Displaying string of text
print "Hello World!";
?>
The output of the above PHP code will look something like this:
Hello World!
Example
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The output of the above PHP code will look something like this:
This is a simple heading.
This is heading with style.
Display Variables
The following example will show you how to display variable using the print statement:
Example
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
print $txt;
print "<br>";
print $num;
print "<br>";
print $colors[0];
?>
The output of the above PHP code will look something like this:
Hello World!
123456789
Red
PHP supports total eight primitive data types: Integer, Floating point number or Float, String, Booleans,
Array, Object, resource and NULL. These data types are used to construct variables. Now let's discuss each
one of them in detail.
PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be specified in
decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 - prefixed with 0) notation,
optionally preceded by a sign (- or +).
Example
<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>";
PHP Strings
Strings are sequences of characters, where every character is the same as a byte.
A string can hold letters, numbers, and special characters and it can be as large as up to 2GB (2147483647
bytes maximum). The simplest way to specify a string is to enclose it in single quotes (e.g. 'Hello world!'),
however you can also use double quotes ("Hello world!").
Example
<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
$b = "Hello world!";
echo $b;
echo "<br>";
Example
<?php
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);
?>
PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
Example
<?php
// Assign the value TRUE to a variable
$show_error = true;
var_dump($show_error);
?>
PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to aggregate a series of
related items together, for example a set of country or city names.
An array is formally defined as an indexed collection of data values. Each index (also known as the key) of
an array is unique and references a corresponding value.
Example
<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";
$color_codes = array(
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);
?>
You will learn more about arrays in PHP Array tutorial.
PHP Objects
An object is a data type that not only allows storing data but also information on, how to process that
data. An object is a specific instance of a class which serve as templates for objects. Objects are created
based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class. Every object instance
is completely independent, with its own properties and methods, and can thus be manipulated
independently of other objects of the same class.
Example
<?php
// Class definition
class greeting{
// properties
public $str = "Hello World!";
// methods
function show_greeting(){
return $this->str;
}
}
// Create object from class
$message = new greeting;
var_dump($message);
?>
PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of type NULL is a variable
without any data. NULL is the only possible value of type null.
Example
<?php
$a = NULL;
var_dump($a);
echo "<br>";
$b = "Hello World!";
$b = NULL;
var_dump($b);
?>
When a variable is created without a value in PHP like $var; it is automatically assigned a value of null.
Many novice PHP developers mistakenly considered both $var1 = NULL; and $var2 = ""; are same, but
this is not true. Both variables are different — the $var1 has null value while $var2indicates no value
assigned to it.
PHP Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database connections.
Example
<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";
PHP Strings
In this tutorial you will learn how to store and manipulate strings in PHP.
You can also use double quotation marks ("). However, single and double quotation marks work in
different ways. Strings enclosed in single-quotes are treated almost literally, whereas the strings delimited
by the double quotes replaces variables with the string representations of their values as well as specially
interpreting certain escape sequences.
Here's an example to clarify the differences between single and double quoted strings:
Example
<?php
$my_str = 'World';
echo "Hello, $my_str!<br>"; // Displays: Hello World!
echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
Example
<?php
$my_str = 'Welcome to Tutorial Republic';
// Outputs: 28
echo strlen($my_str);
?>
Example
<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
// Outputs: 9
echo str_word_count($my_str);
?>
Example
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
You can optionally pass the fourth argument to the str_replace() function to know how many times the
string replacements was performed, like this.
Example
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
Example
<?php
$my_str = 'You can do anything, but not everything.';
PHP Operators
In this tutorial you will learn how to manipulate or perform the operations on variables and values using
operators in PHP.
The following example will show you these arithmetic operators in action:
Example
<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
= Assign $x = $y $x = $y
The following example will show you these assignment operators in action:
Example
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $x; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same
type
The following example will show you these comparison operators in action:
Example
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
PHP Incrementing and Decrementing Operators
The increment/decrement operators are used to increment/decrement a variable's value.
The following example will show you these increment and decrement operators in action:
Example
Run this code »
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
The following example will show you these logical operators in action:
Example
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>
The following example will show you these string operators in action:
Example
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
=== Identity $x === $y True if $x and $y have the same key/value pairs in the same order and of
the same types
The following example will show you these array operators in action:
Example
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
The spaceship operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is
greater. It basically provides three-way comparison as shown in the following table:
The following example will show you how spaceship operator actually works:
Example
<?php
// Comparing Integers
echo 1 <=> 1; // Outputs: 0
echo 1 <=> 2; // Outputs: -1
echo 2 <=> 1; // Outputs: 1
// Comparing Floats
echo 1.5 <=> 1.5; // Outputs: 0
echo 1.5 <=> 2.5; // Outputs: -1
echo 2.5 <=> 1.5; // Outputs: 1
// Comparing Strings
echo "x" <=> "x"; // Outputs: 0
echo "x" <=> "y"; // Outputs: -1
echo "y" <=> "x"; // Outputs: 1
?>
There are several statements in PHP that you can use to make decisions:
• The if statement
• The if...else statement
• The if...elseif....else statement
• The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to true. This is
the simplest PHP's conditional statements and can be written like:
if(condition){
// Code to be executed
}
The following example will output "Have a nice weekend!" if the current day is Friday:
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will
output "Have a nice day!"
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice
Sunday!" if the current day is Sunday, otherwise it will output "Have a nice day!"
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
You will learn about PHP switch-case statement in the next chapter.
Example
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>
Using the ternary operator the same code could be written in a more compact way:
Example
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>
The ternary operator in the example above selects the value on the left of the colon (i.e. 'Child') if the
condition evaluates to true (i.e. if $age is less than 18), and selects the value on the right of the colon (i.e.
'Adult') if the condition evaluates to false.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}
Consider the following example, which display a different message for each day.
Example
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>
The switch-case statement differs from the if-elseif-else statement in one important way.
The switch statement executes line by line (i.e. statement by statement) and once PHP finds
a casestatement that evaluates to true, it's not only executes the code corresponding to that case
statement, but also executes all the subsequent case statements till the end of the switch block
automatically.
To prevent this add a break statement to the end of each case block. The break statement tells PHP to
break out of the switch-case statement block once it executes the code associated with the first true case.
PHP Arrays
What is PHP Arrays
Arrays are complex variables that allow us to store more than one value or a group of values under a
single variable name. Let's suppose you want to store colors in your PHP script. Storing the colors one by
one in a variable could look something like this:
Example
<?php
$color1 = "Red";
$color2 = "Green";
$color3 = "Blue";
?>
But what, if you want to store the states or city names of a country in variables and this time this not just
three may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable.
And here array comes into play.
Indexed Arrays
An indexed or numeric array stores each array element with a numeric index. The following examples
shows two ways of creating an indexed array, the easiest way is:
Example
<?php
// Define an indexed array
$colors = array("Red", "Green", "Blue");
?>
This is equivalent to the following example, in which indexes are assigned manually:
Example
Run this code »
<?php
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>
Associative Arrays
In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the
following example the array uses keys instead of index numbers:
Example
Run this code »
<?php
// Define an associative array
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
The following example is equivalent to the previous example, but shows a different way of creating
associative arrays:
Example
Run this code »
<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>
Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each element in the
sub-array can be an array or further contain array within itself and so on. An example of a
multidimensional array will look something like this:
Example
Run this code »
<?php
// Define a multidimensional array
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "[email protected]",
),
array(
"name" => "Clark Kent",
"email" => "[email protected]",
),
array(
"name" => "Harry Potter",
"email" => "[email protected]",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>
Example
Run this code »
<?php
// Define array
$cities = array("London", "Paris", "New York");
Array ( [0] => London [1] => Paris [2] => New York )
This output shows the key and the value for each element in the array. To get more information, use the
following statement:
Example
Run this code »
<?php
// Define array
$cities = array("London", "Paris", "New York");
array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
This output shows the data type of each element, such as a string of 6 characters, in addition to the key
and value. In the next chapter you will learn how to sort array elements.
PHP comes with a number of built-in functions designed specifically for sorting array elements in different
ways like alphabetically or numerically in ascending or descending order. Here we'll explore some of these
functions most commonly used for sorting arrays.
Example
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )
Similarly you can sort the numeric elements of the array in ascending order.
Example
<?php
// Define array
$numbers = array(1, 2, 2.5, 4, 7, 10);
Array ( [0] => 1 [1] => 2 [2] => 2.5 [3] => 4 [4] => 7 [5] => 10 )
Sorting Indexed Arrays in Descending Order
The rsort() function is used for sorting the elements of the indexed array in descending order
(alphabetically for letters and numerically for numbers).
Example
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
Similarly you can sort the numeric elements of the array in descending order.
Example
<?php
// Define array
$numbers = array(1, 2, 2.5, 4, 7, 10);
Array ( [0] => 10 [1] => 7 [2] => 4 [3] => 2.5 [4] => 2 [5] => 1 )
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by key and print
ksort($age);
print_r($age);
?>
This print_r() statement gives the following output:
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
PHP Loops
Different Types of Loops in PHP
Loops are used to execute the same block of code again and again, as long as a certain condition is met.
The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and
effort. PHP supports four different types of loops.
• while — loops through a block of code as long as the condition specified evaluates to true.
• do…while — the block of code executed once and then condition is evaluated. If the condition is true the
statement is repeated as long as the specified condition is true.
• for — loops through a block of code until the counter reaches a specified number.
• foreach — loops through a block of code for each element in an array.
You will also learn how to loop through the values of array using foreach() loop at the end of this
chapter. The foreach() loop work specifically with arrays.
The example below define a loop that starts with $i=1. The loop will continue to run as long as $i is less
than or equal to 3. The $i will increase by 1 each time the loop runs:
Example
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>
Example
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional
expression is false, because the condition is evaluated at the end of the loop iteration rather than the
beginning.
• initialization — it is used to initialize the counter variables, and evaluated once unconditionally before
the first execution of the body of the loop.
• condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop
continues and the nested statements are executed. If it evaluates to false, the execution of the loop ends.
• increment — it updates the loop counter with a new value. It is evaluate at the end of each iteration.
The example below defines a loop that starts with $i=1. The loop will continued until $i is less than, or
equal to 3. The variable $i will increase by 1 each time the loop runs:
Example
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
The following example demonstrates a loop that will print the values of the given array:
Example
<?php
$colors = array("Red", "Green", "Blue");
PHP Functions
PHP Built-in Functions
A function is a self-contained block of code that performs a specific task.
PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts
to perform a specific task, like gettype(), print_r(), var_dump, etc.
Please check out PHP reference section for a complete list of useful PHP built-in functions.
• Functions reduces the repetition of code within a program — Function allows you to extract
commonly used block of code into a single component. Now you can perform the same task by calling
this function wherever you want within your script without having to copy and paste the same block of
code again and again.
• Functions makes the code much easier to maintain — Since a function created once can be used
many times, so any changes made inside a function automatically implemented at all the places without
touching the several files.
• Functions makes it easier to eliminate the errors — When the program is subdivided into
functions, if any error occur you know exactly what function causing the error and where to find it.
Therefore, fixing errors becomes much easier.
• Functions can be reused in other application — Because a function is separated from the rest of
the script, it's easy to reuse the same function in other applications just by including the php file
containing those functions.
The following section will show you how easily you can define your own function in PHP.
The declaration of a user-defined function start with the word function, followed by the name of the
function you want to create followed by parentheses i.e. () and finally place your function's code between
curly brackets {}.
Example
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
Functions with Parameters
You can specify parameters when you define your function to accept input values at run time. The
parameters work like placeholder variables within a function; they're replaced at run time by the values
(known as argument) provided to the function at the time of invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
You can define as many parameters as you like. However for each parameter you specify, a corresponding
argument needs to be passed to the function when it is called.
The getSum() function in following example takes two integer values as arguments, simply add them
together and then display the result in the browser.
Example
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20);
?>
The output of the above code will be:
Example
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
As you can see the third call to customFont() doesn't include the second argument. This causes PHP
engine to use the default value for the $size parameter which is 1.5.
Example
<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}
Example
<?php
// Defining function
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}
Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the
function definition, as shown in the example below:
Example
<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}
$mynum = 5;
echo $mynum; // Outputs: 5
selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>
By default, variables declared within a function are local and they cannot be viewed or manipulated from
outside of that function, as demonstrated in the example below:
Example
<?php
// Defining function
function test(){
$greet = "Hello World!";
echo $greet;
}
Example
<?php
$greet = "Hello World!";
// Defining function
function test(){
echo $greet;
}
// Defining function
function test(){
global $greet;
echo $greet;
}
Example
<?php
// Defining recursive function
function printValues($arr) {
global $count;
global $items;
/*
Loop through array, if value is itself an array recursively call the
function else add the value found to the output items array,
and increment counter by 1 for each value found
*/
foreach($arr as $a){
if(is_array($a)){
printValues($a);
} else{
$items[] = $a;
$count++;
}
}
Example
<?php
echo 7 + 3; // 0utputs: 10
echo 7 - 2; // 0utputs: 5
echo 7 * 2; // 0utputs: 14
echo 7 / 2; // 0utputs: 3.5
echo 7 % 2; // 0utputs: 1
?>
Every math operation has a certain precedence level; generally multiplication and division are performed
before addition and subtraction. However, parentheses can alter this precedence; expressions enclosed
within parentheses are always evaluated first, regardless of the operation's precedence level, as
demonstrated in the following example:
Example
<?php
echo 5 + 4 * 10; // 0utputs: 45
echo (5 + 4) * 10; // 0utputs: 90
echo 5 + 4 * 10 / 2; // 0utputs: 25
echo 8 * 10 / 4 - 2; // 0utputs: 18
echo 8 * 10 / (4 - 2); // 0utputs: 40
echo 8 + 10 / 4 - 2; // 0utputs: 8.5
echo (8 + 10) / (4 - 2); // 0utputs: 9
?>
In the following section we're going to look at some built-in PHP functions that are most frequently used
in performing mathematical operations.
Example
<?php
echo abs(5); // 0utputs: 5 (integer)
echo abs(-5); // 0utputs: 5 (integer)
echo abs(4.2); // 0utputs: 4.2 (double/float)
echo abs(-4.2); // 0utputs: 4.2 (double/float)
?>
As you can see if the given number is negative, the valued returned is positive. But, if the number is
positive, this function simply returns the number.
Example
<?php
// Round fractions up
echo ceil(4.2); // 0utputs: 5
echo ceil(9.99); // 0utputs: 10
echo ceil(-5.18); // 0utputs: -5
Example
<?php
echo sqrt(9); // 0utputs: 3
echo sqrt(25); // 0utputs: 5
echo sqrt(10); // 0utputs: 3.1622776601684
echo sqrt(-16); // 0utputs: NAN
?>
Example
<?php
// Generate some random numbers
echo rand() . "<br>";
echo rand() . "<br>";
Example
Run this code »
<?php
// Convert Decimal to Binary
echo decbin(2); // 0utputs: 10
echo decbin(12); // 0utputs: 1100
echo decbin(100); // 0utputs: 1100100
Example
Run this code »
<?php
// Convert decimal to hexadecimal
echo dechex(255); // 0utputs: ff
echo dechex(196); // 0utputs: c4
echo dechex(0); // 0utputs: 0
This function accepts three parameters: the number to convert, the base it's currently in, and the base it's
to be converted to. The basic syntax is as follows:
base_convert(number, frombase, tobase);
Example
<?php
// Convert decimal to binary
echo base_convert('12', 10, 2); // 0utputs: 1100
// Convert binary to decimal
echo base_convert('1100', 2, 10); // 0utputs: 12
The bold parts in the URL are the GET parameters and the italic parts are the value of those parameters.
More than one parameter=value can be embedded in the URL by concatenating with ampersands (&). One
can only send simple text data via GET method.
Advantages and Disadvantages of Using the GET Method
• Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with
specific query string values.
• The GET method is not suitable for passing sensitive information such as the username and password,
because these are fully visible in the URL query string as well as potentially stored in the client browser's
memory as a visited page.
• Because the GET method assigns data to a server environment variable, the length of the URL is limited.
So, there is a limitation for the total data to be sent.
PHP provides the superglobal variable $_GET to access all the information sent either through the URL or
submitted through an HTML form using the method="get".
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP GET method</title>
</head>
<body>
<?php
if(isset($_GET["name"])){
echo "<p>Hi, " . $_GET["name"] . "</p>";
}
?>
<form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
Like $_GET, PHP provide another superglobal variable $_POST to access all the information sent via post
method or submitted through an HTML form using the method="post".
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP POST method</title>
</head>
<body>
<?php
if(isset($_POST["name"])){
echo "<p>Hi, " . $_POST["name"] . "</p>";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP $_REQUEST variable</title>
</head>
<body>
<?php
if(isset($_REQUEST["name"])){
echo "<p>Hi, " . $_REQUEST["name"] . "</p>";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
The computer stores dates and times in a format called UNIX Timestamp, which measures time as a
number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1,
1970 i.e. January 1, 1970 00:00:00 GMT ).
Since this is an impractical format for humans to read, PHP converts a timestamp to a format that is
readable to humans and dates from your notation into a timestamp the computer understands. The
syntax of the PHP date() function can be given with.
date(format, timestamp)
The format parameter in the date() function is required which specifies the format of returned date and
time. However the timestamp is an optional parameter, if not included then current date and time will be
used. The following statement displays today's date:
Example
Run this code »
<?php
$today = date("d/m/Y");
echo $today;
?>
Note: The PHP date() function return the current date and time according to the built-in clock of the web
server on which the script has been executed.
• d - Represent day of the month; two digits with leading zeros (01 or 31)
• D - Represent day of the week in text as an abbreviation (Mon to Sun)
• m - Represent month in numbers with leading zeros (01 or 12)
• M - Represent month in text, abbreviated (Jan to Dec)
• y - Represent year in two digits (08 or 14)
• Y - Represent year in four digits (2008 or 2014)
The parts of the date can be separated by inserting other characters, like hyphens ( -), dots (.), slashes (/),
or spaces to add additional visual formatting.
Example
<?php
echo date("d/m/Y") . "<br>";
echo date("d-m-Y") . "<br>";
echo date("d.m.Y");
?>
Similarly you can use the following characters to format the time string:
The PHP code in the following example displays the date in different formats:
Example
<?php
echo date("h:i:s") . "<br>";
echo date("F d, Y h:i:s A") . "<br>";
echo date("h:i a");
?>
Example
Run this code »
<?php
// Executed at March 05, 2014 07:19:18
$timestamp = time();
echo($timestamp);
?>
The above example produce the following output.
1394003958
We can convert this timestamp to a human readable date through passing it to the previously
introduce date() function.
Example
<?php
$timestamp = 1394003958;
echo(date("F d, Y h:i:s", $timestamp));
?>
The above example produce the following output.
The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014:
Example
<?php
// Create the timestamp for a particular date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
The above example produce the following output.
1399735212
The mktime() function can be used to find the weekday name corresponding to a particular date. To do
this, simply use the 'l' (lowercase 'L') character with your timestamp, as in the following example, which
displays the day that falls on April 1, 2014:
Example
<?php
// Get the weekday name of a particular date
echo date('l', mktime(0, 0, 0, 4, 1, 2014));
?>
The above example produce the following output.
Tuesday
The mktime() function can also be used to find a particular date in future after a specific time period. As in
the following example, which displays the date which falls on after 30 month from the current date?
Example
<?php
// Executed at March 05, 2014
$futureDate = mktime(0, 0, 0, date("m")+30, date("d"), date("Y"));
echo date("d/m/Y", $futureDate);
?>
The above example produce the following output.
05/09/2016
You can save a lot of time and work through including files — Just store a block of code in a separate file
and include it wherever you want using the include() and require() statements instead of typing the
entire block of code multiple times. A typical example is including the header, footer and menu file within
all the pages of a website.
The basic syntax of the include() and require() statement can be given with:
include("path/to/filename"); -Or- include "path/to/filename";
require("path/to/filename"); -Or- require "path/to/filename";
Tip: Like the print and echo statements, you can omit the parentheses while using
the include and require statements as demonstrated above.
The following example will show you how to include the common header, footer and menu codes which
are stored in separate 'header.php', 'footer.php' and 'menu.php' files respectively, within all the pages of
your website. Using this technique you can update all pages of the website at once by making the
changes to just one file, this saves a lot of repetitive work.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tutorial Republic</title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>
The only difference is — the include() statement will only generate a PHP warning but allow script
execution to continue if the file to be included can't be found, whereas the require() statement will
generate a fatal error and stops the script execution.
Example
<?php require "my_variables.php"; ?>
<?php require "my_functions.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php displayTitle($home_page); ?></title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>
The include_once and require_once Statements
If you accidentally include the same file (typically functions or classes files) more than one time within
your code using the include or require statements, it may cause conflicts. To prevent this situation, PHP
provides include_once and require_once statements. These statements behave in the same way
as include and require statements with one exception.
The include_once and require_once statements will only include the file once even if asked to include it a
second time i.e. if the specified file has already been included in a previous statement, the file is not
included again. To better understand how it works, let's check out an example. Suppose we've a
'my_functions.php' file with the following code:
Example
<?php
function multiplySelf($var){
$var *= $var; // multiply variable by itself
echo $var;
}
?>
Here's is the PHP script within which we've included the 'my_functions.php' file.
Example
<?php
// Including file
require "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
Example
<?php
// Including file
require_once "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
The first parameter passed to fopen() specifies the name of the file you want to open, and the second
parameter specifies in which mode the file should be opened. For example:
Example
<?php
$handle = fopen("data.txt", "r");
?>
The file may be opened in one of the following modes:
Modes What it does
w Open the file for writing only and clears the contents of file. If the file does not exist, PHP will attempt to
create it.
w+ Open the file for reading and writing and clears the contents of file. If the file does not exist, PHP will
attempt to create it.
a Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If the file
does not exist, PHP will attempt to create it.
a+ Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file.
If the file does not exist, PHP will attempt to create it.
x Open the file for writing only. Return FALSE and generates an error if the file already exists. If the file does
not exist, PHP will attempt to create it.
x+ Open the file for reading and writing; otherwise it has the same behavior as 'x'.
If you try to open a file that doesn't exist, PHP will generate a warning message. So, to avoid these error
messages you should always implement a simple check whether a file or directory exists or not before
trying to access it, with the PHP file_exists() function.
Example
<?php
$file = "data.txt";
Example
<?php
$file = "data.txt";
Example
<?php
$file = "data.txt";
Example
<?php
$file = "data.txt";
The easiest way to read the entire contents of a file in PHP is with the readfile() function. This function
allows you to read the contents of a file without needing to open it. The following example will generate
the same output as above example:
Example
<?php
$file = "data.txt";
Another way to read the whole contents of a file without needing to open it is with
the file_get_contents() function. This function accepts the name and path to a file, and reads the entire
file into a string variable. Here's an example:
Example
<?php
$file = "data.txt";
To process the file data, you need to iterate over the array using a foreach loop. Here's an example, which
reads a file into an array and then displays it using the loop:
Example
<?php
$file = "data.txt";
The fwrite() function takes two parameter — A file handle and the string of data that is to be written, as
demonstrated in the following example:
Example
<?php
$file = "note.txt";
Example
<?php
$file = "note.txt";
Example
<?php
$file = "note.txt";
Example
<?php
$file = "file.txt";
Example
<?php
$file = "note.txt";
Function Description
feof() Checks whether the end of the file has been reached.
Example
<?php
// The directory path
$dir = "testdir";
Example
<?php
// Source file path
$file = "example.txt";
Now we're going to create a custom function that will recursively list all files in a directory using PHP. This
script will be helpful if you're working with deeply nested directory structure.
Example
<?php
// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Scan the files in this directory
$result = scandir($path);
The PHP code in the following example will search the documents directory and list all the files
with .text extension. It will not search the subdirectories.
Example
<?php
/* Search the directory and loop through
returned array containing the matched files */
foreach(glob("documents/*.txt") as $file){
echo basename($file) . " (size: " . filesize($file) . " bytes)" . "<br>";
}
?>
The glob() function can also be used to find all the files within a directory or its subdirectories. The
function defined in the following example will recursively list all files within a directory, just like we've
done in previous example with the scandir() function.
Example
<?php
// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Search the files in this directory
$files = glob($path ."/*");
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$file")){
// Display only filename
echo basename($file) . "<br>";
} else if(is_dir("$file")){
// Recursively call the function if directories found
outputFiles("$file");
}
}
} else{
echo "ERROR: No such file found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="upload-manager.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a
max size of 5 MB.</p>
</form>
</body>
</html>
Note: In addition to a file-select field the upload form must use the HTTP post method and must
contain an enctype="multipart/form-data" attribute. This attribute ensures that the form data is encoded
as mulitpart MIME data — which is required for uploading the large quantities of binary data such as
image, audio, video, etc.
Example
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" =>
"image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
You might be wondering what this code was all about. Well, let's go through each part of this example
code one by one for a better understanding of this process.
Explanation of Code
Once the form is submitted information about the uploaded file can be accessed via PHP superglobal
array called $_FILES. For example, our upload form contains a file select field called photo
(i.e. name="photo"), if any user uploaded a file using this field, we can obtains its details like the name,
type, size, temporary name or any error occurred while attempting the upload via
the $_FILES["photo"] associative array, like this:
• $_FILES["photo"]["name"] — This array value specifies the original name of the file, including the file
extension. It doesn't include the file path.
• $_FILES["photo"]["type"] — This array value specifies the MIME type of the file.
• $_FILES["photo"]["size"] — This array value specifies the file size, in bytes.
• $_FILES["photo"]["tmp_name"] — This array value specifies the temporary name including full path that is
assigned to the file once it has been uploaded to the server.
• $_FILES["photo"]["error"] — This array value specifies error or status code associated with the file
upload, e.g. it will be 0, if there is no error.
The PHP code in the following example will simply display the details of the uploaded file and stores it in
a temporary directory on the web server.
Example
<?php
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
echo "File Name: " . $_FILES["photo"]["name"] . "<br>";
echo "File Type: " . $_FILES["photo"]["type"] . "<br>";
echo "File Size: " . ($_FILES["photo"]["size"] / 1024) . " KB<br>";
echo "Stored in: " . $_FILES["photo"]["tmp_name"];
}
?>
Tip: Once a file has been successfully uploaded, it is automatically stored in a temporary directory on the
server. To store this file on a permanent basis, you need to move it from the temporary directory to a
permanent location using the PHP's move_uploaded_file() function.
Example
<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>
Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive
directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip
and exe files are downloaded automatically to the hard drive by default.
Forcing a Download Using PHP
You can force images or other kind of files to download directly to the user's hard drive using the
PHP readfile() function. Here we're going to create a simple image gallery that allows users to download
the image files from the browser with a single mouse click.
Let's create a file named "image-gallery.php" and place the following code inside it.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
.img-box{
display: inline-block;
text-align: center;
margin: 0 15px;
}
</style>
</head>
<body>
<?php
// Array containing sample image file names
$images = array("kites.jpg", "balloons.jpg");
Here's the complete code of "download.php" file, which force image download.
Example
<?php
if(isset($_REQUEST["file"])){
// Get parameters
$file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
$filepath = "images/" . $file;
// Process download
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
exit;
}
}
?>
Similarly, you can force download other files formats like word doc, pdf files, etc.
PHP Cookies
In this tutorial you will learn how to store a small amount of information within the user's browser itself
using the PHP cookies.
What is a Cookie
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user's computer.
They are typically used to keeping track of information such as username that the site can retrieve to
personalize the page when user visit the website next time.
Tip: Each time the browser requests a page to the server, all the data in the cookie is automatically sent
to the server within the request.
Parameter Description
value The value of the cookie. Do not store sensitive information since this value is stored on the user's
computer.
expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default
value is 0.
path Specify the path on the server for which the cookie will be available. If set to /, the cookie will be
available within the entire domain.
domain Specify the domain for which the cookie is available to e.g www.example.com.
secure This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists.
Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the
session i.e. when the browser closes.
Here's an example that uses setcookie() function to create a cookie named username and assign the
value value John Carter to it. It also specify that the cookie will expire after 30 days (30 days * 24 hours
* 60 min * 60 sec).
Example
<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Note: All the arguments except the name are optional. You may also replace an argument with an empty
string ("") in order to skip that argument, however to skip the expire argument use a zero (0) instead, since
it is an integer.
Warning: Don't store sensitive data in cookies since it could potentially be manipulated by the
malicious user. To store the sensitive data securely use sessions instead.
Example
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
The PHP code in the above example produce the following output.
John Carter
It's a good practice to check whether a cookie is set or not before accessing its value. To do this you can
use the PHP isset() function, like this:
Example
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
You can use the print_r() function like print_r($_COOKIE); to see the structure of
this $_COOKIEassociative array, like you with other arrays.
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie name and any value
(such as an empty string) however this time you need the set the expiration date in the past, as shown in
the example below:
Example
Download
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Tip: You should pass exactly the same path, domain, and other arguments that you have used when you
first created the cookie in order to ensure that the correct cookie is deleted.
PHP Sessions
In this tutorial you will learn how to store certain data on the server on a temporary basis using PHP
session.
What is a Session
Although you can store data using cookies but it has some security issues. Since cookies are stored on
user's computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful
data in your application that might break your application.
Also every time the browser requests a URL to the server, all the cookie data for a website is automatically
sent to the server within the request. It means if you have stored 5 cookies on user's system, each having
4KB in size, the browser needs to upload 20KB of data each time the user views a page, which can affect
your site's performance.
You can solve both of these issues by using the PHP session. A PHP session stores data on the server
rather than user's computer. In a session based environment, every user is identified through a unique
number called session identifier or SID. This unique session ID is used to link each user with their own
information on the server like emails, posts, etc.
Tip: The session IDs are randomly generated by the PHP engine which is almost impossible to guess.
Furthermore, because the session data is stored on the server, it doesn't have to be sent with every
browser request.
The PHP code in the example below simply starts a new session.
Example
Download
<?php
// Starting session
session_start();
?>
The session_start() function first checks to see if a session already exists by looking for the presence of
a session ID. If it finds one, i.e. if the session is already started, it sets up the session variables and if
doesn't, it starts a new session by creating a new session ID.
Note: You must call the session_start() function at the beginning of the page i.e. before any output
generated by your script in the browser, much like you do while setting the cookies
with setcookie() function.
Example
<?php
// Starting session
session_start();
Example
<?php
// Starting session
session_start();
Note: To access the session data in the same page there is no need to recreate the session since it has
been already started on the top of the page.
Destroying a Session
If you want to remove certain session data, simply unset the corresponding key of
the $_SESSIONassociative array, as shown in the following example:
Example
<?php
// Starting session
session_start();
Example
<?php
// Starting session
session_start();
// Destroying session
session_destroy();
?>
Note: Before destroying a session with the session_destroy() function, you need to first recreate the
session environment if it is not already there using the session_start() function, so that there is
something to destroy.
Every PHP session has a timeout value — a duration, measured in seconds — which determines how long
a session should remain alive in the absence of any user activity. You can adjust this timeout duration by
changing the value of session.gc_maxlifetime variable in the PHP configuration file (php.ini).
PHP Send Emails
In this tutorial you will learn how to send simple text or HTML emails directly from the script using the
PHP mail() function.
You can use the PHP built-in mail() function for creating and sending email messages to one or more
recipients dynamically from your PHP application either in a plain-text form or formatted HTML. The basic
syntax of this function can be given with:
mail(to, subject, message, headers, parameters)
Parameter Description
subject Subject of the email to be sent. This parameter i.e. the subject line cannot contain any newline
character (\n).
message Defines the message to be sent. Each line should be separated with a line feed-LF (\n). Lines should
not exceed 70 characters.
headers This is typically used to add extra headers such as "From", "Cc", "Bcc". The additional headers should
be separated with a carriage return plus a line feed-CRLF (\r\n).
Example
<?php
$to = '[email protected]';
$subject = 'Marriage Proposal';
$message = 'Hi Jane, will you marry me?';
$from = '[email protected]';
// Sending email
if(mail($to, $subject, $message)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
To send an HTML email, the process will be the same. However, this time we need to provide additional
headers as well as an HTML formatted message.
Example
Download
<?php
$to = '[email protected]';
$subject = 'Marriage Proposal';
$from = '[email protected]';
// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Note: However, the PHP mail() function is a part of the PHP core but you need to set up a mail server on
your machine to make it really work.
Open up your favorite code editor and create a new PHP file. Now type the following code and save this
file as "contact-form.php" in the root directory of your project.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php" method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName">
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
Explanation of code
Notice that there are two attributes within the opening <form> tag:
• The action attribute references a PHP file "process-form.php" that receives the data entered into the form
when user submit it by pressing the submit button.
• The method attribute tells the browser to send the form data through POST method.
Rest of the elements inside the form are basic form controls to receive user inputs. To learn more about
HTML form elements please check out the HTML Forms tutorial.
Superglobal Description
$_GET Contains a list of all the field names and values sent by a form using the get method (i.e. via the URL
parameters).
$_POST Contains a list of all the field names and values sent by a form using the post method (data will not
visible in the URL).
$_REQUEST Contains the values of both the $_GET and $_POST variables as well as the values of
the $_COOKIE superglobal variable.
When a user submit the above contact form through clicking the submit button, the form data is sent to
the "process-form.php" file on the server for processing. It simply captures the information submitted by
the user and displays it to browser.
The PHP code of "process-form.php" file will look something like this:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_POST["name"]?></li>
<li><em>Email:</em> <?php echo $_POST["email"]?></li>
<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
<li><em>Message:</em> <?php echo $_POST["message"]?></li>
</ol>
</body>
</html>
The PHP code above is quite simple. Since the form data is sent through the post method, you can
retrieve the value of a particular form field by passing its name to the $_POST superglobal array, and
displays each field value using echo() statement.
In real world you cannot trust the user inputs; you must implement some sort of validation to filter the
user inputs before using them. In the next chapter you will learn how sanitize and validate this contact
form data and send it through the email using PHP.