Web Application Development: Dr. Babasaheb Ambedkar Open University Ahmedabad

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

WEB APPLICATION DEVELOPMENT

PGDCA 202

BLOCK 2:
OO AND FILE HANDLING
IN PHP

Dr. Babasaheb Ambedkar Open University


Ahmedabad
WEB APPLICATION DEVELOPMENT

Knowledge Management and


Research Organization
Pune
Editorial Panel

Author
Mr. Sanjay Thapar

Language Editor
Mr. K. J. Sharma

Graphic and Creative Panel


Ms. K. Jamdal
Ms. Lata Dawange
Mr. Prashant Tikone

Copyright © 2015 Knowledge Management and Research Organization.


All rights reserved. No part of this book may be reproduced, transmitted or utilized
in any form or by a means, electronic or mechanical, including photocopying,
recording or by any information storage or retrieval system without written
permission from us.

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

The need to plan effective instruction is imperative for a successful


distance teaching repertoire. This is due to the fact that the instructional
designer, the tutor, the author (s) and the student are often separated by
distance and may never meet in person. This is an increasingly common
scenario in distance education instruction. As much as possible, teaching by
distance should stimulate the student's intellectual involvement and
contain all the necessary learning instructional activities that are capable of
guiding the student through the course objectives. Therefore, the course /
self-instructional material are completely equipped with everything that
the syllabus prescribes.
To ensure effective instruction, a number of instructional design
ideas are used and these help students to acquire knowledge, intellectual
skills, motor skills and necessary attitudinal changes. In this respect,
students' assessment and course evaluation are incorporated in the text.
The nature of instructional activities used in distance education self-
instructional materials depends on the domain of learning that they
reinforce in the text, that is, the cognitive, psychomotor and affective. These
are further interpreted in the acquisition of knowledge, intellectual skills
and motor skills. Students may be encouraged to gain, apply and
communicate (orally or in writing) the knowledge acquired. Intellectual-
skills objectives may be met by designing instructions that make use of
students' prior knowledge and experiences in the discourse as the
foundation on which newly acquired knowledge is built.
The provision of exercises in the form of assignments, projects and
tutorial feedback is necessary. Instructional activities that teach motor skills
need to be graphically demonstrated and the correct practices provided
during tutorials. Instructional activities for inculcating change in attitude
and behavior should create interest and demonstrate need and benefits
gained by adopting the required change. Information on the adoption and
procedures for practice of new attitudes may then be introduced.
Teaching and learning at a distance eliminates interactive
communication cues, such as pauses, intonation and gestures, associated
with the face-to-face method of teaching. This is particularly so with the
exclusive use of print media. Instructional activities built into the
instructional repertoire provide this missing interaction between the
student and the teacher. Therefore, the use of instructional activities to
affect better distance teaching is not optional, but mandatory.
Our team of successful writers and authors has tried to reduce this.
Divide and to bring this Self Instructional Material as the best teaching
and communication tool. Instructional activities are varied in order to assess
the different facets of the domains of learning.
Distance education teaching repertoire involves extensive use of self-
instructional materials, be they print or otherwise. These materials are
designed to achieve certain pre-determined learning outcomes, namely goals
and objectives that are contained in an instructional plan. Since the teaching
process is affected over a distance, there is need to ensure that students actively
participate in their learning by performing specific tasks that help them to
understand the relevant concepts. Therefore, a set of exercises is built into the
teaching repertoire in order to link what students and tutors do in the
framework of the course outline. These could be in the form of students'
assignments, a research project or a science practical exercise. Examples of
instructional activities in distance education are too numerous to list.
Instructional activities, when used in this context, help to motivate students,
guide and measure students' performance (continuous assessment)
PREFACE
We have put in lots of hard work to make this book as user-friendly
as possible, but we have not sacrificed quality. Experts were involved in
preparing the materials. However, concepts are explained in easy language
for you. We have included may tables and examples for easy understanding.
We sincerely hope this book will help you in every way you expect.
All the best for your studies from our team!
WEB APPLICATION DEVELOPMENT
Contents

BLOCK 1: INTRODUCTION TO PHP

UNIT 1 INTRODUCTION TO WEB APPLICATION


The architecture of a web application, static and dynamic web
application, Installing WAMP.
UNIT 2 PHP BASICS
Embedding PHP Code in Your Web Pages, Commenting Your Code,
Outputting Data to the Browser, PHP's Supported Data types,
Identifiers, Variables, Constants, Expressions, String Interpolation,
Control Structures.

