Web Development Using PHP
Web Development Using PHP
Using PHP
Sahil Showkat
SHOUKATSAHIL@GMAIL.COM
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.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
1
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)
2
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.
3
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.
4
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.
<?php
?>
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";
5
?>
</body>
</html>
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.
<html>
<body>
<?php
//This is a single line comment
?>
</body>
</html>
<html>
<body>
<?php
/*
This is a multiline
Comment block
*/
?>
</body>
</html>
6
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.
OUTPUT
<?php
$txt="Hello World!";
echo $txt;
Hello World!
echo “<h5>Using ECHO</h5>”;
Using 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.
<?php
$txt1 = "Learn PHP";
$txt2 = "IUST";
OUTPUT
$x = 5;
Learn PHP
$y = 4;
Study PHP at IUST
print "<h2>" . $txt1 . "</h2>";
9
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
7
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.
8
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.
$var_name = value;
<?php
$txt="Hello World!";
$x=16;
?>
<?php
$x = 5;
$y = 10;
OUTPUT
function myTest() {
global $x, $y;
$y = $x + $y;
15
}
myTest();
echo $y
?>
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.
OUTPUT
<?php
$x = 5;
$y = 10; 15
10
function myTest() {
$GLOBALS['y'] = $GLOBALS['x']
+ $GLOBALS['y'];
}
myTest();
echo $y;
?>
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
OUTPUT
function myTest() {
static $x = 0;
0
echo $x;
1
$x++;
2
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called. 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
11
PHP Strings & Constants
<?php
OUTPUT
$txt="Hello World";
echo $txt;
Hello World
?>
<?php OUTPUT
$txt1="Hello World!";
$txt2="What a nice day!"; Hello World! What a nice day!
echo $txt1 . " " . $txt2;
?>
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.
12
<?php
OUTPUT
echo strlen("Hello world!");
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).
OUTPUT
<?php
echo strpos("Hello world!","world"); 6
?>
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).
SYNTAX
htmlentities(string,flags,character-set,double_encode)
html_entity_decode(string,flags,character-set)
13
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>
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()
Related functions:
14
OUTPUT
<?php
echo lcfirst("Hello world!");
hello world!
?>
Figure 18:lcfirst()
charlist specifies which characters to remove from the string. If omitted, all of the following
characters are removed:
"\0" - NULL
"\t" - tab
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
OUTPUT
$str = "Hello World!";
echo $str . "<br>";
Hello World!
echo trim($str,"Hed!");
llo Worl
?>
<?php OUTPUT
// Positive numbers:
echo substr("Hello world",0,10)."<br>"; Hello worl
echo substr("Hello world",1,8)."<br>"; ello wor
echo substr("Hello world",-10,-2)."<br>"; ello wor
echo substr("Hello world",0,-6)."<br>"; Hello
?>
OUTPUT
<?php
echo str_repeat(".",13);
.............
?>
16
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 OUTPUT
echo str_replace("world","Peter","Hello world!");
?> Hello Peter!
<?php OUTPUT
echo strchr("Hello world!","world");
?> world!
<?php
OUTPUT
echo strcmp("Hello","Hello");
echo "<br>";
0
echo strcmp("Hello","hELLo");
-1
?>
17
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
<?php
OUTPUT
define("GREETING", "Welcome to
W3Schools.com!", true);
Welcome to W3Schools.com!
echo greeting;
Welcome to W3Schools.com!
echo GREETING
?>
18
PHP Operators
19
Table 3: PHP Comparison Operators
20
Table 7:PHP Array Operators
21
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.
SYNTAX:
function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}
function setHeight($minheight = 50) { OUTPUT
echo "The height is : $minheight <br>";
}
Hello world!
function sum($x, $y) {
$z = $x + $y; The height is : 50
return $z; The height is : 80
}
writeMsg(); 6
setHeight();
setHeight(80);
echo sum(2,4);
?>
Figure 26: User Defined Function
22
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();
<?php
$cars = array("Volvo", "BMW", "Toyota");
/* $cars[0] = "Volvo";
OUTPUT
$cars[1] = "BMW";
$cars[2] = "Toyota"; */
I like Volvo, BMW and Toyota.
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
23
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);
24
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
<?php
$marks = array(
"mohammad" => array (
"physics" => 35, OUTPUT
"maths" => 30,
"chemistry" => 39 Marks for mohammad in physics : 35
Marks for qadir in maths : 32
),
Marks for zara in chemistry : 39
25
"chemistry" => 29
),
OUTPUT
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
Array
(
?> [a] => apple
[b] => banana
26
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars); OUTPUT
27
Table 8: PHP Array Functions
Function Description
array() Creates an array
array_chunk() Splits an array into chunks of arrays
Creates an array by using the elements from one "keys" array and one
array_combine()
"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
28
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
<?php
$x = 75;
$y = 25;
addition();
echo $z;
?>
Figure 33: $GLOBALS use
29
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.
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
30
$_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
31
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.
32
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;
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.
33
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.
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.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old."; OUTPUT after submitting the form
exit();
}
?> Welcome Sahil
<html>
You are 21 years old
<body>
</body>
</html>
35
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.
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.
36
PHP Files & I/O
Modes Description
Open a file for read only. File pointer starts at the beginning of the
r
file
Open a file for write only. Erases the contents of the file or
w creates a new file if it doesn't exist. File pointer starts at the
beginning of the file
Open a file for write only. The existing data in file is preserved.
a File pointer starts at the end of the file. Creates a new file if the file
doesn't exist
Creates a new file for write only. Returns FALSE and an error if
x
file already exists
Open a file for read/write. File pointer starts at the beginning of
r+
the file
Open a file for read/write. Erases the contents of the file or
w+ creates a new file if it doesn't exist. File pointer starts at the
beginning of the file
Open a file for read/write. The existing data in file is preserved.
a+ File pointer starts at the end of the file. Creates a new file if the file
doesn't exist
Creates a new file for read/write. Returns FALSE and an error if
x+
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.
37
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.
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" ); OUTPUT
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
38
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" );
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
fclose( $file );
39
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.
<?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.";
}
40
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>
</body>
</html>
OUTPUT
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.
41
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
42
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
43
PHP Cookies & Sessions
44
<?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>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
45
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.";
?>
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.
46
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.
<?php
session_start();
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
47
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();
48
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.
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
49
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.
<?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);
?>
50
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 );
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
if(! $conn ) {
if(! $retval ) {
mysql_close($conn);
?>
51
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.
The INSERT INTO statement is used to add new records to a MySQL table:
EXAMPLE:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
52
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
if(! $conn ) {
53
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';
mysql_select_db('test_db');
if(! $retval ) {
while($row = mysql_fetch_array($retval)) {
"--------------------------------<br>";
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.
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
54
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());
}
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
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());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
56
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 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.
57
14.1 Getting data from database
AJAX can be used for interactive communication with a database.
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
58
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.re
sponseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
59
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));
}
60
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
61
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.
62
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
63
64