0% found this document useful (0 votes)
42 views

Chapter 5 Server Side Scripting (PHP)

The document discusses the basics of PHP including its history, features, syntax, variables, and strings. PHP is a server-side scripting language used to build dynamic websites and web applications. It is open-source, integrated with HTML, and can connect to databases. PHP code is embedded within HTML and executed on the server before the results are returned to the browser. Variables, comments, and strings are core elements of PHP syntax.

Uploaded by

Mohammad Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Chapter 5 Server Side Scripting (PHP)

The document discusses the basics of PHP including its history, features, syntax, variables, and strings. PHP is a server-side scripting language used to build dynamic websites and web applications. It is open-source, integrated with HTML, and can connect to databases. PHP code is embedded within HTML and executed on the server before the results are returned to the browser. Variables, comments, and strings are core elements of PHP syntax.

Uploaded by

Mohammad Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 5

Basics of Hypertext Preprocessor (PHP)

1. Introduction to PHP?

PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home
Page. It is a general-purpose programming language used to design a website or web application.
It is the server-side scripting language embedded with HTML to develop Static website, Dynamic
website, or Web applications. It was created by Rasmus Lerdorf in 1994. The syntax of PHP is
similar to C, C++, and Java. It manages the dynamic content, database, session, cookies, etc of a
dynamic website.

The websites like www.facebook.com, www.yahoo.com are also built on PHP. It can be easily
embedded with HTML files and HTML codes can also be written in a PHP file. The thing that
differentiates PHP and HTML is, PHP codes are executed on the server whereas HTML codes are
directly rendered on the browser. PHP codes are first executed on the server and then the result is
returned to the browser. The only information that the client or browser knows is the result returned
after executing the PHP script on the server and not the actual PHP codes present in the PHP file.
Also, PHP files can support other client-side scripting languages like CSS and JavaScript. It is
integrated with a number of popular databases such as MySQL, Oracle, Microsoft SQL Server and
others.

2. Features of PHP

Php has the following features

 Open Source: It is an open-source programming language so it can download freely.


 Simplicity: Since PHP does not include libraries like C/C++ so its structure is simple. It
contains lots of pre-defined functions to secure your data. Execution of PHP starts from
(<?php) and end with closing escape sequence (?>).
 Efficiency: uses resource allocation mechanisms and object-oriented programming, in
addition to session management features. It eliminates unnecessary memory allocation.
 Security: Many encryption functions are supported by PHP to secure the data.

COMPILED BY JEMAL ZUBER (MSc) 1


 Flexibility: It is a very flexible language because it can be embedded with HTML, CSS,
JavaScript, XML, and many other languages. Also, the PHP code can be run on any
device like Phone, Tabs, and Laptops etc.
 Object-Oriented: The object-oriented programming features are added in PHP 4.0.
 PHP performs system functions:- it can create, open, read, write, and close files
 It can handle forms:- gather data from files and save data to a file
 It can add, delete, modify elements within your database
 Access cookies variables and set cookies
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data

Advantages of PHP

o It is supported by all Operating Systems like Windows, Linux, Unix, etc.


o It is integrated with other programming languages (HTML, CSS, JavaScript, etc) and
databased.
o It is easy to connect with the database to store and retrieve data from the database.
Multiple databases can also be integrated with PHP.
o It is the fastest programming language compared to other programming languages.
o PHP frameworks and tools are used to protect web applications from outer attacks and
security threats.

Disadvantages of PHP

o Since PHP is open-source so its code is visible to all programmers. If any bugs exist in
the source code then its weakness can be explored by other programmers.
o It is not suitable for large applications because its maintenance is difficult.
o The error handling of a PHP framework is not good.
3. Basic PHP syntax

Scripting in PHP

COMPILED BY JEMAL ZUBER (MSc) 2


PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The
most universally effective PHP tag style used to write PHP code is <?php...?> tag. All PHP code
must be included inside <?php...?> tag to be recognized by the PHP Parser.
Example
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
 PHP statements are expressions terminated by semicolons (;).

Example: - $Fname = "Semir Mohammed!";


print("$Fname ");

 Sequence of statements in PHP are enclosed by curly braces {}.

Example

if (CGPA = = 4) {
print("Excellent");
print("This result is your best effort<br>");
}

 PHP is whitespace insensitive: - it almost never matters how many whitespace characters,
tabs, and carriage returns you have in a row.
 PHP is case sensitive:- Example the php variables $gradepoint and $Gradepoint are
different variables

PHP comments

There are two commenting formats in PHP: - Single-line and Multi-line comment
Comment type syntax Example
<?php <?php

COMPILED BY JEMAL ZUBER (MSc) 3


Single line #...... # This is a sample php code
//…… // It print string output
?> echo"An example with single line comments";
?>
<?php <?php
/* …… /* This php code
Multi-line
……. Prints multi line
.…… string
*/ */
?> echo"An example with multi line comments";
?>
Variables
The main way to store information in the middle of a PHP program is by using a variable. PHP
variables has the following characteristics.

 All variables in PHP are denoted with a leading dollar sign ($).
 Variables are assigned with the = operator.
 Variables can, but do not need, to be declared before assignment
 Variables in PHP do not have intrinsic types
 Variables used before they are assigned have default values
 PHP automatically convert variable types from one to another when necessary

Variable types in php

Data type Description Example


Correspond to simple whole numbers, both $age = 25;
Integer positive and negative
Double Correspond to floating-point numbers $gradePoint = 3.75;
if (TRUE)
Boolean Have only two possible values either true or false print("Qualified<br>");

else

COMPILED BY JEMAL ZUBER (MSc) 4


print("Unqualified<br>");
NULL Special type that only has one value: NULL $var = NULL;
String Sequences of characters $Dept = "Computer Science";

Variable Scope
 PHP variables can be one of four scope types
 Local variables
 Function parameters
 Global variables
 Static variables
Variable Naming
 Variable names must begin with a letter or underscore character.
 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
