Web Application Development: Dr. Babasaheb Ambedkar Open University Ahmedabad
Web Application Development: Dr. Babasaheb Ambedkar Open University Ahmedabad
Web Application Development: Dr. Babasaheb Ambedkar Open University Ahmedabad
PGDCA 202
BLOCK 2:
OO AND FILE HANDLING
IN PHP
Author
Mr. Sanjay Thapar
Language Editor
Mr. K. J. Sharma
Acknowledgment
Every attempt has been made to trace the copyright holders of material reproduced
in this book. Should an infringement have occurred, we apologize for the same and
will be pleased to make necessary correction/amendment in future edition of this
book.
The content is developed by taking reference of online and print publications that
are mentioned in Bibliography. The content developed represents the breadth of
research excellence in this multidisciplinary academic field. Some of the
information, illustrations and examples are taken "as is" and as available in the
references mentioned in Bibliography for academic purpose and better
understanding by learner.'
ROLE OF SELF INSTRUCTIONAL MATERIAL IN DISTANCE LEARNING
UNIT 1
Object Oriented PHP 03
UNIT 2
File and Directory Handling 36
BLOCK 3: OO AND FILE HANDLING IN
PHP
Block Introduction
Object-Oriented Programming is a type of programming which can be
modular and reusable web applications. It is a methodology which frames an
application that could be any sort of web based or windows based. In OOP, all
will be around objects and class.
In this block, we will detail about the basic of Object-Oriented
Programming and its modelling techniques. The block will focus on declaration of
variables, functions, structures, unions, or enumerations with study about their
syntax. The concept of structured data type and class in PHP are also explained.
In this block, the student will make to learn and understand about the basic
of Comma Separated Values with their usability and necessity in programming the
script. The concept related to directory support functions and knowledge related to
read and operate directories and entries will also be explained to students. The
student will be demonstrated practically about storing tabular data in plain text
format.
Block Objective
After learning this block, you will be able to understand:
2
UNIT 1: OBJECT ORIENTED PHP
Unit Structure
1.0 Learning Objectives
1.1 Introduction
1.2 The benefits of OOP
1.19 Glossary
1.20 Assignment
1.21 Activities
1.22 Case Study
3
OO and file 1.0 Learning Objectives
handling in PHP
After learning this unit, you will be able to understand:
∑ About OOP
1.1 Introduction
Object-Oriented Programming is a type of programming which can be
modular and reusable web applications. In PHP, OOP will help the code to remain
flexible by defining at many places. It is the latest way of software development
where all languages such as Java, PERL, PHP, C#, Ruby use in programming.
a. web based
b. windows based
c. both a and b
d. neither a nor b
4
1.3 Key OOP Concepts Object
Oriented
In terms of programming, object-oriented is hard concept having difficult PHP
syntax and roadblocks. Object-oriented programming serves as unique coding
style which allows developers to assemble similar work into classes. The concept
related to OOP is DRY programming which describes a piece of information
when changes in a program, normally required so as to update the programming
code. OOP shows threatening to developers since it introduces new syntax and
appears to be complex as simple procedural or inline code.
d. none of above
<?php
class MyPlant
{
public $prop1 = "Rose is my Plant!";
}
$obj = new MyPlant;
var_dump($obj);
?>
5
OO and file
In this code, keyword public will describe visibility of property, while
handling in PHP property is named by standard variable syntax with certain value. If you have to
read such property and give it to browser, then you need to reference the object
from place where you read and read as:
echo $obj->prop1;
class MyPlant
{ public $prop1 = "My Plant is Rose!";
}
$obj = new MyPlant;
Output:
My Plant is Rose!
a. exist()
b. exist_class()
c. class_exist()
d. __exist()
b. public
c. protected
d. $this
6
1.5 Constructors and Destructors Methods Object
Oriented
To start with an object, it is advisable to set few things. To handle this, PHP PHP
gives with magic method __construct() that is automatic when an object is
created. To have an idea of constructors, you have to add constructor to MyClass
which will output message when new instance of class is created:
8
Object
Oriented
PHP
?>
Output:
End of file
The class "MyClass" was destroyed.
"When the end of a file is reached, PHP automatically releases all resources."
To explicitly trigger the destructor, you can destroy the object using the function
unset():
9
OO and file
handling in PHP
}
}
Output:
10
Object
Oriented
PHP
c. i) and iii)
d. ii), iii) and iv)
b. _construct()
c. function _construct()
d. function __construct()
class MyClass
11
OO and file
{
handling in PHP
12
Object
Oriented
PHP
a. class object
b. object class
c. object instance
d. class instantiation
d. const G = ‘9.18’;
13
OO and file
handling in PHP
It is noted that regular property cannot be applied by static way, and if so,
will result in fatal error. It is noted that inside a class you can access static
property by self keyword. If you are accessing parent class property then, apply
parent keyword as shown:
It is found that static variable or property is the good means to save value of
variable in the context of various instances.
14
Object
Check your progress 6 Oriented
1. Regular property in static way will lead to: PHP
a. data error
b. runtime error
c. fatal error
d. all of above
{
public $var1 = 'value 5';
function iterateVisible() {
echo "MyClass::iterateVisible:\n";
}
}
}
$class = new MyClass();
15
OO and file
foreach($class as $key => $value) {
handling in PHP print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
On running above program:
var1 => value 5
MyClass::iterateVisible:
var1 => value 5
In the output, each iterated properties get accessed where iterator interface gets
worked out.
16
Object
Check your progress 7
Oriented
1. The output of the program will be: PHP
<?php
$colors = array("white","safron","magenta","brown");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
a)white
safron
magenta
a. brown
b. white
c. brown
d. error
17
OO and file
After cloning is over and once clone() method is defined, then newly created
handling in PHP object's __clone() method gets called which allow required properties for change.
18
Object
Oriented
PHP
Cloned Object:
19
OO and file
handling in PHP
c. both a and b
d. neither a nor b
Consider an example:
class Person
20
end Object
Oriented
end
PHP
bob= Person.new("Sanjay Mathur", 45)
p bob
Outputs:
a. alphabets
b. numbers
c. characters
d. all of these
In the above code we see that child class makes use of non-private methods
and a property which tends to inherit from parent class which allows writing code
once in parent and can be applied in parent and child classes.
Consider an example:
//The parent class
21
OO and file
class Vehicle {
handling in PHP // Private property inside the class
private $model;
{
$this -> model = $model;
}
}
//The child class inherits the code from the parent class
}
//Create an instance from the child class
//Use another method that the child class inherited from the parent class
echo $sportsVehicle1 -> hello();
Output:
horn! I am Maruti
22
Object
Check your progress 10
Oriented
1. Which class from which child class inherits? PHP
i) Child class
b. (ii)
c. (iii)
It is a class or its members having access modifier that are used publicly
from anywhere from outside scope of class. It is used where data is available for
all public.
Private
The class members with this gets access inside class itself which saves members
from outside class access with reference of class instance.
Protected
It is similar as private, since it allows sub classes to access protected super class
members.
Abstract
23
OO and file
It is applied only for PHP classes and its functions having abstract functions
handling in PHP with abstract class.
Final
It saves sub classes which override super class members having final
keyword.
}
}
}
}
?>
24
public function NameDisplay1(){ Object
Oriented
echo "Accessing inside the Parent Class: ".$this->Name; PHP
}
}
class Display extends Computer{
}
$obj = new Computer;
echo $obj->NameDisplay1();
$obj = new Display;
echo $obj->NameDisplay2();
?>
{
private int empid;
{
Accounts acc = new Accounts();
return acc.calculateBonus();
}
}
*
25
OO and file class Accounts
handling in PHP {
public double calculateBonus(){//method's code}
}
a. Aggregation
b. Simple Association
c. Dependency
d. Composition
Output:
Fatal error:
It is noted that an abstract class is partially implemented, so it is fine for it to
contain normal methods:
26
Object
Oriented
PHP
In abstract class, you can declare method as abstract that is not implemented but
any non-abstract subclass implements it. The body of abstract method:
It is noticed that an abstract class need not require having any abstract methods.
Also if the class is not declared as abstract, it has no abstract method as shown:
<?php
class MyClass {
/*
Output:
If we run the above program, we see that it will generate fatal error:
27
OO and file 1.14 Create final classes and methods
handling in PHP
Final Class
A final class is a class that cannot be extended and can be declared by
prefixing ‘class’ keyword along with ‘final’.
Example:
We see that BaseClass here is declared as final and will not inherit. In this,
DerivedClass tries to extend from BaseClass and compiler compile an error.
Final Method
It is a method that cannot be overruled. In order to declare method as final,
you need to prefix function name with ‘final’ keyword as shown in example:
28
Object
Oriented
PHP
b. cannot be overruled
c. given fatal error
d. none of above
interface iTemplate
{
It is seen that when a class implements interface, it should explain all methods or
functions of interface else php engine will result in error.
*/
c. both a and b
d. neither a nor b
<?php
namespace Handle;
// app/models/another.php
class add
{
30
} Object
Oriented
In this, add class with small change shows namespace directive. The line
PHP
namespace Handle will tell PHP about Handle namespace. It says if classes
created in such file will be there in ‘Handle’ namespace. So using Handle class
once again.
<?php
// app/routes.php
$add = new add();
Example:
This\Namespace\And\Class\Combination\Is\Silly\But\Works
namespace app\a{
class one{
}
}
}
namespace app\b{
class one{
public static function _2(){
}
}
namespace app{
echo a\one::_1();
echo b\one::_2();
31
OO and file
echo a\two::_1();
handling in PHP }
namespace app\a{
class two{
public static function _1(){
}
prints
a one _1
b one _2
a two _1
a. similar names
b. no similar names
Answers: (1-c)
Answers: (1-c)
Answers: (1-c)
Answers: (1-a)
33
OO and file Check your progress 8
handling in PHP
Answers: (1-a)
Answers: (1-d)
Answers: (1-d)
Answers: (1-c)
Answers: (1-b)
Answers: (1-b)
Answers: (1-c)
Answers: (1 –b)
1.19 Glossary
1. Public - It is a property or method which can be worked upon from anywhere
on the script.
2. Private - It is a method which cannot be accessed from everywhere since used
by class or object.
3. Protected - It is a property which can be used by code in class which is part
of.
4. Abstract - It is a property that subclasses and not applied directly.
34
1.20 Assignment Object
Oriented
What is Object-oriented programming? PHP
1.21 Activities
What are Namespace in PHP?
35
OO and file UNIT 2: FILE AND DIRECTORY HANDLING
handling in PHP
Unit Structure
2.0 Learning Objectives
2.1 Introduction
2.2 Get a directory listing
2.11 Assignment
2.12 Activities
2.1 Introduction
PHP carries full set of directory support functions which describes different
functions that will read and operate directories and entries in it. With other
36
directory or file parts, it performs similar functions as with other languages and File and
can do similar work with more simplified versions. directory
handling
∑ Able to upload zip files and can able to extract them directly having an
option to delete zip file once extracted.
∑ Will able to hide certain file types, names or extensions and directories.
37
OO and file
handling in PHP
);
}
}
$d->close();
return $retval;
}
38
?> File and
directory
You can use this function as follows:
handling
File and
directory
?> handling
Example:
39
OO and file
handling in PHP
$myFile = "sampleFile.txt";
$fh = fopen($project, 'r');
echo $projectContents;
To do this, you need to initially set the file with file name which could be
anything as $project which can be set to "sampleFile.txt" as shown. Using link
with $myFileLink variable, set file name and set instruction for the file. Now see
for line with carrying contents of file with variable $projectContents. Now
applying fread function, and pass variable link as first parameter followed by
40
number of characters which you want to read. You see that PHP will read the files File and
in the same way as you read. directory
handling
Just like reading the file, PHP will able to write. With filesize function
having file size that shows number of characters present in the file. Using this in
fread function will tell PHP to read till the end of the file.
In PHP, writing to file is not hard as compared to reading of file. For this,
consider an example shown:
$project2 = "testFolder/sampleFile2.txt";
fwrite($projectLink2, $newContents);
fclose($projectLink2);
41
OO and file
closed using fclose() function. The fclose() function needs file pointer as its
handling in PHP argument which returns true when closure succeeds or false if it fails.
Reading a file
Once a file is opened using fopen() function it can be read with a function
called fread() that makes use of two arguments. These arguments should be file
pointer having file length in bytes. It is noted that files length be found using
filesize() function that takes file name as argument and returns file size expressed
in bytes. Consider the steps shown in reading of file in PHP:
Consider an example that contains text file to a variable which shows required text
on web page.
<html>
<head>
exit();
42
?> File and
</body> directory
handling
</html>
Writing a file
In order to write text in existing file with PHP fwrite() function, it is seen
that this function uses two arguments that specifies file pointer and string of data
which is to be written. You can also include third integer argument to specify
length of data to write. The impact of third argument is that, it will stop writing
after reaching to particular length. Consider an example showing text insertion in
file by writing short text heading inside it. After closing this file its existence is
confirmed using file_exist() function which takes file name as an argument
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
43
OO and file
handling in PHP
</body>
</html>
a. one
b. two
c. three
d. four
b. strings
c. file pointer
d. none of above
44
2.5 Read and write CSV data File and
directory
CSV data in PHP is Comma Separated Values that are file that stores tabular handling
data in plain text form with sequence of characters having no data that has to be
interpreted as binary numbers. It carries any number of records, with line breaks
having fields, separated by character or string with literal comma or tab. In this,
the records have identical sequence of fields. The structure of CSV file:
one, two
example1, example2
data1, data2
test1, test2
You can read from a CSV file using php function "fgetcsv" which reads content of
csv file as shown:
<?php
45
OO and file
handling in PHP
}
?>
Example
<?php
$list = array (
array('"dd"', '"mm"')
);
fputcsv($fp, $fields);
}
fclose($fp);
?>
46
Check your progress 4 File and
directory
1. In PHP, fputcsv fuinction helps: handling
a. To read CSV
d. None of above
<?php
47
OO and file
echo 'An error occurred during copying the file';
handling in PHP PHP renaming a file
You can rename a file using rename() function which makes you to move a
file from one directory to different directories. Consider the program where
renaming of test.txt file to test.bak file exists with code:
}else{
We see that rename() function will return true when file gets successfully
renamed, else returns false. In the following program, it describes how to apply
rename() function so as to move test.bak to backup directory:
<?php
48
} File and
directory
handling
<?php
$fn = './backup/test.bak';
if(unlink($fn)){
}else{
echo sprintf("An error occurred deleting the file %s",$fn);
}
<?php
$fn = './backup/test.bak';
if(unlink($fn)){
echo sprintf("The file %s deleted successfully",$fn);
}else{
echo sprintf("An error occurred deleting the file %s",$fn);
}
We see that copy(), rename() and unlink() functions raise warning-level
errors if the file cannot be found therefore it is good practice to check the file
exists using the file_exists() function before copying, renaming or deleting it.
49
OO and file
handling in PHP
Check your progress 5
1. The unlink() functions is used in:
a. read of file
b. writing of file
c. deleting of file
d. none of above
∑ On opening HTML form having text files along with browse button and
submit button.
∑ User on clicking browse button and choosing uploading of file from local
PC.
∑ Complete path along with selected file will appear in text filed which the
user will click on submit button.
∑ The PHP script specified as form handler in form's action will check for
arriving of file which further copies file in intended directory.
∑ The PHP script further will make sure about success to user.
50
File and
directory
handling
$target_dir = "uploads/": This will specify directory about the place of file
$target_file: It shows path of file which to be uploaded
a. upload.php
b. upl.php
c. uploa.php
d. upload.php/
51
OO and file 2.8 Let Us Sum Up
handling in PHP
In this unit we have learnt that PHP carries full set of directory support
functions which describes different functions that will read and operate directories
and entries in it. In PHP, fopen() function is used to open a file. It requires two
arguments stating first the file name and then mode in which to operate. After
making a changes to the opened file it is important to close it with the fclose()
function.
CSV data in PHP is Comma Separated Values that are file that stores tabular
data in plain text form with sequence of characters having no data that has to be
interpreted as binary numbers.
Answers: (1-b)
Answers: (1-d)
Answers: (1-b)
Answers: (1-c)
Answers: (1-a)
52
2.10 Glossary File and
directory
1. Class - HTML elements can have one or more classes, separated by spaces. handling
You can style elements using CSS by selecting them with their classes.
2. Usage - Almost all content belongs inside the body tag. The main exceptions
are script and style tags, as well as the page title tag.
3. Div - A block level container for content with no semantic meaning.
2.11 Assignment
Explain the CSV data in PHP.
2.12 Activities
Write a program stated the application of PHP fopen() function.
53
OO and file Block Summary
handling in PHP
In this block, you will understand about the basic of Use the protected
access modifier with knowledge about creating abstract classes and methods. The
block gives an idea on creating final classes and methods along with concept of
Interface of class are well detailed. The examples related to concept of
Namespaces are also discussed.
In this block, you will understand about the basic of Copy, rename and
deleting file along with its techniques. The concept related to reading and writing
complete or part of file in PHP is well detailed. The student will be demonstrated
practically about Comma Separated Values.
54
Block Assignment
Short Answer Questions
1. What is directory listing in PHp?
2. What is object's __clone() method?
55
OO and file Enrolment No.
handling in PHP
1. How many hours did you need for studying the units?
Unit No 1 2 3 4
Nos of Hrs
2. Please give your reactions to the following items based on your reading of the
block:
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
56
Education is something
which ought to be
brought within
the reach of every one.
- Dr. B. R. Ambedkar