BLOCK 2: ARRAY, FUNCTION AND EXPRESSION

UNIT 1 ARRAY IN PHP


Array introduction, creating an array, adding and removing array
element, determining array size and uniqueness sorting array,
UNIT 2 FUNCTION IN PHP
In built functions: String functions, array functions, mathematical
functions, File System functions, Date and Time Functions,
Miscellaneous Functions, User Defined Functions, arguments
passing by reference , Argument passing by value
UNIT 3 FUNCTION IN PHP
Regular Expression, Error Handling Regular Expressions, Exception
handling
BLOCK 3: OO AND FILE HANDLING IN PHP

UNIT 1 OBJECT ORIENTED PHP


The benefits of OOP, Key OOP Concepts, Create and Use class,
properties, Constructors and Destructors, Methods, Create and Use
Object, class constant, static properties and method, loop through an
object’s properties, clone and compare objects, inspect an object,
inherit a class, use the protected access modifier, create abstract
classes and methods, create final classes and methods, work with
interfaces, Introducing Namespaces
UNIT 2 FILE AND DIRECTORY HANDLING
Get a directory listing, read and write an entire file, read and write
part of a file, read and write CSV data, copy, rename and delete a file,
file uploading

BLOCK 4: DATABASE AND STATE MANAGEMENT IN PHP

UNIT 1 PHP AND MYSQL DATABASE


Three ways to use PHP to work with MySQL (PDO, mysqli extension,
MySQL extension), database connection, select data, insert, update
and delete data in PHP using MySQL
UNIT 2 STATE MANAGEMENT IN PHP
Session, Cookies
Dr. Babasaheb PGDCA 202
Ambedkar
Open University

Web Application Development


BLOCK 3: OO AND FILE HANDLING IN PHP

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:

∑ The basic of OOP Concepts.

∑ Features about Creating and Using class properties.

∑ Basic about Constructors and Destructors Methods.

∑ Features regarding Cloning and comparing objects.

∑ Idea about Class Inherit.

∑ Understanding about Namespaces.

∑ Idea about Read/Write entire/part of file.

∑ Features of read and write CSV data.

∑ Basic of Copy, rename and delete file.

∑ Idea about File uploading in PHP.


1
OO and file Block Structure
handling in PHP
Unit 1: Object Oriented PHP

Unit 2: File and Directory Handling

2
UNIT 1: OBJECT ORIENTED PHP
Unit Structure
1.0 Learning Objectives

1.1 Introduction
1.2 The benefits of OOP

1.3 Key OOP Concepts


1.4 Create and Use class, properties

1.5 Constructors and Destructors Methods


1.6 Create and Use Object, class constant

1.7 Static properties and method


1.8 Loop through an object’s properties

1.9 Clone and compare objects


1.10 Inspect an object

1.11 Inherit a class

1.12 Use the protected access modifier

1.13 Create abstract classes and methods


1.14 Create final classes and methods

1.15 Work with interfaces


1.16 Introducing Namespaces

1.17 Let Us Sum Up


1.18 Answers for Check Your Progress

1.19 Glossary
1.20 Assignment

1.21 Activities
1.22 Case Study

1.23 Further Readings

3
OO and file 1.0 Learning Objectives
handling in PHP
After learning this unit, you will be able to understand:

∑ About OOP

∑ About Constructors and Destructors Methods

∑ About Creating and Using Object class constant

∑ About Inspecting an object

∑ About protected access modifier

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.

1.2 The benefits of OOP


Object oriented programming methodology frames an application which
could be any type as web based or windows based applications. In OOP, all will
be around objects and class. Use of OOP in PHP will form modular web
application and can do activity in object model structure. It carries many benefits.
OOP invokes usage of classes in order to arrange data and structure of an
application. It is noted that large programmers avoids the use of OOP as
programming theory. It is noted that objects in programming is similar to real
word object where all programming object carries properties and behaviours.

Check your progress 1


1. Object oriented programming methodology is:

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.

Check your progress 2


1. OOP is:
a. comfortable for users

b. simple for user


c. threatening for user

d. none of above

1.4 Create and Use class properties


While defining a class in PHP, you can add properties in it. It is hard to
imagine that to create native class having regular non-typed public PHP
properties. To add data to class, properties or class-specific variables are used
which works just like regular variables. In order to add property to MyPlant, write
the code as:

<?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;

As multiple instances of class exist, when individual object is not