Using strings in php

 Strings are sequences of characters


 Singly quoted strings are treated almost literally
 Doubly quoted strings replace variables with their values as well as specially
interpreting certain character sequences
 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their
values

Example
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";

COMPILED BY JEMAL ZUBER (MSc) 5


print($literally);
?>
 To concatenate two string variables together, use the dot (.) operator

Example
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
 The strlen() function is used to find the length of a string

Example
<?php
echo strlen("Internet Programing");
?>
 The strpos() function is used to search for a string or character within a string

Example
<?php
echo strpos("Internet Programing", "Programing");
?>
4. Retrieve data from html forms

Dynamic websites provide the functionalities that can use to store, update, retrieve, and delete the
data in a database. A form is a document that containing black fields, that the user can fill the data
or user can select the data and the data will store in the data base. There are two ways the browser
client can send information to the web server. These are the GET and the POST method.

 GET Method
 GET method sends the encoded user information appended to the page request.

COMPILED BY JEMAL ZUBER (MSc) 6


 The page and the encoded information are separated by the ? character. Like
http://www.test.com/index.htm?name1=value1&name2=value2
 It is restricted to send up to 1024 characters only
 Never use GET method if you have password or other sensitive information to be
sent to the server
 It can't be used to send binary data, like images or word documents, to the server
 PHP provides $_GET associative array to access all the sent information using GET
method

Example

<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
 POST Method
 The POST method transfers information via HTTP headers
 data sent by POST method goes through HTTP header so security depends on
HTTP protocol

COMPILED BY JEMAL ZUBER (MSc) 7


 By using Secure HTTP you can make sure that your information is secure
 It does not have any restriction on data size to be sent
 It can be used to send ASCII as well as binary data
 PHP provides $_POST associative array to access all the sent information using
POST method

