2. 1
Introduction to PHP
PHP is a widely-used general-purpose scripting language that is especially suited for Web
development and can be embedded into HTML. PHP is the Web Development Language written
by and for Web developers. PHP stands for PHP: Hypertext Preprocessor. The product was
originally named Personal Home Page Tools, and many people still think that`s what the acronym
stands for. But as it expanded in scope, a new and more appropriate name was selected by
community vote. PHP is a server-side scripting language, which can be embedded in HTML or
used as a standalone binary (although the former use is much more common). Much of its syntax
is borrowed from C.
1.1 History of PHP
PHP development began in 1994 when the developer Rasmus Lerdorf wrote a series of Common
Gateway Interface (CGI) Perl scripts, which he used to maintain his personal homepage. The tools
performed tasks such as displaying his résumé and recording his web traffic[1]
.He rewrote these
scripts in C for performance reasons, extending them to add the ability to work with web forms
and to communicate with databases and called this implementation "Personal Home Page/Forms
Interpreter" or PHP/FI. PHP/FI could be used to build simple, dynamic web applications. Lerdorf
initially announced the release of PHP/FI as "Personal Home Page Tools (PHP Tools) version 1.0"
publicly to accelerate bug location and improve the code, on the
comp.infosystems.www.authoring.cgi Usenet discussion group on June 8, 1995. This release
already had the basic functionality that PHP has today. This included Perl-like variables, form
handling, and the ability to embed HTML. The syntax was similar to Perl but was more limited
and simpler, although less consistent. A development team began to form and, after months of
work and beta testing, officially released PHP/FI 2 in November 1997.
1.2 Versions of PHP:
1.2.1 PHP1, PHP2:
These versions were primary versions of PHP which are now not at all used.
1.2.2 PHP3:
PHP 3.0 was the first version that closely resembles PHP as it exists today. Finding PHP/FI 2.0
still inefficient and lacking features they needed to power an eCommerce application they were
developing for a university project, Andi Gutmans and Zeev Suraski of Tel Aviv, Israel, began yet
3. 2
another complete rewrite of the underlying parser in 1997. Approaching Rasmus online, they
discussed various aspects of the current implementation and their redevelopment of PHP. In an
effort to improve the engine and start building upon PHP/FI's existing user base, Andi, Rasmus,
and Zeev decided to collaborate in the development of a new, independent programming language.
This entirely new language was released under a new name, that removed the implication of
limited personal use that the PHP/FI 2.0 name held. It was renamed simply 'PHP', with the
meaning becoming a recursive acronym - PHP: Hypertext Preprocessor.
One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to
providing end users with a mature interface for multiple databases, protocols, and APIs, the ease
of extending the language itself attracted dozens of developers who submitted a variety of
modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features
introduced in PHP 3.0 included object-oriented programming support and a far more powerful and
consistent language syntax.
In June, 1998, with many new developers from around the world joining the effort, PHP 3.0 was
announced by the new PHP Development Team as the official successor to PHP/FI 2.0. At its
peak, PHP 3.0 was installed on approximately 10% of the web servers on the Internet.
1.2.3 PHP4:
By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev
Suraski had begun working on a rewrite of PHP's core. The design goals were to improve
performance of complex applications, and improve the modularity of PHP's code base. Such
applications were made possible by PHP 3.0's new features and support for a wide variety of third
party databases and APIs, but PHP 3.0 was not designed to handle such complex applications
efficiently.
The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these
design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine,
and coupled with a wide range of additional new features, was officially released in May 2000,
almost two years after its predecessor. In addition to the highly improved performance of this
version, PHP 4.0 included other key features such as support for many more web servers, HTTP
sessions, output buffering, more secure ways of handling user input and several new language
constructs.
1.2.4 PHP5:
On July 14, 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5 included new
features such as improved support for object-oriented programming, the PHP Data Objects (PDO)
4. 3
extension (which defines a lightweight and consistent interface for accessing databases), and
numerous performance enhancements. In 2008 PHP 5 became the only stable version under
development. Late static binding had been missing from PHP and was added in version 5.3.
Many high-profile open-source projects ceased to support PHP 4 in new code as of February 5,
2008, because of the GoPHP5 initiative, provided by a consortium of PHP developers promoting
the transition from PHP 4 to PHP 5.
Over time, PHP interpreters became available on most existing 32-bit and 64-bit operating
systems, either by building them from the PHP source code, or by using pre-built binaries. For the
PHP versions 5.3 and 5.4, the only available Microsoft Windows binary distributions were 32-
bit x86 builds, requiring Windows 32-bit compatibility mode while using Internet Information
Services (IIS) on a 64-bit Windows platform. PHP version 5.5 made the 64-bit x86-64 builds
available for Microsoft Windows.
1.2.5 PHP6:
PHP received mixed reviews due to lacking native Unicode support at the core language level. In
2005, a project headed by Andrei Zmievski was initiated to bring native Unicode support
throughout PHP, by embedding the International Components for Unicode (ICU) library, and
representing text strings as UTF-16 internally. Since this would cause major changes both to the
internals of the language and to user code, it was planned to release this as version 6.0 of the
language, along with other major features then in development.
However, a shortage of developers who understood the necessary changes, and performance
problems arising from conversion to and from UTF-16, which is rarely used in a web context, led
to delays in the project. As a result, a PHP 5.3 release was created in 2009, with many non-Unicode
features back-ported from PHP 6, notably namespaces. In March 2010, the project in its current
form was officially abandoned, and a PHP 5.4 release was prepared containing most remaining
non-Unicode features from PHP 6, such as traits and closure re-binding. Initial hopes were that a
new plan would be formed for Unicode integration, but as of 2014 none have been adopted.
1.2.6 PHP7:
During 2014 and 2015, a new major PHP version was developed, which was numbered PHP 7.
The numbering of this version involved some debate. While the PHP 6 Unicode experiment had
never been released, several articles and book titles referenced the PHP 6 name, which might have
caused confusion if a new release were to reuse the name. After a vote, the name PHP 7 was
chosen.
5. 4
The foundation of PHP 7 is a PHP branch that was originally dubbed PHP next
generation (phpng). It was authored by Dmitry Stogov, Xinchen Hui and Nikita Popov and aimed
to optimize PHP performance by refactoring the Zend Engine while retaining near-complete
language compatibility. As of 14 July 2014, WordPress-based benchmarks, which served as the
main benchmark suite for the phpng project, showed an almost 100% increase in performance.
Changes from phpng are also expected to make it easier to improve performance in the future, as
more compact data structures and other changes are seen as better suited for a successful migration
to a just-in-time (JIT) compiler. Because of the significant changes, the reworked Zend Engine is
called Zend Engine 3, succeeding Zend Engine 2 used in PHP 5. Because of major internal changes
in phpng, it must receive a new major version number of PHP, rather than a minor PHP 5 release,
according to PHP's release process. Major versions of PHP are allowed to break backward-
compatibility of code and therefore PHP 7 presented an opportunity for other improvements
beyond phpng that require backward-compatibility breaks. Many fatal- or recoverable-level
legacy PHP error mechanisms were replaced with modern object-oriented exceptions. The syntax
for variable dereferencing was reworked to be internally more consistent and complete, allowing
the use of the operators ->, [], (), {}, and :: with arbitrary meaningful left-hand-side expressions.
Constructors for the few classes built-in to PHP which returned null upon failure were changed to
throw an exception instead, for consistency. Support for legacy ASP-style PHP code delimiters
(<% and %>, <script language=php> and </script>) was removed. Support for hexadecimal
number support in some implicit conversions from strings to number types was removed.
Conversions between integers and floating point numbers were tightened and implemented more
consistently across platforms.
1.3 FEATURES OF PHP:
1.3.1 SERVER SIDE SCRIPTING
PHP was originally designed to create dynamic web content, and it is still best suited for
that task. To generate HTML, we need the PHP parser and a web server to send the
documents. Lately, PHP has also become popular for generating XML documents,
graphics, Flash animations, PDF files, and more.
1.3.2 COMMAND LINE SCRIPTING
PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. We
might use the command-line scripts for system administration tasks, such as backup and
log parsing.
6. 5
1.3.3 CLIENT SIDE GUI APPLICATIONS
Using PHP-GTK (http://gtk.php.net), We can write full-blown, cross-platform GUI
applications in PHP.
1.3.4 OPERATING SYSTEM SUPPORT
PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD,
and Solaris to such diverse platforms as Windows and Mac OS X. It can be used with all
leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers.
1.3.5 DATABASE SUPPORT
One of PHP's most significant features is its wide-ranging support for databases. PHP
supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, and ODBC-
compliant databases), and even many obscure ones. With PHP, creating web pages with
dynamic content from a database is remarkably simple.
Finally, PHP provides a library of PHP code to perform common tasks, such as database
abstraction, error handling, and so on, with the PHP Extension and Application Repository
(PEAR). PEAR is a framework and distribution system for reusable PHP components.
1.4 Basic PHP Syntax:
PHP code is executed on the server, and the plain HTML result is sent to the browser. A PHP
scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed
anywhere in the document.
<?php
?>
Figure 1: PHP Syntax
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the
browser:
<html>
<body>
<?php
echo "Hello World";
7. 6
?>
</body>
</html>
Figure 2: PHP Hello Word
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.
1.5 Comments in PHP:
In PHP, there are two types of comments used here. These types are as follows:
Single line comment:
In this we use // to make a single-line comment
<html>
<body>
<?php
//This is a single line comment
?>
</body>
</html>
Figure 3: Single Line Comment
Multiple line comment:
In this we use /* and */ to make a large comment block.
<html>
<body>
<?php
/*
This is a multiline
Comment block
*/
?>
</body>
</html>
Figure 4: Multi Line Comment
8. 7
1.6 PHP echo
The PHP command echo is a means of outputting text to the web browser. To output a string, we
use PHP echo. We can place either a string variable or we can use quotes, like we do below, to
create a string that the echo function will output.
<?php
$txt="Hello World!";
echo $txt;
echo “<h5>Using ECHO</h5>”;
?>
OUTPUT
Hello World!
Using ECHO
Figure 5: PHP echo
In the above example we output "Hello World!" without a hitch. The text we are outputting is
being sent to the user in the form of a web page, so it is important that we use proper HTML
syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this
we simply put the <h5> at the beginning of the string and closed it at the end of the string.
1.7 PHP print
The print statement can be used with or without parentheses: print or print().
The following example shows how to output text with the print command (notice that the text
can contain HTML markup):
<?php
$txt1 = "Learn PHP";
$txt2 = "IUST";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
OUTPUT
Learn PHP
Study PHP at IUST
9
Figure 6: PHP print
9. 8
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
10. 9
PHP Variables
A variable is used to store information. A variable is a means of storing a value, such as text string
"Hello World!" or the integer value 4. A variable can then be reused throughout our code, instead
of having to type out the actual value over and over again. Also, variable names are case-sensitive,
so use the exact same capitalization when using a variable. The variables $a_number and
$A_number are different variables in PHP's eyes.
2.1 Variables in PHP
All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in
PHP:
$var_name = value;
Figure 7: Variable Declaration
Without $ before a variable it will not work. An Example of variable containing a string, and a
variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
Figure 8:Variable Example
2.2 PHP is a Loosely Typed Language
In PHP, a variable does not need to be declared before adding a value to it. In the example above,
we see that we do not have to tell PHP which data type the variable is. PHP automatically converts
the variable to the correct data type, depending on its value. In a strongly typed programming
language, we have to declare (define) the type and name of the variable before using it. In PHP,
the variable is declared automatically when we use it.
2.3 Naming Rules for Variables
A variable name must start with a letter or an underscore "_"
A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-
9, and _ )
11. 10
A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with an underscore ($my_string), or with capitalization ($my_String)
2.4 PHP Variables Scope:
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local
global
static
2.4.1 Global and Local Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function
The global keyword is used to access a global variable from within a function.
To do this, we use the global keyword before the variables (inside the function):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y
?>
OUTPUT
15
Figure 9: Global Variable
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.
<?php
$x = 5;
$y = 10;
OUTPUT
15
12. 11
function myTest() {
$GLOBALS['y'] = $GLOBALS['x']
+ $GLOBALS['y'];
}
myTest();
echo $y;
?>
Figure 10: Use of $GLOBALS
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable not to be deleted. We need it for a further job.
To do this, we use the static keyword when we first declare the variable:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
OUTPUT
0
1
2
Figure 11: Use of Static keyword
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called. The variable is still local to the function.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
13. 12
PHP Strings & Constants
A string variable is used to store and manipulate text.
3.1 String Variables in PHP
String variables are used for values that contain characters. After we create a string we can
manipulate it. A string can be used directly in a function or it can be stored in a variable. Below,
the PHP script assigns the text "Hello World" to a string variable called $txt:
<?php
$txt="Hello World";
echo $txt;
?>
OUTPUT
Hello World
Figure 12: String Variable
3.2 The Concatenation Operator
There is only one string operator in PHP. The concatenation operator (.) is used to put two string
values together. To concatenate two string variables together, use the concatenation operator:
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
OUTPUT
Hello World! What a nice day!
Figure 13: Concatenation Operator
We used the concatenation operator two times. This is because we had to insert a third string (a
space character), to separate the two strings.
3.3 Predefined String Functions
3.3.1 The strlen() function:
The strlen() function is used to return the length of a string.
SYNTAX:
strlen(string)
14. 13
<?php
echo strlen("Hello world!");
?>
OUTPUT
12
Figure 14: strlen() function
The length of a string is often used in loops or other functions, when it is important to know when
the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).
3.3.2 The strpos() function:
The strpos() function is used to search for character within a string. If a match is found, this
function will return the position of the first match. If no match is found, it will return FALSE.
SYNTAX:
strpos(string_to_search,string_to_find,start)
<?php
echo strpos("Hello world!","world");
?>
OUTPUT
6
Figure 15: strpos() function
The position of the string "world" in our string is position 6. The reason that it is 6 (and not 7), is
that the first position in the string is 0, and not 1. The strpos() function is case-sensitive. The
stripos() returns the position of the first occurrence of a string inside another string (case-
insensitive).
3.3.3 The htmlentities() & html_entity_decode() function:
The htmlentities() function converts characters to HTML entities. To convert HTML entities back
to characters, use the html_entity_decode() function.
SYNTAX
htmlentities(string,flags,character-set,double_encode)
html_entity_decode(string,flags,character-set)
15. 14
Figure 16: htmlentities() function
PHP CODE:
<?php
$str = '<a href="https://www.google.com">google.com</a>';
echo html_entity_decode($str);
?>
SOURCE CODE:
<a href="https://www.google.com">Go to google.com</a>
BROWSER OUTPUT:
Go to google.com
Figure 17:html_entity_decode()
3.3.4 The lcfirst() function:
The lcfirst() function converts the first character of a string to lowercase.
SYNTAX
lcfirst(string)
Related functions:
ucfirst() - converts the first character of a string to uppercase
ucwords() - converts the first character of each word in a string to uppercase
strtoupper() - converts a string to uppercase
strtolower() - converts a string to lowercase
PHP CODE:
<?php
$str = '<a href="https://www.google.com">Go to google.com</a>';
echo htmlentities($str);
?>
SOURCE CODE:
<a href="https://www.googlw.com">Go to google.com</a>
BROWSER OUTPUT:
<a href="https://www.google.com">Go to google.com</a>
16. 15
<?php
echo lcfirst("Hello world!");
?>
OUTPUT
hello world!
Figure 18:lcfirst()
3.3.5 The trim() function:
The trim() function removes whitespace and other predefined characters from both sides of a
string
SYNTAX:
trim(string,charlist)
charlist specifies which characters to remove from the string. If omitted, all of the following
characters are removed:
"0" - NULL
"t" - tab
"n" - new line
"x0B" - vertical tab
"r" - carriage return
" " - ordinary white space
Related functions:
ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a
string
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
OUTPUT
Hello World!
llo Worl
Figure 19: trim() function
17. 16
3.3.6 The substr() function:
The substr() function returns a part of a string. If the start parameter is a negative number and
length is less than or equal to start, length becomes 0.
SYNTAX:
substr(string,start,length)
<?php
// Positive numbers:
echo substr("Hello world",0,10)."<br>";
echo substr("Hello world",1,8)."<br>";
echo substr("Hello world",-10,-2)."<br>";
echo substr("Hello world",0,-6)."<br>";
?>
OUTPUT
Hello worl
ello wor
ello wor
Hello
Figure 20: substr() function
3.3.7 The str_repeat() function:
The str_repeat() function repeats a string a specified number of times.
SYNTAX:
str_repeat(string,repeat)
<?php
echo str_repeat(".",13);
?>
OUTPUT
.............
Figure 21: str_repeat() function
3.3.8 The str_replace() function:
The str_replace() function replaces some characters with some other characters in a string.
This function works by the following rules:
If the string to be searched is an array, it returns an array
If the string to be searched is an array, find and replace is performed with every array
element
If both find and replace are arrays, and replace has fewer elements than find, an empty
string will be used as replace
If find is an array and replace is a string, the replace string will be used for every find value
18. 17
This function is case-sensitive. The str_ireplace() function is used to perform a case-insensitive
search.
SYNTAX:
str_replace(find,replace,string,count)
<?php
echo str_replace("world","Peter","Hello world!");
?>
OUTPUT
Hello Peter!
Figure 22:str_replace() function
3.3.9 The strchr() function
The strchr() function searches for the first occurrence of a string inside another string. This
function is case-sensitive. For a case-insensitive search, we use stristr() function.
SYNTAX:
strchr(string,search,before_search)
<?php
echo strchr("Hello world!","world");
?>
OUTPUT
world!
Figure 23: strchr() function
3.3.10 The strcmp() function:
The strcmp() function compares two strings. The strcmp() function is case-sensitive.
SYNTAX:
strcmp(string1,string2)
<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>
OUTPUT
0
-1
Figure 24: strcmp() function
19. 18
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
3.4 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).
Unlike variables, constants are automatically global across the entire script.
To create a constant, use the define() function
SYNTAX:
define(name, value, case-insensitive)
<?php
define("GREETING", "Welcome to
W3Schools.com!", true);
echo greeting;
echo GREETING
?>
OUTPUT
Welcome to W3Schools.com!
Welcome to W3Schools.com!
Figure 25: define() function
20. 19
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Table 1: PHP Arithmetic Operators
Table 2:PHP Assignment Operators
Assignment Same as... Description
x = y x = y
The left operand gets set to the value of the
expression 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
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y
Result of raising $x to the $y'th
power (Introduced in PHP 5.6)
21. 20
Table 3: PHP Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y
Returns true if $x is equal to $y, and
they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y
Returns true if $x is not equal to $y, or
they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>=
Greater than
or equal to
$x >= $y
Returns true if $x is greater than or
equal to $y
<=
Less than or
equal to
$x <= $y
Returns true if $x is less than or equal
to
Table 4: PHP Increment / Decrement Operators
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Table 5: PHP Logical Operators
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y
True if either $x or $y is true, but
not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
Table 6: PHP String Operators
Operator Name Example Result
. Concatenation $txt1 . $txt2
Concatenation of $txt1
and $txt2
.=
Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to $txt1
22. 21
Table 7:PHP Array Operators
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y
Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y
Returns true if $x and $y have the same
key/value pairs in the same order and of
the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!==
Non-
identity
$x !== $y Returns true if $x is not identical to $y
23. 22
PHP User Defined Functions
PHP comes with hundreds of ready-made, built-in functions, making it a very rich language. To
use a function, call it by name Besides the built-in PHP functions, we can create our own
functions. A function is a block of statements that can be used repeatedly in a program. A function
will not execute immediately when a page loads. A function will be executed by a call to the
function. A function name can start with a letter or underscore (not a number). Information can
be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. We can add as many
arguments as we want, just separate them with a comma. We can let a function return a value
using return statement.
5.1 Create a User Defined Function in PHP
A user defined function declaration starts with the word "function"
SYNTAX:
function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
function sum($x, $y) {
$z = $x + $y;
return $z;
}
writeMsg();
setHeight();
setHeight(80);
echo sum(2,4);
?>
OUTPUT
Hello world!
The height is : 50
The height is : 80
6
Figure 26: User Defined Function
24. 23
PHP Arrays
An array is a special variable, which can hold more than one value at a time. An array can hold
many values under a single name, and we can access the values by referring to an index number.
Some arrays are referenced by numeric indices; others allow alphanumeric identifiers. Built-in
functions let us sort them, add or remove sections, and walk through them to handle each item
through a special kind of loop. And by placing one or more arraysinside another, we can create
arrays of two, three, or any number of dimensions.
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
6.1 Indexed Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
<?php
$cars = array("Volvo", "BMW", "Toyota");
/* $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota"; */
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
OUTPUT
I like Volvo, BMW and Toyota.
Figure 27: Indexed Array
6.2 PHP Associative Arrays:
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that we can
establish a strong association between key and values.
25. 24
To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" =>
1000, "zara" => 500);
echo "Salary of mohammad is ".
$salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ".
$salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
OUTPUT
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Figure 28: Associative Array
6.3 Loop through an Associative Array
To loop through and print all the values of an associative array, we use a foreach loop.
SYNTAX:
foreach ($array as $value) {
code to be executed;
}
26. 25
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.
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
$age= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
OUTPUT
red
green
blue
yellow
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Figure 29: foreach loop
6.4 PHP Multidimensional Array
A multidimensional array is an array containing one or more arrays. In multi-dimensional array
each element in the main array can also be an array. And each element in the sub-array can be an
array, and so on. Values in the multi-dimensional array are accessed using multiple index.
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
OUTPUT
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
27. 26
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
Figure 30: Multidimensional Array
6.5 The print_r () function
An array in PHP computer programming contains a group of similar objects that are the same type
and size. The array can contain integers, characters or anything else with a defined data type.
The print_r PHP function is used to return an array in a human readable form. It is written as
print_r($your_array)
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
OUTPUT
Array
(
[a] => apple
[b] => banana
28. 27
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
Figure 31: print_r() function
6.6 Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
In this chapter, we will go through the following PHP array sort functions:
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
OUTPUT
BMW
Toyota
Volvo
Figure 32: sort() function
29. 28
Table 8: PHP Array Functions
Function Description
array() Creates an array
array_chunk() Splits an array into chunks of arrays
array_combine()
Creates an array by using the elements from one "keys" array and one
"values" array
array_count_values() Counts all the values of an array
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_intersect() Compare arrays, and returns the matches (compare values only)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_merge() Merges one or more arrays into one array
array_pop() Deletes the last element of an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_unique() Removes duplicate values from an array
array_values() Returns all the values of an array
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Returns the current key and value pair from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
30. 29
PHP Global Variables – Superglobals
Several predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and can be accessed from any function, class or file without
having to do anything special.
The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
7.1 PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods). PHP stores all global
variables in an array called $GLOBALS[index]. The index holds the name of the variable.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x']
+ $GLOBALS['y'];
}
addition();
echo $z;
?>
OUTPUT
100
Figure 33: $GLOBALS use
31. 30
7.2 PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations. The entries in this array are created by the web server.
Table 9: $_SERVER Variables
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently
executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common
Gateway Interface (CGI) the server is
using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host
server
$_SERVER['SERVER_NAME'] Returns the name of the host server
(such as www.w3schools.com)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification
string (such as Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the
information protocol (such as
HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to
access the page (such as POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of
the request (such as 1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is
accessed via a query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the
current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header
from the current request (such as utf-
8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the
current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the
current page (not reliable because not
all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure
HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where
the user is viewing the current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where
the user is viewing the current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the
user's machine to communicate with
the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the
currently executing script
32. 31
$_SERVER['SERVER_ADMIN'] Returns the value given to the
SERVER_ADMIN directive in the web
server configuration file (if our script
runs on a virtual host, it will be the
value defined for that virtual host)
(such as someone@w3schools.com)
$_SERVER['SERVER_PORT'] Returns the port on the server
machine being used by the web
server for communication (such as
80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual
host name which are added to server-
generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to
the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
7.3 PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form. It is an associative
array consisting of the contents of $_GET, $_POST, and $_COOKIE.
7.4 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.
7.5 PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get". $_GET can also collect data sent in the URL.
33. 32
Conditional Statements
Very often when we write code, we want to perform different actions for different decisions. We
can use conditional statements in our code to do this.
In PHP we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is true.
if...else statement - use this statement to execute some code if a condition is true and
another code if the condition is false.
if...else if....else statement - use this statement to select one of several blocks of code to be
executed.
switch statement - use this statement to select one of many blocks of code to be executed
8.1 The if Statement
The if statement is used to execute some code only if a specified condition is true.
SYNTAX:
if (condition) code to be executed if condition is true;
8.2 The if...else Statement
The if....else statement is used to execute some code if a condition is true and another code if a
condition is false.
SYNTAX:
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
8.3 The if...else if....else Statement
The if....else if...else statement is used to select one of several blocks of code to be executed.
34. 33
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;
8.4 Switch Statement
Conditional statements are used to perform different actions based on different conditions. Switch
statement is used to select one of many blocks of code to be executed.
SYNTAX:
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
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.
35. 34
PHP – GET & POST Methods
There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by the
ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other non-alphanumeric characters
are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
9.1 The GET Method
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ?character.
http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in our server logs, in the browser's Location:
box.
The GET method is restricted to send upto 1024 characters only. GET can't be used to send binary
data, like images or word documents, to the server. The PHP provides $_GET associative array
to access all the sent information using GET method. However, because the variables are
displayed in the URL, it is possible to bookmark the page. GET should never be used for sending
passwords or other sensitive information! This can be useful in some cases. GET may be used for
sending non-sensitive data.
9.2 The POST Method
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING. The POST
method does not have any restriction on data size to be sent. The POST method can be used to
send ASCII as well as binary data. The data sent by POST method goes through HTTP header so
securitydepends on HTTP protocol. By using Secure HTTP we can make sure that our information
is secure. The PHP provides $_POST associative array to access all the sent information using
36. 35
POST method. Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request)
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method
= "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
OUTPUT after submitting the form
Welcome Sahil
You are 21 years old
Figure 34: Basic Form
37. 36
PHP File Inclusion
We can include the content of a PHP file into another PHP file before the server executes it. There
are two PHP functions which can be used to included one PHP file into another PHP file.
The include() Function
The require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that
can be reused on multiple pages. This will help developers to make it easy to change the layout of
complete website with minimal effort. If there is any change required then instead of changing
thousands of files just change included file. The include (or require) statement takes all the
text/code/markup that exists in the specified file and copies it into the file that uses the include
statement.
10.1 The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include() function generates a
warning but the script will continue execution.
The include_once() statement can be used to include a php file in another one, when we may need
to include the called file more than once. If it is found that the file has already been included,
calling script is going to ignore further inclusions.
SYNTAX:
include_once('name of the called file with path');
10.2 The require() Function
The require() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the require() function generates a
fatal error and halt the execution of the script.It is recommended to use the require() function
instead of include(), because scripts should not continue executing if files are missing or
misnamed.
The require_once() statement can be used to include a php file in another one, when we may need
to include the called file more than once. If it is found that the file has already been included,
calling script is going to ignore further inclusions.
SYNTAX:
require_once('name of the calling file with path');
38. 37
PHP Files & I/O
11.1 Creating, Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file
name and then mode in which to operate. If an attempt to open a file fails then fopen returns a
value of false otherwise it returns a file pointer which is used for further reading or writing to that
file.
Table 10: Modes of Operation of fopen()
Modes Description
r
Open a file for read only. File pointer starts at the beginning of the
file
w
Open a file for write only. Erases the contents of the file or
creates a new file if it doesn't exist. File pointer starts at the
beginning of the file
a
Open a file for write only. The existing data in file is preserved.
File pointer starts at the end of the file. Creates a new file if the file
doesn't exist
x
Creates a new file for write only. Returns FALSE and an error if
file already exists
r+
Open a file for read/write. File pointer starts at the beginning of
the file
w+
Open a file for read/write. Erases the contents of the file or
creates a new file if it doesn't exist. File pointer starts at the
beginning of the file
a+
Open a file for read/write. The existing data in file is preserved.
File pointer starts at the end of the file. Creates a new file if the file
doesn't exist
x+
Creates a new file for read/write. Returns FALSE and an error if
file already exists
The fopen() function is also used to create a file. If we use fopen() on a file that does not exist, it
will create it, given that the file is opened for writing (w) or appending (a). The file will be created
in the same directory where the PHP code resides.
After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the closure
succeeds or false if it fails.
39. 38
11.2 Reading a file
Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and maximum number of bytes to
read usually the length of the file.
The files length can be found using the filesize() function which takes the file name as its argument
and returns the size of the file expressed in bytes.
11.2.1 Read Single Line - fgets()
The fgets() function is used to read a single line from a file.
11.2.2 PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is
useful for looping through data of unknown length.
11.2.3 PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
OUTPUT
Figure 35: Reading a file
40. 39
11.3 Writing a file
A new file can be written or text can be appended to an existing file using the
PHP fwrite() function. This function requires two arguments specifying a file pointer and the
string of data that is to be written. Optionally a third integer argument can be included to specify
the length of the data to write. If the third argument is included, writing would will stop after the
specified length has been reached. After closing this file its existence is confirmed
using file_exist()function which takes file name as an argument
The following example creates a new text file then writes a short text heading inside it.
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple testn" );
fclose( $file );
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "$filetext" );
echo("file name: $filename");
?>
OUTPUT
Figure 36: Writing to a file
41. 40
11.4 PHP File Uploading
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially
files are uploaded into a temporary directory and then relocated to a target destination by a PHP
script.
The process of uploading a file follows these steps −
The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the submit
button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form's action attribute checks
that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail. An
uploaded file could be a text file or image file or any document.
11.4.1 Creating an upload form
The following HTM code below creates an uploader form. This form is having method attribute
set to post and enctype attribute is set to multipart/form-data
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
42. 41
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
OUTPUT
Figure 37: File Upload Script
There is one global PHP variable called $_FILES. This variable is an associate double dimension
array and keeps all the information related to uploaded file. So if the value assigned to the input's
name attribute in uploading form was file, then PHP would create following five variables −
$_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web
server.
$_FILES['file']['name'] − the actual name of the uploaded file.
$_FILES['file']['size'] − the size in bytes of the uploaded file.
$_FILES['file']['type'] − the MIME type of the uploaded file.
$_FILES['file']['error'] − the error code associated with this file upload.
43. 42
Table 11: File System Functions
Function Description
basename() Returns the filename component of a path
chmod() Changes the file mode
chown() Changes the file owner
copy() Copies a file
dirname() Returns the directory name component of a path
fclose() Closes an open file
feof() Tests for end-of-file on an open file
fflush() Flushes buffered output to an open file
fgetc() Returns a character from an open file
fgets() Returns a line from an open file
fgetss() Returns a line, with HTML and PHP tags removed, from an open file
file() Reads a file into an array
file_exists() Checks whether or not a file or directory exists
file_get_contents() Reads a file into a string
file_put_contents() Writes a string to a file
fileatime() Returns the last access time of a file
filectime() Returns the last change time of a file
filemtime() Returns the last modification time of a file
fileowner() Returns the user ID (owner) of a file
fileperms() Returns the permissions of a file
filesize() Returns the file size
filetype() Returns the file type
fopen() Opens a file or URL
fread() Reads from an open file
fscanf() Parses input from an open file according to a specified format
fwrite() Writes to an open file
is_dir() Checks whether a file is a directory
is_executable() Checks whether a file is executable
is_file() Checks whether a file is a regular file
is_link() Checks whether a file is a link
44. 43
is_readable() Checks whether a file is readable
is_uploaded_file() Checks whether a file was uploaded via HTTP POST
is_writable() Checks whether a file is writeable
mkdir() Creates a directory
move_uploaded_file() Moves an uploaded file to a new location
pathinfo() Returns information about a file path
readfile() Reads a file and writes it to the output buffer
rename() Renames a file or directory
rmdir() Removes an empty directory
tmpfile() Creates a unique temporary file
unlink() Deletes a file
45. 44
PHP Cookies & Sessions
12.1 PHP Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP
transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
12.1.1 Setting Cookies
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments −
Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS or $_COOKIE. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that we actually want
to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After
this time cookie will become inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
Path − This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
Security − This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
46. 45
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Figure 38: Setting Cookies
12.1.2 Accessing Cookies
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables.
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
Figure 39: Accessing Cookies
47. 46
12.1.3 Deleting a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
echo "Cookie 'user' is deleted.";
?>
Figure 40: Deleting a Cookie
12.2 PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages. Unlike a
cookie, the information is not stored on the users computer. Session variables store user
information to be used across multiple pages (e.g. username, favorite color, etc). By default,
session variables last until the user closes the browser. So, Session variables hold information
about one single user, and are available to all pages in one application.
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file
called session.save_path.
When a session is started following things happen −
PHP first creates a unique identifier for that particular session which is a random string of
32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the
unique session identifier string from the PHPSESSID cookie and then looks in its temporary
directory for the file bearing that name and a validation can be done by comparing both values.
48. 47
A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.
12.2.1 Starting a PHP Session
A PHP session is easily started by making a call to the session_start()function. This function first
checks if a session is already started and if none is started then it starts one. It is recommended to
put the call to session_start() at the beginning of the page. Session variables are stored in
associative array called $_SESSION[]. These variables can be accessed during lifetime of a
session.
The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session.
<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ".
$_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
OUTPUT
You have visited this page 1in this session.
49. 48
12.2.2 Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If we want to destroy a single
session variable then we can use unset() function to unset a session variable.
SYNTAX:
To unset a single variable
unset($_SESSION['counter']);
To destroy all the session variables
session_destroy();
50. 49
PHP & MySQL
PHP will work with virtually all database software, including Oracle and Sybase but most
commonly used is freely available MySQL database.
MySQL is a database system used on the web. It runs on a server and is ideal for both small and
large applications. It is very fast, reliable, and easy to use. It uses standard SQL and compiles on
a number of platforms. MySQL is developed, distributed, and supported by Oracle Corporation.
It is free to download and use. The data in a MySQL database are stored in tables. A table is a
collection of related data, and it consists of columns and rows.
13.1 Creating Connection
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
Both MySQLi and PDO have their advantages. PDO will work on 12 different database systems,
whereas MySQLi will only work with MySQL databases. So, if we have to switch our project to
use another database, PDO makes the process easy. We only have to change the connection string
and a few queries. With MySQLi, we will need to rewrite the entire code - queries included. Both
are object-oriented, but MySQLi also offers a procedural API. Both support Prepared Statements.
Prepared Statements protect from SQL injection, and are very important for web application
security.
Using mysqli_connect(), we can open a connection to MySQL.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
51. 50
13.2 Closing Connection
The connection will be closed automatically when the script ends. To close the connection
before, we use mysqli_close() or mysqli_close($conn);
This function takes connection resource returned by mysql_connect function. It returns TRUE on
success or FALSE on failure. If a resource is not specified then last opend database is closed.
13.3 Creating a Database
To create and delete a database we should have admin privilege. A database consists of one or
more tables. We need special CREATE privileges to create or to delete a MySQL database. The
CREATE DATABASE statement is used to create a database in MySQL.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
52. 51
13.4 Selecting a Database
Once we establish a connection with a database server then it is required to select a particular
database where our all the tables are associated. This is required because there may be multiple
databases residing on a single server and we can do work with a single database at a time.
PHP provides function mysql_select_db to select a database. It returns TRUE on success or
FALSE on failure.
SYNTAX:
bool mysqli_select_db( db_name, connection );
13.5 Deleting a Database
If a database is no longer required then it can be deleted forever. We can use pass an SQL
command to mysql_query to delete a database.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP DATABASE test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not delete database db_test: ' . mysql_error());
}
echo "Database deleted successfullyn";
mysql_close($conn);
?>
53. 52
13.6 Create MySQL Table
To create tables in the new database we need to do the same thing as creating the database. First
create the SQL query to create the tables then execute the query using mysqli_query() function.
13.7 Delete MySQL Table
It is again a matter of issuing one SQL command i.e. DROP TABLE through mysqli_query
function to delete any database table.
13.8 Insert data into MySQL Table
Data can be entered into MySQL tables by executing SQL INSERT statement through PHP
function mysqli_query.
Here are some syntax rules to follow:
The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
EXAMPLE:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
54. 53
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
13.9 Retrieve Data from MySQL Table
Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP
function mysql_query. We have several options to fetch data from MySQL.
The most frequently used option is to use function mysql_fetch_array(). This function returns
row as an associative array, a numeric array, or both. This function returns FALSE if there are no
more rows.
Below is a simple example to fetch records from employee table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
55. 54
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfullyn";
mysql_close($conn);
?>
PHP provides another function called mysql_fetch_assoc() which also returns the row as an
associative array. With an associative array we can access the field by using their name instead of
using the index.
13.10 Update data in MySQL table
Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP
function mysqli_query.
To update a record in any table it is required to locate that record by using a conditional clause.
The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
56. 55
EXAMPLE:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
13.11 Delete data from MySQL table
Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP
function mysqli_query.
To delete a record in any table it is required to locate that record by using a conditional clause.
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value
58. 57
PHP – AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating
better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java
Script. Conventional web application transmit information to and from the sever using
synchronous requests. This means we fill out a form, hit submit, and get directed to a new page
with new information from the server. With AJAX when submit is pressed, JavaScript will make
a request to the server, interpret the results and update the current screen. In the purest sense, the
user would never know that anything was even transmitted to the server.
AJAX is based on internet standards, and uses a combination of:
XMLHttpRequest object (to exchange data asynchronously with a server)
JavaScript/DOM (to display/interact with the information)
CSS (to style the data)
XML (often used as the format for transferring data)
AJAX is a web browser technology independent of web server software. A user can continue to
use the application while the client program requests information from the server in the
background. Clicking is not required, mouse movement is a sufficient event trigger.
59. 58
14.1 Getting data from database
AJAX can be used for interactive communication with a database.
Table 12:AJAX Table
id FirstName LastName Age Hometown Job
1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot
Figure 41: AJAX Select
In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed. The function is triggered by the onchange event.
HTML CODE:
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
61. 60
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint
and exit the function. If a person is selected, do the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
PHP CODE:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
62. 61
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
When the query is sent from the JavaScript to the PHP file, the following happens:
1. PHP opens a connection to a MySQL server
2. The correct person is found
3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder
63. 62
Conclusion
It is open source scripting language so we can free download this and use. PHP is a server site
scripting language. It is open source scripting language. It is widely used all over the world. It is
faster than other scripting language. PHP is case sensitive scripting language at time of variable
declaration. In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are NOT case-sensitive PHP is a great tool for writing dynamic web pages. PHP
is not restricted to use by professional Web developers. Nor do we have to be an IT administration
professional. Just like any scripting language, PHP can seem complicated at first glance. But if we
persevere, we'll see that this is an interesting and accessible technology. It's also a good way of
gaining an understanding of the server-side world.
Few things we must remember:
i. PHP is a server-side technology, and does not work in a browser.
ii. The filename must have .php extension.
iii. PHP enhanced pages can contain a mixture of HTML and PHP code.
iv. PHP code must be enclosed in a <? php ……….. ?> tag.
64. 63
REFERENCES
1. Robin Nixon’s “Learning PHP, MySQL, JavaScript, CSS & HTML5”, Third Edition,
13/06/2014.
2. Luke Welling & Laura Thomson’s “PHP and MySQL Web Development”, Fifth
Edition, 27/09/2016.
3. Thomas Powell’s “Ajax: The Complete Reference”, First Edition, 13/03/2008.
4. https://www.w3schools.com/php/default.asp
5. https://www.tutorialspoint.com/php/index.htm