referenced. In such case, the script is unable to find object which will read. You
can alter the script in test.php so as to read the property instead of dumping whole
class by simply changing the code as shown:
<?php

class MyPlant
{ public $prop1 = "My Plant is Rose!";

}
$obj = new MyPlant;

echo $obj->prop1; // Output the property


?>

Output:
My Plant is Rose!

Check your progress 3


1. Which functions shows existence of class?

a. exist()
b. exist_class()

c. class_exist()
d. __exist()

2. ______keyword describes properties or methods in class itself?


a. 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:

In this, we see that __CLASS__ returns the name of class in which it is


called which is magic constant. On reloading file in browser, we have the
following result:
7
OO and file
The class "MyClass" was initiated!
handling in PHP I'm a class property!
End of file.

To call a function when object is damaged, the __destruct() magic method is


available which is good for class cleanup. The message will be outputted when
object gets destroyed by explaining magic method as:

8
Object
Oriented
PHP

?>

Output:

The class "MyClass" was initiated!


I'm a class property!

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

}
}

// Create a new object


$obj = new MyClass;

Output:

10
Object
Oriented
PHP

Check your progress 4


1. Which statements is true about Constructors?
i PHP has class constructors.

ii Constructors accept parameters.


iii Constructors call class methods.

iv Constructors call other constructors.


a. ii) and iii)
b. All of above

c. i) and iii)
d. ii), iii) and iv)

2. PHP identifies constructors by:


a. classname()

b. _construct()
c. function _construct()

d. function __construct()

1.6 Create and Use Object class constant


You can define constant values on per-class basis keeping it same and
unchangeable. Constants differ from normal variables where no use of $ symbol is
there in order to declare.

Example #1 Defining and using a constant


<?php

class MyClass