Example
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['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>
5. Displaying errors

Error handling is the process of catching errors raised by your program and then taking
appropriate action.

COMPILED BY JEMAL ZUBER (MSc) 8


 Defining custom error handling function
o PHP provides you a framework to define error handling function
o This function must be able to handle a minimum of two parameters (error level
and error message)
o It can accept up to five parameters (optionally: file, line-number, and the error
context)
o The following table shows sample PHP error levels

Error level Description


E_ERROR Fatal run-time errors. Execution of the script is halted
E_WARNING Non-fatal run-time errors. Execution of the script is not
halted
E_PARSE Compile-time parse errors. Generated by the parser
E_CORE_ERROR Fatal errors that occur during PHP's initial start-up

o The above error level can be set using following PHP built-in library function

int error_reporting ( [int $level] )

o Syntax for custom error handling function declaration

error_function(error_level,error_message, error_file,error_line,error_context);

o Once you define your custom error handler you need to set it using PHP built-in
library set_error_handler function

Example: - the following PHP code handle an error for function calling which does
not exist

<?php
error_reporting( E_ERROR );
function handleError($errno, $errstr,$error_file,$error_line) {
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";

COMPILED BY JEMAL ZUBER (MSc) 9


echo "Terminating PHP Script";
die();
}
//set error handler
set_error_handler("handleError");
//trigger error
myFunction();
?>
6. Control structures

PHP supports the two main control structures: conditional statements and repetition statements

I. Conditional statements

Conditional statements uses in a code to make a decisions. PHP supports following three
decision making statements.

Decision making Syntax Example


statement
if (condition) <?php
code to be executed if $d = date("D");
condition is true; if ($d = = "Fri")
if...else else echo "Have a nice weekend!";
code to be executed if else
condition is false; echo "Have a nice day!";
?>
if (condition) <?php
code to be executed; $d = date("D");
else if (condition) if ($d == "Fri")
else if statement code to be executed; echo "Have a nice weekend!";
else elseif ($d == "Sun")
code to be executed; echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
switch (expression){ <?php
case label1: $grade="E";
code to be executed switch ($d){
if expression = label1; case "A":

COMPILED BY JEMAL ZUBER (MSc) 10


switch statement break; echo "EXCELLENT";
break;
case label2: case "B":
code to be executed echo "VERY GOOD";
if expression = label2; break;
break; case "C":
default: echo "GOOD";
break;
code to be executed case "D":
if expression is echo "FAIR";
different break;
from both label1 and case "F":
label2; echo "FAIL";
} break;
default:
echo "INVALID GRADE?";
}
?>

II. Repetition (Loop) statements

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

Looping Syntax Example


statement
<?php
$a = 0;
for (initialization; $b = 0;
for loop condition; increment){ for( $i = 0; $i<5; $i++ ) {
code to be executed; $a += 10;
} $b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
<?php
$i = 0;
$num = 50;
while (condition) { while( $i < 10) {
while loop code to be executed; $num--;
} $i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>

COMPILED BY JEMAL ZUBER (MSc) 11


<?php
do { $i = 0;
code to be executed; $num = 0;
do...while }
while (condition); do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
<?php
foreach (array as value) $array = array( 1, 2, 3, 4, 5);
{
foreach code to be executed; foreach( $array as $value ) {
} echo "Value is $value <br />";
}
?>

7. Arrays

An array is a data structure that stores one or more similar type of values in a single value. In PHP,
there are three different kind of arrays and each array value is accessed using an array index.

Array type Description Example


Store numbers, strings and any <?php
object $numbers = array( 1, 2, 3, 4, 5);
Their index will be represented by foreach( $numbers as $value ) {
Numeric array
numbers echo "Value is $value <br />";
Array index starts from zero ?}

An array with strings as index. It stores element values in association with key
values rather than in a strict linear index order. Consider the following example

Associative array <?php


$salaries = array("Muktar" => 2000, "Selam" => 1000, "Adem" => 500);
echo "Salary of Muktar is ". $salaries['Muktar'] . "<br />";
echo "Salary of Selam is ". $salaries['Selam']. "<br />";

COMPILED BY JEMAL ZUBER (MSc) 12


echo "Salary of Adem is ". $salaries['Adem']. "<br />";
?>
An array containing one or more arrays and values are accessed using multiple
indices. Consider the following example
<?php
$marks = array(
"mohammad" => array (
"ProgrammingI" => 35,
Multidimensional "Compiler" => 30,
array "OOP" => 39
),
"qadir" => array (
" ProgrammingI " => 30,
" Compiler " => 32,
" OOP " => 29
),
);
echo "Marks for mohammad in programming I : " ;
echo $marks['mohammad'][' ProgrammingI'] . "<br />";
echo "Marks for qadir in Compiler: ";
echo $marks['qadir'][' Compiler '] . "<br />";
?>

8. Functions
PHP function is a piece of code which takes one or more input in the form of parameter and does
some processing and returns a value. PHP has more than 1000 built-in functions like fopen(),
fread(), print() etc, but it gives you option to create your own functions as well.
 Creating PHP Function
o While creating a function in PHP, the function name should start with keyword
function
o All the PHP code should be put inside { and } braces

Example

<?php
function writeMessage() {
echo "Welcome To Werabe University, We Are Glad For Your Coming!";

COMPILED BY JEMAL ZUBER (MSc) 13


}
writeMessage();
?>
 PHP Functions with Parameters
o Parameters work like variables inside a function
o Php gives an option to create a function with parameters inside a function

Example

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
 Passing Arguments by Reference
o It is possible to pass arguments to functions by reference by adding an ampersand
(&) to the variable name in either the function call or the function definition

Example

<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );

COMPILED BY JEMAL ZUBER (MSc) 14


echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
 PHP Functions returning value
o A function can return a value using the return statement in conjunction with a value.
o Return stops the execution of the function and sends the value back to the calling
code

Example

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
9. Form Processing using PHP

HTML forms are used to send the user information to the server and returns the result back to the
browser. For example, if you want to get the details of visitors to your website, and send them
good thoughts, you can collect the user information by means of form processing. Then, the
information can be validated either at the client-side or on the server-side. The final result is sent
to the client through the respective web browser. To create a HTML form, form tag should be
used.

Attributes of form Tag

Attribute Description
It specifies the name of the form and is used to identify individual
name or id
forms.

COMPILED BY JEMAL ZUBER (MSc) 15


It specifies the location to which the form data has to be sent when the
action
form is submitted.
It specifies the HTTP method that is to be used when the form is
submitted. The possible values are get and post. If get method is used,
method
the form data are visible to the users in the url. Default HTTP method
is get.
It specifies the encryption type for the form data when the form is
encType
submitted.
It implies the server not to verify the form data when the form is
novalidate
submitted.

Controls used in forms

Attribute Description
Textbox allows the user to provide single-line input, which can be
Textbox
used for getting values such as names, search menu and etc.
Textarea allows the user to provide multi-line input, which can be
Textarea
used for getting values such as an address, message etc.
Dropdown or combobox allows the user to provide select a value from
DropDown
a list of values.
Radio buttons allow the user to select only one option from the given
Radio Buttons
set of options.
Checkbox allows the user to select multiple options from the set of
CheckBox
given options.
Buttons Buttons are the clickable controls that can be used to submit the form

Creating a simple HTML Form

All the form controls given above is designed by using the input tag based on the type attribute of
the tag. In the below script, when the form is submitted, no event handling mechanism is done.
Event handling refers to the process done while the form is submitted. These event handling

COMPILED BY JEMAL ZUBER (MSc) 16


mechanisms can be done by using javaScript or PHP. However, JavaScript provides only client-
side validation. Hence, we can use PHP for form processing.

<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<form id="form1" method="post">
FirstName:
<input type="text" name="firstname" required/>
<br>
<br>
LastName
<input type="text" name="lastname" required/>
<br>
<br>
Address
<input type="text" name="address" required/>
<br>
<br>
Email Address:
<input type="email" name="emailaddress" required/>
<br>
<br>
Password:
<input type="password" name="password" required/>
<br>
<br>
<input type="submit" value="Submit”/>

COMPILED BY JEMAL ZUBER (MSc) 17


</form>
</body>
</html>
Form Validation
Form validation is done to ensure that the user has provided the relevant information. Basic
validation can be done using HTML elements. For example, in the above script, the email address
text box is having a type value as “email”, which prevents the user from entering the incorrect
value for an email. Every form field in the above script is followed by a required attribute, which
will intimate the user not to leave any field empty before submitting the form. PHP methods and
arrays used in form processing are described in the following table.

PHP form processing Functions Description


This function is used to determine whether the variable
isset()
or a form control is having a value or not.
It is used to retrieve the information from the form control
$_GET[] through the parameters sent in the URL. It takes the
attribute given in the url as the parameter.
It is used to retrieve the information from the form control
$_POST[] through the HTTP POST method. It takes name attribute
of corresponding form control as the parameter.
It is used to retrieve an information while using a
$_REQUEST[]
database.

Form Processing using PHP

Above HTML script is rewritten using the above mentioned functions and array. The rewritten
script validates all the form fields and if there are no errors, it displays the received information in
a tabular form.

Example

COMPILED BY JEMAL ZUBER (MSc) 18


<?php
if (isset($_POST['submit']))
{
if ((!isset($_POST['firstname']))
||(!isset($_POST['lastname'])) ||
(!isset($_POST['address'])) ||
(!isset($_POST['emailaddress'])) ||
(!isset($_POST['password'])) ||
(!isset($_POST['gender'])))
{
$error = "*" . "Please fill all the required
fields";
}
else
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$gender = $_POST['gender'];
}
}
?>
<html>

<head>
<title>Simple Form Processing</title>
</head>

<body>

COMPILED BY JEMAL ZUBER (MSc) 19


<h1>Form Processing using PHP</h1>
<fieldset>
<form id="form1" method="post" action="form.php">
<?php
if (isset($_POST['submit']))
{
if (isset($error))
{
echo "<p style='color:red;'>"
. $error . "</p>";
}
}
?>
FirstName:
<input type="text" name="firstname"/>
<span style="color:red;">*</span>
<br>
<br>
Last Name:
<input type="text" name="lastname"/>
<span style="color:red;">*</span>
<br>
<br>
Address:
<input type="text" name="address"/>
<span style="color:red;">*</span>
<br>
<br>
Email:

COMPILED BY JEMAL ZUBER (MSc) 20


<input type="email" name="emailaddress"/>
<span style="color:red;">*</span>
<br>
<br>
Password:
<input type="password" name="password"/>
<span style="color:red;">*</span>
<br>
<br>
Gender:
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
name="gender">Female
<br>
<br>
<input type="submit" value="Submit"
name="submit" />
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
{
if(!isset($error))
{
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<table border='1'>";
echo "<thead>";

COMPILED BY JEMAL ZUBER (MSc) 21


echo "<th>Parameter</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>".$firstname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name</td>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Email Address</td>";
echo "<td>" .$emailaddress."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
}

COMPILED BY JEMAL ZUBER (MSc) 22


}
?>
</body>
</html>
Note: When the PHP and HTML are coded in a single file, the file should be saved as PHP. In the
form, the value for the action parameter should be a file name.

10. PHP File Upload

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.

Information in the phpinfo.php page describes the temporary directory that is used for file uploads
as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as
upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps

o The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
o The user clicks the browse button and selects a file to upload from the local PC.
o The full path to the selected file appears in the text filed then the user clicks the submit
button.
o The selected file is sent to the temporary directory on the server.
o 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.
o 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.

Let’s make an HTML form for uploading the file to the server index.html.

COMPILED BY JEMAL ZUBER (MSc) 23


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>File Upload Form</title>

</head>

<body>

<form action="file-upload-manager.php" method="post" enctype="multipart/form-data">

<!--multipart/form-data ensures that form data is going to be encoded as MIME data-->

<h2>Upload File</h2>

<label for="fileSelect">Filename:</label>

<input type="file" name="photo" id="fileSelect">

<input type="submit" name="submit" value="Upload">

<!-- name of the input fields are going to be used in our php script-->

<p><strong>Note:</strong>Only .jpg, .jpeg, .png formats allowed to a max size of


2MB.</p>

</form>

</body>

</html>

Now, time to write a php script which is able to handle the file uploading system. file-upload-
manager.php

<?php

// Check if the form was submitted

COMPILED BY JEMAL ZUBER (MSc) 24


if($_SERVER["REQUEST_METHOD"] == "POST")

// Check if file was uploaded without errors

if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)