11
OO and file
{
handling in PHP

Example #2 Static data example

Example #3 Constant expression example

12
Object
Oriented
PHP

Check your progress 5


1. Creation of objects based on predefined classes is:

a. class object
b. object class

c. object instance

d. class instantiation

2. Identify correct way to define constant?


a. constant G = “9.18”;
b. const $G = “9.18”;
c. constant G = ‘9.18’;

d. const G = ‘9.18’;

1.7 Static properties and method


In PHP, static methods and properties is an important feature which is
directly accessible without creating object of class. Static properties of class are
directly available from class using scope resolution operator. Also, you can make
property static using static keyword as shown in static variable in php class:

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

1.8 Loop through an object’s properties


PHP provides a way for objects to be defined so it is possible to iterate
through a list of items, with, for example a for each statement. By default, all
visible properties will be used for the iteration.

Example Simple Object Iteration


<?php
class MyClass

{
public $var1 = 'value 5';

public $var2 = 'value 6';


public $var3 = 'value 7';

protected $protected = 'protected var';


private $private = 'private var';

function iterateVisible() {
echo "MyClass::iterateVisible:\n";

foreach ($this as $key => $value) {


print "$key => $value\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

var2 => value 6


var3 => value 7

MyClass::iterateVisible:
var1 => value 5

var2 => value 6


var3 => value 7

protected => protected var

private => private var

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

1.9 Clone and compare objects


Having a copy of object carrying replicated properties is not always
required. In a copy constructor an object having GTK window will holds the
resource of GTK window once duplicate or new window carrying similar
properties exists. An object copy is created by using the clone keyword (which
calls the object's __clone() method if possible). An object's __clone() method
cannot be called directly.

$copy_of_object = clone $object;


Once the object is cloned, PHP will do shallow copy of object's properties which
are referenced to other variables as tcremain references. Its syntax is:
void __clone ( void )

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.

Example Cloning an object

18
Object
Oriented
PHP

The above example will output:


Original Object:

Cloned Object:

19
OO and file
handling in PHP

Check your progress 8


1. By cloning:

a. object itself gets cloned


b. object is cloned with its associations

c. both a and b
d. neither a nor b

1.10 Inspect an object


Inspecting object in good panel or a panel which locates through optional
argument panel Name. Its syntax is inspect(object[, panelName]).

Consider an example:
class Person

attr_accessor :name, :age


def initialize(name, age)

@name, @age = name, age

20
end Object
Oriented
end
PHP
bob= Person.new("Sanjay Mathur", 45)

p bob
Outputs:

#<Person:0x1a58d8 @age=45, @name="Sanjay Mathur">

Check your progress 9


1.The syntax of object inspection involves:

a. alphabets
b. numbers

c. characters
d. all of these

1.11 Inherit a class


Class inheritance is little complicated as inheritance serves as a connection
between a child and its parent. To declare one class inherits code from other class,
in such case we have to apply keyword.

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;

//Public setter method


public function setModel($model)

{
$this -> model = $model;
}

public function hello()


{

return "horn! I am a <i>" . $this -> model . "</i><br />";


}

}
//The child class inherits the code from the parent class

class SportsVehicle extends Vehicle {

//No code in the child class

}
//Create an instance from the child class

$sportsVehicle1 = new SportsVehicle();


// Set the value of the class’ property.

// For this aim, we use a method that we created in the parent


$sportsVehicle1 -> setModel('Maruti');

//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

ii) Parent class


iii) Super class

iv) Base class


a. (i)

b. (ii)
c. (iii)

d. (ii) and (iv)

1.12 Use the protected access modifier


In PHP, access modifiers are applied to give access rights to PHP classes
and their members which define functions and variables in the class.

PHP Access Control Modifiers


Following are the PHP keywords used as access modifiers:
Public:

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.

Example: Private & Public Access Modifier in PHP


<? class Computer {
private $Model = "HP 1150";

private $HardDrive = 800;


private $Ram = 34;

public function Specification(){


return $this->Model;

}
}

class User extends Computer{

public $UserName = "Sanjay";

public $UserExperince = "Engineering";


public function UserInformation(){

echo $this->UserName." has a ";


echo $this->Specification();

}
}

$obj = new User;


echo $obj->UserInformation();

?>

Example: Protected Access Modifier in PHP


<?
class Computer {

protected $Name = "Wipro Satellite Pro";

24
public function NameDisplay1(){ Object
Oriented
echo "Accessing inside the Parent Class: ".$this->Name; PHP
}

}
class Display extends Computer{

public function NameDisplay2(){


echo "<br>Accessing inside the child Class: ".$this->Name;
}

}
$obj = new Computer;

echo $obj->NameDisplay1();
$obj = new Display;

echo $obj->NameDisplay2();
?>

Check your progress 11


1. What will be the class relationship shown in the program?
class Employee

{
private int empid;

private String ename;


public double getBonus()

{
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

1.13 Create abstract classes and methods


Abstract class is such class which is not completely implemented that
mostly applied as base class for other classes in order to take from complete
implementation. It is better in interface as it allows adding common elements of
implementation which can be shared by subclasses not simply specifying the
interface of subclasses. Normally, we look at creation of abstract class with
abstract keyword:
<?php

abstract class MyAbstractClass {}


Abstract class contains no body, so it is less importance since it fails to define
interface for subclasses so as to inherit and serves as legal class.

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 {

public abstract function doSomething();


}

/*

Output:
If we run the above program, we see that it will generate fatal error:

Check your progress 12


1. Abstract class:

a. should contain abstract method


b. need not contain abstract method

c. may or may not contain abstract method


d. all of above

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

In the above example, DerivedClass extends from BaseClass.

Check your progress 13


1. BaseClass has myMethod() declared as final which can be:
a. can be ouveruled

b. cannot be overruled
c. given fatal error

d. none of above

1.15 Work with interfaces


Interfaces are abstract classes which has no guts and cannot be worked out
as they are designed in OOP allowing qualities in classes. Interface classes are
defined by using the keyword interface. All the methods in the interface must be
public as this is the nature of an interface.
// Declare the interface 'iTemplate'

interface iTemplate
{

public function setVariable($name, $var);


public function getHtml($template);

Example of class using interface:


class dog implements sound{
29
OO and file
function sound() {
handling in PHP echo “sa, re, ga, ma …”;
}

/* the interface methods/functions implements in class */


function sound() { echo “piano has sound …”;}

function playing() { echo “guitar is playing …”;}


}
/*

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.

*/

Check your progress 14


1. The abstract class carries:
a. empty concrete method

b. working concrete method

c. both a and b

d. neither a nor b

1.16 Introducing Namespaces


In PHP, there are namespacing which is added to language. There are no
two classes having similar name. They are different as if you are using another
party library having user as class named, in such case you fail to have your own
class. With this, PHP uses namespaces so as to get out of such issue. Consider the
simple program describing Simple Namespacing.

<?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

Example to use namespace


<?php

namespace app\a{
class one{

public static function _1(){


echo 'a one _1<br>';

}
}

}
namespace app\b{

class one{
public static function _2(){

echo 'b one _2<br>';


}

}
}

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(){

echo 'a two _1<br>';


}
}

}
prints

a one _1
b one _2

a two _1

Check your progress 15


1. In PHP two classes will have:

a. similar names
b. no similar names

c. both clsses will have single alphabet


d. none of above

1.17 Let Us Sum Up


In this unit we have learnt that Object-Oriented Programming is a type of
programming which can be modular and reusable web applications. Object
oriented programming methodology frames an application which could be any
type as web based or windows based applications. In OOP, all will be around
objects and class.
Object-oriented programming serves as unique coding style which allows
developers to assemble similar work into classes. While defining a class in PHP,
32
you can add properties in it. It is hard to imagine that to create native class having Object
regular non-typed public PHP properties. Oriented
PHP
In PHP, static methods and properties is an important feature which is
directly accessible without creating object of class. PHP provides a way for
objects to be defined so it is possible to iterate through a list of items, with, for
example for each statement. An object copy is created by using the clone keyword
(which calls the object's __clone() method if possible). An object's __clone()
method cannot be called directly.

1.18 Answers for Check Your Progress

Check your progress 1

Answers: (1-c)

Check your progress 2

Answers: (1-c)

Check your progress 3

Answers: (1-c), (2-d)

Check your progress 4

Answers: (1-b), (2-d)

Check your progress 5

Answers: (1-d), (2-d)

Check your progress 6

Answers: (1-c)

Check your progress 7

Answers: (1-a)

33
OO and file Check your progress 8
handling in PHP
Answers: (1-a)

Check your progress 9

Answers: (1-d)

Check your progress 10

Answers: (1-d)

Check your progress 11

Answers: (1-c)

Check your progress 12

Answers: (1-b)

Check your progress 13

Answers: (1-b)

Check your progress 14

Answers: (1-c)

Check your progress 15

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?

1.22 Case Study


How to create Abstract Class in PHP?

1.23 Further Readings


1. "PHP: Basic syntax", PHI, Robin Smith. 2008-02-22

2. "Using PHP from command line", PHI, Dixit, 2009-09-11

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.3 Read and write an entire file


2.4 Read and write part of file

2.5 Read and write CSV data


2.6 Copy, rename and delete file

2.7 File uploading


2.8 Let Us Sum Up

2.9 Answers for Check Your Progress


2.10 Glossary

2.11 Assignment

2.12 Activities

2.13 Case Study


2.14 Further Readings

2.0 Learning Objectives


After learning this unit, you will be able to understand:

∑ About directory listing.

∑ About Read and write file.

∑ About Read and write part of file.

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

2.2 Get a directory listing


The directory listing in PHP is in shape of Directory Listing Script which
can be configured easily and allows a programmer to simply in uploading of files
on web directories that turns into formatted, mobile friendly directory browser. It
is seen that with the ease of version 4, there appears new features in PHP
directories which are:

∑ Support to mobile browser.

∑ Uploading of many files with certain restrictions on allowed file-types.

∑ Gives access to restricted access to script with the application of password


or IP Address.

∑ Supports formation of new directories and sub-directories.

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

∑ Ability to sort file listings by name, size or last modified date.

Single Directory Listing


In order to start with single directory listing, consider a simple function
which will return list of files, directories and properties from single directory:

37
OO and file
handling in PHP

"name" => "$dir$entry/",

);

}
}

$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

Check your progress 1


1. In PHP, the directory feature will not:

a. support mobile browser


b. have restrictions on uploading file types

c. give access to restricted access

d. supports formation of new directories

2.3 Read and write an entire file


In PHP, you can easily read and write full of existing files and can able to
delete the file. We will initially start with reading a file as:

$myFile = "sampleFile.txt";
$fh = fopen($project, 'r');

$projectContents = fread($fh, 21);


fclose($fh);

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";

$projectLink2 = fopen($project2, 'w+') or die("Can't open file.");


$newContents = "You wrote on me...";

fwrite($projectLink2, $newContents);
fclose($projectLink2);

It is noted that writing to file will vanish it immediately. On using write


function you need to run it on some test content before taking all files out. For
this, you need to have written permission and if it is not enabled, in such case
server will tell PHP that it cannot write to file. On opening file link, we set
variable $newContents to hold content that to be written to file. Finally, apply
fwrite function in order to write $newContents to $projectLink2.

Check your progress 2


1. In PHP, fread function will instruct to read:
a. first two lines

b. last two lines


c. half of the program