$allowed_ext = array("jpg" => "image/jpg",

"jpeg" => "image/jpeg",

"gif" => "image/gif",

"png" => "image/png");

$file_name = $_FILES["photo"]["name"];

$file_type = $_FILES["photo"]["type"];

$file_size = $_FILES["photo"]["size"];

// Verify file extension

$ext = pathinfo($filename, PATHINFO_EXTENSION);

if (!array_key_exists($ext, $allowed_ext))

die("Error: Please select a valid file format.");

// Verify file size - 2MB max

$maxsize = 2 * 1024 * 1024;

if ($file_size > $maxsize)

die("Error: File size is larger than the allowed limit.");

// Verify MYME type of the file

COMPILED BY JEMAL ZUBER (MSc) 25


if (in_array($file_type, $allowed_ext))

// Check whether file exists before uploading it

if (file_exists("upload/".$_FILES["photo"]["name"]))

echo $_FILES["photo"]["name"]." is already exists.";

else

move_uploaded_file($_FILES["photo"]["tmp_name"],

"uploads/".$_FILES["photo"]["name"]);

echo "Your file was uploaded successfully.";

else

echo "Error: Please try again.";

else

echo "Error: ". $_FILES["photo"]["error"];

COMPILED BY JEMAL ZUBER (MSc) 26


}

?>

In the above script, once we submit the form, later we can access the information via a PHP
superglobal associative array $_FILES. Apart from using the $_FILES array, many in-built
functions are playing a major role. After we are done with uploading a file, in the script we will
check the request method of the server, if it is POST then it will proceed otherwise the system will
throw an error. Later on, we have accessed the $_FILES array to get the file name, file size, and
type of the file. Once we got those pieces of information, then we validate the size and type of the
file. In the end, we search in the folder, where the file is to be uploaded, for checking if the file
already exists or not. If not, we have used move_uploaded_file() to move the file from temporary
location to the desired directory on the server and we are done.

11. PHP Cookies and Session

11.1 PHP Cookies

A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that the
site can retrieve to personalize the page when the user visits the website next time. A cookie can
only be read from the domain that it has been issued from. Cookies are usually set in an HTTP
header but JavaScript can also set a cookie directly on a browser.

Setting Cookie in PHP

To set a cookie in PHP, the setcookie() function is used. The setcookie() function needs to be
called prior to any output generated by the script otherwise the cookie will not be set.

Syntax

setcookie(name, value, expire, path, domain, security);

The setcookie() function requires six arguments in general which are described in the following
table.

Parameters Description

COMPILED BY JEMAL ZUBER (MSc) 27


Name It is used to set the name of the cookie.
Value It is used to set the value of the cookie.
It is used to set the expiry timestamp of the cookie after
Expire
which the cookie can not be accessed
It is used to specify the path on the server for which the
Path
cookie will be available.
It is used to specify the domain for which the cookie is
Domain
available.
It is used to indicate that the cookie should be sent only
Security
if a secure HTTPS connection exists.

Creating Cookies

The following example describes the creation of the cookie in PHP. The cookie is named
Auction_Item and assigning the value Luxury Car to it. The cookie will expire after 2 days(2 days
* 24 hours * 60 mins * 60 seconds).

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>

COMPILED BY JEMAL ZUBER (MSc) 28


</body>
</html>
Only the name argument in the setcookie() function is mandatory. To skip an argument, the
argument can be replaced by an empty string(“”).

Checking Whether a Cookie Is Set or Not

It is always advisable to check whether a cookie is set or not before accessing its value. Therefore
to check whether a cookie is set or not, the PHP isset() function is used. To check whether a cookie
“Auction_Item” is set or not, the isset() function is executed as follows:

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.

COMPILED BY JEMAL ZUBER (MSc) 29


</p>
</body>
</html>
Accessing Cookie Values

For accessing a cookie value, the PHP $_COOKIE super global variable is used. It is an associative
array that contains a record of all the cookies values sent by the browser in the current request. The
records are stored as a list where the cookie name is used as the key. To access a cookie named
“Auction_Item”, the following code can be executed.

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Deleting Cookies
The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie()
function is called by passing the cookie name and other arguments or empty strings but however
this time, the expiration date is required to be set in the past. To delete a cookie named
“Auction_Item”, the following code can be executed.

COMPILED BY JEMAL ZUBER (MSc) 30


<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted"
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end of the
session i.e. when the browser closes.

The same path, domain, and other arguments should be passed that were used to create the cookie
in order to ensure that the correct cookie is deleted.

Disadvantages of cookies

Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to easily
modify the content of the cookie. Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.

COMPILED BY JEMAL ZUBER (MSc) 31


Apart from that cookies affect the performance of a site since cookies send the user data each time
the user views a page. Every time the browser requests a URL to the server, all the cookie data for
that website is automatically sent to the server within the request.

12.2 PHP Sessions

When you work with an application, you open it, do some changes, and then you close it. This is
much like a session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address does not maintain state. Session variables solve
this problem by storing user information to be used across multiple pages (e.g. username, favorite
color, etc.). By default, session variables last until the user closes the browser.

A session is used to save information on the server momentarily so that it may be utilized across
various pages of the website. It is the overall amount of time spent on an activity. The user session
begins when the user logs in to a specific network application and ends when the user logs out of
the program or shuts down the machine.

Session values are far more secure since they are saved in binary or encrypted form and can only
be decoded at the server. When the user shuts down the machine or logs out of the program, the
session values are automatically deleted. We must save the values in the database to keep them
forever.

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.
Before using any session variable make sure you have setup this path.

When a session is started following things happen

o PHP first creates a unique identifier for that particular session which is a random string of
32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
o A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.

COMPILED BY JEMAL ZUBER (MSc) 32


o 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. 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.

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. Make use of isset() function to check if session
variable is already set or not.

<?php

session_start();

if( isset( $_SESSION['counter'] ) ) {

$_SESSION['counter'] += 1;

}else {

$_SESSION['counter'] = 1;

$msg = "You have visited this page ".


$_SESSION['counter'];

COMPILED BY JEMAL ZUBER (MSc) 33


$msg .= "in this session.";

?>

<html>

<head>

<title>Setting up a PHP session</title>

</head>

<body>

<?php echo ( $msg ); ?>

</body>

</html>

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 you want to destroy a single
session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable

<?php

unset($_SESSION['counter']);

?>

Here is the call which will destroy all the session variables

<?php

session_destroy();

?>

COMPILED BY JEMAL ZUBER (MSc) 34


Turning on Auto Session

You do not need to call start_session() function to start a session when a user visits your site
if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies

There may be a case when a user does not allow to store cookies on their machine. So there is
another method to send session ID to the browser. Alternatively, you can use the constant SID
which is defined if the session started. If the client did not send an appropriate session cookie,
it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you
can embed it unconditionally into URLs.The following example demonstrates how to register
a variable, and how to link correctly to another page using SID.

<?php

session_start();

if (isset($_SESSION['counter'])) {

$_SESSION['counter'] = 1;

}else {

$_SESSION['counter']++;

$msg = "You have visited this page ".


$_SESSION['counter'];

$msg .= "in this session.";

echo ( $msg );

?>

<p>

To continue click following link <br />

COMPILED BY JEMAL ZUBER (MSc) 35


<a href = "nextpage.php?<?php echo
htmlspecialchars(SID); ?>">

</p>

Accessing session data

Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing
the corresponding key to the $_SESSION associative array. The PHP code to access a session data
with two session variables Rollnumber and Name is shown below.

<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';

echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

?>

Important Points

 The session IDs are randomly generated by the PHP engine.


 The session data is stored on the server therefore it doesn’t have to be sent with every
browser request.
 The session_start() function needs to be called at the beginning of the page, before any
output is generated by the script in the browser.
12. Database Programming using PHP

Database is a collection of inter-related data which helps in efficient retrieval, insertion and
deletion of data from database and organizes the data in the form of tables, views, schemas, reports
etc. For Example, university database organizes the data about students, faculty, and admin staff
etc. which helps in efficient retrieval, insertion and deletion of data from it.

A database is a separate application that stores a collection of data. Each database has one or more
distinct APIs for creating, accessing, managing, searching and replicating the data it holds. Other

COMPILED BY JEMAL ZUBER (MSc) 36


kinds of data stores can also be used, such as files on the file system or large hash tables in memory
but data fetching and writing would not be so fast and easy with those type of systems.

Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different tables
and relations are established using primary keys or other keys known as Foreign Keys.

A Relational Database Management System (RDBMS) is a software that

 Enables you to implement a database with tables, columns and indexes.


 Guarantees the Referential Integrity between rows of various tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from various tables.

RDBMS Terminology

Before we proceed to explain the MySQL database system, let us revise a few definitions related
to the database.

o Database: - A database is a collection of tables, with related data.


o Table: - A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
o Column: - One column (data element) contains data of one and the same kind, for
example the column postcode.
o Row: - A row (= tuple, entry or record) is a group of related data, for example the data
of one subscription.
o Redundancy: - Storing data twice, redundantly to make the system faster.
o Primary Key: - A primary key is unique. A key value cannot occur twice in one table.
With a key, you can only find one row.
o Foreign Key: - A foreign key is the linking pin between two tables.
o Compound Key:- A compound key (composite key) is a key that consists of multiple
columns, because one column is not sufficiently unique
o Index: - An index in a database resembles an index at the back of a book

COMPILED BY JEMAL ZUBER (MSc) 37


o Referential Integrity: - Referential Integrity makes sure that a foreign key value always
points to an existing row.
12.1 Overview on MySQL database

MySQL is the most popular Open Source Relational SQL database management system. MySQL
is one of the best RDBMS being used for developing web-based software applications. It is the
most popular database system used with PHP. MySQL is developed, distributed, and supported
by Oracle Corporation.

o The data in a MySQL database are stored in tables which consists of columns and rows.
o MySQL is a database system that runs on a server.
o MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
o MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
o MySQL is very friendly to PHP, the most appreciated language for web development.
o MySQL is ideal for both small and large applications.
o MySQL is very fast, reliable, and easy to use database system. It uses standard SQL
o MySQL compiles on a number of platforms.
o MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
12.2 Creating Database Connection in PHP

PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This
function takes six parameters and returns a MySQL link identifier on success or FALSE on failure.

Syntax

$mysqli = new mysqli($host, $username, $passwd, $dbName, $port,


$socket);

Parameters Description

COMPILED BY JEMAL ZUBER (MSc) 38


The host name running the database server. If not
$host
specified, then the default value will be localhost: 3306.
The username accessing the database. If not specified,
$username then the default will be the name of the user that owns the
server process.
The password of the user accessing the database. If not
$passwd
specified, then the default will be an empty password.
$dbName Database name on which query is to be performed.
The port number to attempt to connect to the MySQL
$port
server.
$socket Socket or named pipe that should be used.

You can disconnect from the MySQL database anytime using another PHP function close().

Syntax

$mysqli->close();

Example-1

<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);

COMPILED BY JEMAL ZUBER (MSc) 39


exit();
}
printf('Connected successfully.<br />');
$mysqli->close();
?>
</body>
</html>
Example-2
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
12.3 Sending Query to MySQL Database using PHP and Processing Query
Result

Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create,
Read, Update and Delete) operations. Here we will discuss the Read part i.e. data fetching from
database.

Connecting to a Database: You have two options to connect with MySQL database

1. MySQLi Object-Oriented

COMPILED BY JEMAL ZUBER (MSc) 40


$conn = new mysqli($servername, $username,
$databasename)

2. MySQLi Procedural

$conn = mysqli_connect($servername, $username,


$password, $databasename);

Executing Queries

After connecting to the database we need to run queries to fetch data. In Read operations, we will
use only select queries to fetch data from the database.

MySQLi Object-Oriented

$conn->query($query);

MySQLi Procedural

mysqli_query($conn, $query)

Close Connection

After the fetching is performed, you should close the connection to the database using the close()
function.

$conn->close();

Example: Create the following sample database and create table in the database

CREATE TABLE `Student Details` (

`Roll_No` int(11) NOT NULL,

`Name` varchar(255) NOT NULL,

`City` varchar(255) NOT NULL,

`Age` int(11) NOT NULL,

PRIMARY KEY (`Roll_No`)

COMPILED BY JEMAL ZUBER (MSc) 41


);

MySQLi Object-Oriented approach: PHP Code for the above table

<?php

$servername = "localhost";

$username = "root";

$password = "";

$databasename = "StudentDataBase";

// CREATE CONNECTION

$conn = new mysqli($servername,

$username, $password, $databasename);

// GET CONNECTION ERRORS

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// SQL QUERY

$query = "SELECT * FROM `Student Details`;";

// FETCHING DATA FROM DATABASE

$result = $conn->query($query);

if ($result->num_rows > 0)

// OUTPUT DATA OF EACH ROW

while($row = $result->fetch_assoc())

COMPILED BY JEMAL ZUBER (MSc) 42


{

echo "Roll No: " .

$row["Roll_No"]. " - Name: " .

$row["Name"]. " | City: " .

$row["City"]. " | Age: " .

$row["Age"]. "<br>";

else {

echo "0 results";

$conn->close();

?>

MySQLi Procedural approach: PHP Code for the above table

<?php

$servername = "localhost";

$username = "root";

$password = "";

$databasename = " StudentDataBase ";

// CREATE CONNECTION

$conn = mysqli_connect($servername,

$username, $password, $databasename);

COMPILED BY JEMAL ZUBER (MSc) 43


// GET CONNECTION ERRORS

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

// SQL QUERY

$query = "SELECT Roll_No, Name FROM `Student Details`;";

// FETCHING DATA FROM DATABASE

$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {

// OUTPUT DATA OF EACH ROW

while($row = mysqli_fetch_assoc($result)) {

echo "Roll No: " . $row["Roll_No"]

. " - Name: " . $row["Name"]. "<br>";

} else {

echo "0 results";

$conn->close();

?>

13. PHP File Input-Output

File handling is needed for any application. For some tasks to be done file needs to be processed.
File handling in PHP is similar as file handling is done by using any programming language.

COMPILED BY JEMAL ZUBER (MSc) 44


PHP has many functions to work with normal files. Those functions are described in the
following table.

Functions Description
PHP fopen() function is used to open a file. First parameter of fopen() contains
name of the file which is to be opened and second parameter tells about mode in
which file needs to be opened.
Files can be opened in any of the following modes :
o “w” – Opens a file for write only. If file not exist then new file is created
and if file already exists then contents of file is erased.
o “r” – File is opened for read only.
o “a” – File is opened for write only. File pointer points to end of file.
Existing data in file is preserved.
o “w+” – Opens file for read and write. If file not exist then new file is
fopen()
created and if file already exists then contents of file is erased.
o “r+” – File is opened for read/write.
o “a+” – File is opened for write/read. File pointer points to end of file.
Existing data in file is preserved. If file is not there then new file is
created.
o “x” – New file is created for write only.
Example
<?php
$file = fopen(“demo.txt”,'w');
?>
After file is opened using fopen() the contents of data are read using fread(). It
takes two arguments. One is file pointer and another is file size in bytes.
Example
fread() <?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );

COMPILED BY JEMAL ZUBER (MSc) 45


$filedata = fread( $file, $size );
?>
New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to
written to file. It can contain optional third argument where length of text to
written is specified.
Example
fwrite()
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
File is closed using fclose() function. Its argument is file which needs to be
closed.
Example
<?php
fclose() $file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>

14. PHP Date and Time

Date and time are some of the most frequently used operations in PHP while executing SQL
queries or designing a website etc. PHP serves us with predefined functions for these tasks.
Some of the predefined functions in PHP for date and time are discussed below.

PHP date() Function

The PHP date() function converts timestamp to a more readable date and time format.

Syntax:

COMPILED BY JEMAL ZUBER (MSc) 46


date(format, timestamp)

Explanation

o The format parameter in the date() function specifies the format of returned date and
time.
o The timestamp is an optional parameter, if it is not included then the current date and
time will be used.

Example: The below program explains the usage of the date() function in PHP.

<?php

echo "Today's date is :";

$today = date("d/m/Y");

echo $today;

?>

Formatting options available in date() function

The format parameter of the date() function is a string that can contain multiple characters allowing
to generate the dates in various formats. Date-related formatting characters that are commonly
used in the format string:

o d: Represents day of the month; two digits with leading zeros (01 or 31).
o D: Represents day of the week in the text as an abbreviation (Mon to Sun).
o m: Represents month in numbers with leading zeros (01 or 12).
o M: Represents month in text, abbreviated (Jan to Dec).
o y: Represents year in two digits (08 or 14).
o Y: Represents year in four digits (2008 or 2014)

The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.

Example: The below example explains the usage of the date() function in PHP.

COMPILED BY JEMAL ZUBER (MSc) 47


<?php

echo "Today's date in various formats:" . "\n";

echo date("d/m/Y") . "\n";

echo date("d-m-Y") . "\n";

echo date("d.m.Y") . "\n";

echo date("d.M.Y/D");

?>

The following characters can be used along with the date() function to format the time string:

o h: Represents hour in 12-hour format with leading zeros (01 to 12).


o H: Represents hour in 24-hour format with leading zeros (00 to 23).
o i: Represents minutes with leading zeros (00 to 59).
o s: Represents seconds with leading zeros (00 to 59).
o a: Represents lowercase antemeridian and post meridian (am or pm).
o A: Represents uppercase antemeridian and post meridian (AM or PM)

Example: The below example explains the usage of the date() function in PHP.

<?php

echo date("h:i:s") . "\n";

echo date("M,d,Y h:i:s A") . "\n";

echo date("h:i a");

?>

PHP time() Function

The time() function is used to get the current time as a Unix timestamp (the number of seconds
since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).

The following characters can be used to format the time string:

COMPILED BY JEMAL ZUBER (MSc) 48


o h: Represents hour in 12-hour format with leading zeros (01 to 12).
o H: Represents hour in 24-hour format with leading zeros (00 to 23).
o i: Represents minutes with leading zeros (00 to 59).
o s: Represents seconds with leading zeros (00 to 59).
o a: Represents lowercase antemeridian and post meridian (am or pm).
o A: Represents uppercase antemeridian and post meridian (AM or PM).

Example: The below example explains the usage of the time() function in PHP.

<?php

$timestamp = time(); 1512486297

echo($timestamp); December 05, 2017 03:04:57 PM

echo "\n";

echo(date("F d, Y h:i:s A", $timestamp));

?>

PHP mktime() Function

The mktime() function is used to create the timestamp for a specific date and time. If no date and
time are provided, the timestamp for the current date and time is returned.

Syntax:

mktime(hour, minute, second, month, day, year)

Example: The below example explains the usage of the mktime() function in PHP.

<?php

echo mktime(23, 21, 50, 11, 25, 2017);

?>

The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs.

COMPILED BY JEMAL ZUBER (MSc) 49


15. PHP OOP
Object Oriented Programming is a very important concept for programmers to solve real-life
problems. In this section explain the concept of object-oriented programming and its features.
Object
Everything in this world is surrounded with objects. Table, chair, monitor, cellphone everything is
an object. There are two things in an object to remember to solve real-life problems. One is
attribute and the other one is behavior. If we talk about monitor so…model number, screen size all
these are attributes. On the other hand, the features like volume up or volume down are behavior
for the monitor. In programming, variables are attributes and functions are behavior.
Example
<?php
// Class definition
class TV {
// Member variables
public $model = 'xyz';
public $volume = 1;
// Member Functions
function volumeUp() {
Output
$this->volume++; 2
}
function volumeDown() {
$this->volume--;
}
}
// Create new object
$tv_one = new TV;
// Calling member function
$tv_one->volumeUp();
echo $tv_one->volume;?>
Constructor function

COMPILED BY JEMAL ZUBER (MSc) 50


Constructor function is a special function for which do not need to call the function like earlier we
were doing after creating an object.
Example
<?php
// Class definition
class TV {
// Member variables
public $model;
public $volume;
// Member Functions
function volumeUp() {
$this->volume++;
} Output
function volumeDown() {
xyz
$this->volume--;
}
function __construct($m, $v) {
$this->model = $m;
$this->volume= $v;
}
}
// Create new object
$tv = new TV('xyz', 2);
echo $tv->model;
?>

Inheritance
In a simple word, inheritance means inheriting the properties or functionalities from one class to
another class. Model and volume will find in all kinds of television but suppose you need to add
additional feature timer. The timer cannot be included in all the television. So it will use inheritance
for that television which includes timer property. Use ‘extends’ keyword to implement inheritance.

COMPILED BY JEMAL ZUBER (MSc) 51


Example:
<?php
// Class definition
class TV {
// Member variables
public $model;
public $volume;
// Member Functions
function volumeUp() {
$this->volume++;
}
function volumeDown() {
$this->volume--;
} Output
function __construct($m, $v) {
$this->model = $m; xyz
$this->volume= $v;
}
}
class TvWithTimer extends TV {
public $timer = true;
}
// Create new object
$tv = new TvWithTimer('xyz', 2);
echo $tv->model;
?>
Encapsulation
Encapsulation is all about wrapping the data and method in a single unit. Object-Oriented
programming sets the access level for member functions or variables. It means from where it needs
to be accessed. There are three kinds of access levels or access specifies.

 Public: Public functions or variables can only be accessed from anywhere. In all the above
examples, we are able to access the public functions and variables outside the class and
everyone can call it.
 Private: Private functions or variables can only be accessed by the class who created it.

Example
<?php
// Class definition
class TV {

COMPILED BY JEMAL ZUBER (MSc) 52


// Member variables
private $model;
public $volume;
// Member Functions
function volumeUp() {
$this->volume++;
}
Output
function volumeDown() { Cannot access private
property TV::$model in
$this->volume--; /home/65af96133e297a6da
} 6c1ad3d75c9ff46.php:28

function __construct($m, $v) {


$this->model = $m;
$this->volume= $v;
}
}
// Create new object
$tv = new TV('xyz', 2);
echo $tv->model;
?>
Protected

Protected functions or variables can only be used by the class who created and it’s child class
means all the classes which inherit the property of parent class having protected method or
variable.

Example:

<?php
// Class definition
class TV {
// Member variables

COMPILED BY JEMAL ZUBER (MSc) 53


protected $model;
public $volume;
// Member Functions
function volumeUp() {
$this->volume++;
Output
}
xyz
function volumeDown() {
$this->volume--;
}
function getModel() {
return $this->model;
}
function __construct($m, $v) {
$this->model = $m;
$this->volume= $v;
}
}
class plazma extends TV {
function getModel() {
return $this->model;
}
}
// Create new object
$tv = new plazma('xyz', 1);
echo $tv->getModel();?>
Abstract Classes

Like the keyword is saying, Abstract means not completed. Abstract classes are those classes
where functions are declared but not implemented.

Example

COMPILED BY JEMAL ZUBER (MSc) 54


<?php

// Abstract class

abstract class ABC {

public abstract function xyz();

class def extends ABC {

public function xyz() {

echo "Welcome to Computer Science";

}
Output
// Create new object
Welcome to Computer Science
$obj = new def;

echo $obj->xyz();

?>

Interfaces

There is a limitation for inheritance in PHP that is you cannot extend multiple classes. Through
Interface you can achieve multiple inheritance property. Interfaces also worked like abstract
classes. The ‘implements’ keyword is used for interfaces. There is a difference between abstract
class and interface class. In abstract class define variables but in the interface, the class cannot
define variables. It can also not create constructor function in interfaces. It cannot declare a private
or protected function.

Example

<?php
interface a {

COMPILED BY JEMAL ZUBER (MSc) 55


public function abc();
}
interface b {
public function xyz();
}
class c implements a, b {
public function abc() {
echo 'Werabe University';
}
public function xyz() {
echo 'computer science Department';
}
}
// Create an object
Output
$obj = new c;
Werabe University
$obj->abc();
Computer science Department
$obj->xyz();
?>
Static Members
Static variables or static functions are directly related with class. It can access static variables or
functions directly with the class names. Use the ‘static’ keyword to declare a static function or
static variable.
Example
<?php
// Class definition
class abc {
public static $data = 'Computer Science Portal ';
public static function xyz() {
echo "A computer science portal";
}

COMPILED BY JEMAL ZUBER (MSc) 56


}
Output
echo abc::$data;
Computer science portal
abc::xyz();
?>
Example: The following example count how many objects we have created for a class.
<?php
class abc {
public static $objectCount = 0;
public static function getCount() {
return self::$objectCount;
}
public function __construct() {
self::$objectCount++;
}
}
$a = new abc();
Output
$b = new abc();
4
$c = new abc();
$d = new abc();
echo abc::getCount();
?>
Polymorphism

Polymorphism means many types or many forms. It means suppose you have created an interface
also classes that will implement this interface class. These classes will have different functionality
and they all will share this common interface.

Create an interface with LoggerInterface name in LoggerInterface.php file.

<?php
interface LoggerInterface {

COMPILED BY JEMAL ZUBER (MSc) 57


public function log($message);
}
?>
Now creating a file EmailLogger.php which will implement this interface.

<?php
class EmailLogger implements LoggerInterface {
public function log($message) {
echo "Logging message to email: $message";
}
}
?>
Create another file FileLogger.php and implement the interface class.

<?php

class FileLogger implements LoggerInterface {

public function log($message) {

echo "Logging message to file: $message";

?>

Another file is DBLogger.php

<?php

class DBLogger implements LoggerInterface {

public function log($message) {

echo "logging message to DB: $message";

COMPILED BY JEMAL ZUBER (MSc) 58


}?>

Now, create a UserProfile.php file where call all these files by only defining interface name using
type hinting. Do not need to define the class name for calling each and every class created in a file.

<?php

class UserProfile {

private $logger;

public function createUser() {

echo "creating user";

$this->logger->log("User Created");

public function updateUser() {

echo "updating user";

$this->logger->log("User Updated");

public function deleteUser() {

echo "deleting user";

$this->logger->log("Deleting User");

public function __construct(LoggerInterface


$logger)

$this->logger = $logger;

COMPILED BY JEMAL ZUBER (MSc) 59


}?>

Now, create a file index.php

<?php
function __autoload($class) {
// classes is a directory where all
// the above files are placed.
include_once "classes/$class.php";
}
function getLogger($type) {
switch($type) {
case 'email':
return new EmailLogger();
break;
case 'database':
return new DBLogger();
break;
case 'file':
return new FileLogger();
break;
}
}
$logger = getLogger('database');
$profile = new UserProfile($logger);
$profile->createUser(); ?>

COMPILED BY JEMAL ZUBER (MSc) 60

You might also like