d. from top to bottom of file

2.4 Read and write part of file


You can read and write part of the file in PHP. The fopen() function in PHP
is applied to open a file which needs two arguments that initially shows file name
and mode of operation. You can make the change to opened file which will be

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:

∑ Open a file using fopen() function.

∑ Have file's length using filesize() function.

∑ Read file's content using fread() function.

∑ Close file with fclose() function.

Consider an example that contains text file to a variable which shows required text
on web page.

<html>
<head>

if( $file == false ) {


echo ( "Error in opening file" );

exit();

42
?> File and
</body> directory
handling
</html>

It will produce the following result:


File size : 278 bytes

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

fwrite( $file, "This is a simple test\n" );


fclose( $file );

?>
<html>

<head>
<title>Writing a file using PHP</title>

</head>
<body>

43
OO and file
handling in PHP

</body>
</html>

It will produce the following result:


Error in opening new file

Check your progress 3


1. The PHP fopen() function uses _______arguments to open a file.

a. one
b. two

c. three
d. four

2. The fclose() function needs ___________as its argument.


a. arrays

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

}
?>

Once the code is executed, data gets stored in database.


To write into CSV File we require "fputcsv" which will format a line as csv and
write it to particular file handle.

Example
<?php
$list = array (

array('dd', 'mm', 'yy','),


array('12', '12', '2016'),

array('"dd"', '"mm"')
);

$fp = fopen('file.csv', 'w');


foreach ($list as $fields) {

fputcsv($fp, $fields);
}

fclose($fp);
?>

Following code will write into CSV File.

46
Check your progress 4 File and
directory
1. In PHP, fputcsv fuinction helps: handling

a. To read CSV

b. To write CSV file


c. To print CSV file

d. None of above

2.6 Copy, rename and delete file


PHP copying a file
Simply, to copy a file, use copy() function which initially requires file type
to copy that passes file path to first parameter of copy() function. Apart from this,
you need to show file path so as to copy file. It is seen that copy() function will
return true when file gets copied completely, else will returns false. In the
following program, there are specific codes written which shows how to copy the
test.txt file to test2.txt file.

<?php

echo 'An error occurred during copying the file';


<?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{

echo 'An error occurred during renaming the file';


}

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 deleting a file


Similarly you can delete a file using unlink() function where on applying the
particular file will result in deletion using unlink() function. Consider the program
showing use of unlink() function in file deletion.

<?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);

}
<?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

2.7 File uploading


It is seen that normally files get uploaded in temporary directory which
further will send across targeted destination with the help of PHP script.
Information in phpinfo.php page will show temporary directory which is required
for file uploading using upload_tmp_dir with max allowed size of files as
upload_max_filesize. Such parameter gets set in PHP configuration file php.ini.

The process of uploading requires following steps −

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

∑ On pressing submit, selected file gets sent to temporary directory on server.

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

Creating Upload File Script


The "upload.php" file contains the code for uploading a file:

50
File and
directory
handling

In this, we see that:

$target_dir = "uploads/": This will specify directory about the place of file
$target_file: It shows path of file which to be uploaded

$imageFileType: It will keep file extension of file

Check your progress 6


1. The correct form of uploading files in PHP is:

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.

2.9 Answers for Check Your Progress

Check your progress 1

Answers: (1-b)

Check your progress 2

Answers: (1-d)

Check your progress 3

Answers: (1-b), (2-c)

Check your progress 4

Answers: (1-b)

Check your progress 5

Answers: (1-c)

Check your progress 6

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.

2.13 Case Study


Compile and run the program in PHP which will upload files from
computer?

2.14 Further Readings


1. "PHP: Basic syntax", PHI, Robin Smith. 2008-02-22.
2. "Using PHP from command line", PHI, Dixit, 2009-09-11.

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?

3. What are the advantages and drawbacks of directories in PHP?


4. What is declaration of object in PHP?

5. Explain attribute with example?

Long Answer Questions


1. Explain the steps involved in reading and writing part of file in PHp?
2. What are the features of CSV data files in PHP?

3. Explain Copy, rename and delete file in PHP?

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:

3. Any Other Comments

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

56
Education is something
which ought to be
brought within
the reach of every one.

- Dr. B. R. Ambedkar

Dr. Babasaheb Ambedkar Open University


Jyotirmay’ Parisar, Opp. Shri Balaji Temple, Sarkhej-Gandhinagar Highway, Chharodi,
Ahmedabad-382 481.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy