Please style sheet are not equal in internet explorer browser Firefox, Chrome, Safari, Apple and Opera browser please visit this website.

Thank for Visit My Site and Please sent me Shayari, Status and Quotes post request.

PHP - Object Oriented Programming, Working with File System & I/O

Object Oriented Programming
 
Introduction
 
While PHP 4 was the first version to offer Object-Oriented Programming (OOP) capabilities, many considered the feature to be poorly designed and more an afterthought than anything else. PHP 5 resolves many of the version 4 OOP inconsistencies, not to mention greatly enhances the language's object-oriented capabilities.
 
While you're still free to program using a procedural methodology, those of you with object oriented backgrounds will certainly feel much more at home creating fully object-driven PHP applications. In this article I'll introduce many of these new and improved features.
 
In addition, for those of you somewhat new to the subject, this article will also offer a bit of instruction regarding those concepts key to truly understanding OOP.
 
While for many languages object orientation is simply a matter of course, it took several years before such features were incorporated into PHP. Yet the early forays into adding object-oriented features to the language were considered by many to be a poor attempt at best.
 
Although the very basic premises of object-oriented programming (OOP) were offered in version 4, several deficiencies existed, including the following:
 
. An unusual object-referencing methodology
. No means for setting the scope (public, private, protected, abstract) of fields and methods
. No standard principle for naming constructors
. Absence of object destructors
. Lack of an object-cloning feature
. No support for interfaces
 
Thankfully, version 5 eliminated all of the abovementioned encumbrances, offering significant improvements over the original implementation, as well as a bevy of new OOP features. This chapter and the following aim to introduce these new features and enhanced functionality.
 
 
 
The Benefits of OOP
 
The birth of object-oriented programming represented a major paradigm shift in development strategy, refocusing attention on an application's data rather than its logic. To put it another way, OOP shifts the focus from a program's procedural events toward the real-life entities it ultimately models. The result is an application that closely resembles the world around us.
 
This section examines three of OOP's foundational concepts:
Encapsulation,
Inheritance,
and
Polymorphism
 
Together, these three ideals form the basis for the most powerful programming model yet devised.
 
Note: For detailed information on OOP please read our C++ tutorial at http://education.mkdtutorials.com
 
PHP provides extensive support for developing object-oriented web applications. The area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of this Tutorial.
 
Instead we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to PHP development.
 
An object-oriented programming system (OOPS) consists of objects. The object determines both the state and the behavior of the corresponding element.

Why has object-oriented programming gone from being ``something to think about'' to being a de-facto standard in the way software is developed today? OOA/OOD/OOP is good for: * Analyzing user requirements * Designing software * Constructing software o Reusability (reusable components) o Reliability o Robustness o Extensibility o Maintainability * Reducing large problems to smaller, more manageable problems

 
Why OO PHP5?
 
For now let's just say that OOP is about creating relatively small objects with specific functions that interact with each other to form a complete application.
 
Typically, the main advantages of OOP are:
 
* Reusability of code:
a well designed object has only one specific function and is therefore completely independent of the environment it is placed in and thus can be reused easily.
 
* Clearer structure of code:
Again a well designed object has only one specific function which means that all the code supporting that function is located in one place which increases maintainability.
 
* Easy to maintain:

While using Classes for small projects in your PHP script may seem cumbersome due to extra lines of code that is required, but when you work on a large project or as your project grows in term of size, pages or functionality, using OO approach becomes a necessity.
 
A major disadvantage of OOP is that it requires more lines of code and is therefore more time consuming to produce.
 
In PHP we as developers are left with a choice. Typically, anyone who started out with PHP without any (OO) programming background will have started with learning procedural coding.
 
Most tutorials on the web only cover procedural coding and quite honestly, the old fashioned way is just easier to use in many situations (for instance in small applications, or when you just start out with PHP).
 
 
 
Difference between PHP4 & PHP5
 
In general when a new software version appears everybody hurries to update it especially if it is for free. PHP 5 has just appeared and it seems that there are people who use the PHP 4 version and others who use the PHP 5 one.
 
You probably know that PHP 5 is destined for OOP, but it appears that habitual programming can be used too. Moreover, OOP is used in PHP4 as well, with the difference that in PHP5 things are a little more evaluated.
 
This means that in PHP4 safety modes for classes (public, private) are not accepted. In PHP4 the objects are a kind of structures which accept objects and functions as well, according to OOP. In PHP4 they are useful as well.
 
If you are used to working with PHP4 you can use PHP5 with no problems because the differences are not significant and the changes were made so that programmers would not be confused. An example would be class builders which, in PHP4 were functions within the classes bearing the same name as the class.
 
In PHP5 it is firstly checked if there is a function (method) __construct (). If it does not exist, check if there is a function (method) which has the same name as the class. This means that even if you are not aware of the latest news in the domain of PHP5, your scripts will function without any problem.
 
But it is strongly recommend to migrate to PHP5 (if you are using PHP4) or to start with PHP5 if you are new to PHP, because PHP has discontinued the support of PHP4 and it will not release any patches or security updates for PHP4. Since PHP has withdrawn support for PHP4 web servers will discontinue support of PHP4 sooner or later, so the sooner you change the better for you.
 
Differences Between PHP 4 and 5
 
Language Features PHP 5 allows limited type hinting. This allows you to specify that the parameter to a function or class method can only be of a specific class (or one of its subclasses), or an array. However, you may not specify any other scalar types.
 
The foreach construct now supports by-reference declaration of the value element. A number of new functions, particularly for string and array manipulation, has also been added to the core platform.
 
Objects For all intents and purposes, all objects in PHP 5 are passed by reference. This means that assigning an object to a variable will not create a copy of the former, but simply creates another reference to it. Constants, as well as static methods and properties, can now be defined within the scope of a class.
 
Class methods and properties now feature visibility, and can be declared as public, private or protected. Classes and methods can also be declared as final to prevent further inheritance. Since all objects are assigned by reference, you now need a specialized mechanism to copy objects. This is provided by the clone construct and the __clone() magic method.
 
PHP 5 features unified constructors and destructors-all constructors should now be named __construct(), and the new __destruct() magic method has been added for object destruction.
 
With the addition of interfaces and abstract classes, PHP developers now have far greater control over how they implement their object-oriented code. Interfaces can be used to define common APIs, while abstract classes provide models for class implementations that follow a specific blueprint.
 
Class definitions can now be loaded on demand by using the __autoload() function.
 
MagicMethods A multitude of new "magic" methods has been introduced in PHP 5: __get() and __set() are called when accessing or assigning an undefined object
 
property, while __call() is executed when calling a non-existent method of a class. __isset() is called when passing an undefined property to the isset() construct.
 
. __unset() is called when passing an undefined property to unset().
. __toString() is called when trying to directly echo or print() an object.
. __set_state() is inserted dynamically by var_export() to allow for reinitialization on execution of var_export()'s output.
 
Selected New Extensions
 
. SimpleXML allows easy access to XML data using object and array notation.
 
. PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in the form of the libxml2-based DOM and XSL extensions.
 
. The PHP Data Objects (PDO) extension provides a unified database access extension that allows access to many different types of database systems by using a common interface. PDO is not an abstraction layer-except for prepared queries, it does nothing to abstract the actual database code (SQL), itself.
 
. The hash extension is a new replacement for the GPLed libmhash; it was added to the PHP core starting with version 5.1.2. It can produce hashes using many algorithms, including the familiar MD5 and SHA1, as well as some more secure (albeit slower) algorithms, such as snefru.
 
. The Standard PHP Library (SPL) provides numerous interfaces that enhance the way classes interact with the PHP language, including the new Iterator interfaces.
 
. The new Reflection extension allows for runtime introspection of executing PHP code.
 
ErrorManagement
 
Classes now support exceptions; the new set_exception_handler() functionallows you to define a script-wide exception handler.
 
. The E_STRICT error reporting level has been added to the language to emit notices when legacy or deprecated code is encountered.
 
 
 
Classes and Objects in PHP5
 
What is an Object?
 
An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application. Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.
 
An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life.
 
What is a Class?
 
Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.
 
How is an Object Created from a Class?
 
The process of creating an object from the class 'blueprint' is called instantiation. Essentially, you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods.
 
You can create as many object instances of a class as you desire. Objects are instantiated using the new keyword. For example, to create an instance of a class called employee_details we would write:
 
$emp = new employee_details();
 
In the above example we now have an object called $emp of type employee_details.
 
What is sub-classing?
 
It is possible to build classes that are derived from other classes, extending the functionality of the parent class to make it specific to a particular requirement. For example you might have a vehicle class which contains the attributes common to all vehicles, and a subclass called car which inherits all the generic vehicle attributes but adds some its own car specific methods and properties.
 
Defining a PHP Class
 
Before an object can be instantiated we first need to define the class 'blueprint' for the object. Classes are defined using the class, keyword followed by braces which will be used to enclose the body of the class:
 
<?php
class employee_details
{ //variables, methods and other class elements }
?>
 
We have now defined a class.
 
Note: the structure of class in PHP is almost same to the classes found in other Object Oriented Programming languages such as Java/C++ etc.
 
 
 
Creating and Using Classes in PHP5
 
Defining a PHP Class
 
Before an object can be instantiated we first need to define the class 'blueprint' for the object. Classes are defined using the class keyword followed by braces which will be used to enclose the body of the class:
 
<?php
class employee_details {
}
?>
 
We have now defined a class. The next step is add some functionality to the class.
 
PHP Class Constructors and Destructors
 
The next step in creating a class is to define what should happen when an object is first instantiated using the class, and also when that object is later destroyed. These actions are defined in the constructor and destructor methods of the class.
 
The constructor and destructor are really just functions that get called when the object is created and destroyed and are defined in the class body using the function keyword. This needs to be prefixed with the public qualifier.
 
This means the method is accessible to code outside of the object. The default names for the constructor and destructor are __construct and __destruct respectively. Both methods can take arguments to be used in initializing the object. These are declared in the same way arguments are defined in any function (see PHP Functions for details).
 
We can now extend our employee_details class to include a constructor and destructor:
 
<?php
class employee_details{


 public function __construct($emp_id,$emp_name,$addr)
 {

  echo "Constructor Called with the following values<br>";
  echo "Employee ID = ".$emp_id."<br>E
mployee Name = ".$emp_name."<br>Address = ".$addr; } public function __distruct(){} } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> PHP Tutorial: Working with Classes </TITLE> <META NAME="Generator" CONTENT="jNote-iT"> </HEAD> <BODY> <?php $emp=new employee_details("EMP0012","Aman Singh","B-320,
Sector 44, Rohni"); ?> </BODY> </HTML>
 
When the example is loaded into a browser we should get the following output:
 
img
 
Creating Members in a PHP Class
 
Class members are essentially variables and methods embedded into the class. Members can be public or private and static or variable.
 
Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).
 
Members declared as static are immutable, in that once defined they cannot be changed (much like constants). Members and functions are prefixed with public, private and static when declared in the class. The default is public non-static.
 
We can now extend out employee_details class to add member variables to hold the account name and number passed into the constructor. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as private. We will also add to our constructor to assign the passed arguments to our new members.
 
When doing so we need to use the $this variable to tell PHP we are setting variables in the current class:
 
<?php
class employee_details{
 private $emp_id;
 private $emp_name;
 private $addr;

 public function __construct($emp_id,$emp_name,$addr)
 {
  $this->emp_id=$emp_id;
  $this->emp_name=$emp_name;
  $this->addr=$addr;
  echo "Constructor Called with following values:";
  echo "<br>Employee ID   : ".$this->emp_id;
  echo "<br>Employee Name : ".$this->emp_name;
  echo "<br>Address  : ".$this->addr;
 }
 public function __distruct(){}
}
?>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> PHP Tutorials: Working with Classes </TITLE> <META NAME="Generator" CONTENT="jNote-iT"> </HEAD> <BODY> <?php $emp=new employee_details("EMP0012",
"Aman Singh","B-320, Sector 44, Rohni"); ?> </BODY> </HTML>
 
The next task is to define methods that will give us access to our data.
 
Defining and Calling Methods
 
We define our own methods in much the same way as we declared the constructor and destructor methods with exception that we get to choose the names.
 
We declare methods inside PHP classes in the fashion we declare methods outside, the only difference being that, we may specify an access specifier like public, private etc. To demonstrate this we will add to our class to provide methods to get and set the Employee id, name and address:
 
Source code for Employee.class.php
 
<?php
class employee_details{
 private $emp_id;
 private $emp_name;
 private $addr;

 function __construct($emp_id,$emp_name,$addr)
 {
  $this->emp_id=$emp_id;
  $this->emp_name=$emp_name;
  $this->addr=$addr;
 }
 //Setter Methods of employee details class
 public function setEmpID($emp_id)
 {
  $this->emp_id=$emp_id;
 }
 public function setEmpName($emp_name)
 {
  $this->emp_name=$emp_name;
 }
 public function setEmpAddr($addr)
 {
  $this->addr=$addr;
 }
//getter Methods of employee details class
 public function getEmpID()
 {
  return $this->emp_id;
 }
 public function getEmpName()
 {
  return $this->emp_name;
 }
 public function getEmpAddr()
 {
  return $this->addr;
 }

 public function display_details()
 {
  echo "<br>Employee ID      : ".$this->emp_id;
  echo "<br>Employee Name : ".$this->emp_name;
  echo "<br>Address      : ".$this->addr;
 }
}
?>
 
Save the above script as employee.class.php
 
Now that we have defined our getter and setter method to get and set the employee values we can call the methods. This is done by specifying the name of the object on which the methods are being called. This is followed by '->', and then the name of the method we are calling (including the parentheses containing any arguments required):
 
$emp2=new employee_details("","","");
//Using setter metter to set the employee details
$emp2->setEmpID("EMP0032");
$emp2->setEmpName("Neelam Rai");
$emp2->setEmpAddr("C-216/2, 
Barakhamba Road, New Delhi");
 
Complete Source code of employee_class.php
 
<?php
require ("employee.class.php");
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>
<BODY>

<?php
$emp1=new employee_details("EMP0012",
"Aman Singh","B-320, Sector 44, Rohni"); $emp2=new employee_details("","",""); //Using setter metter to set the employee details $emp2->setEmpID("EMP0032"); $emp2->setEmpName("Neelam Rai"); $emp2->setEmpAddr("C-216/2,
Barakhamba Road, New Delhi"); #Displaying Details of Employee 1 echo "<h3>Details of Employee 1</h3>"; $emp1->display_details(); #Displaying details of Employee 2 echo "<h3>Details of Employee 1</h3>"; $emp2->display_details(); echo "<br> <b> Name of Employee 2 is :
".$emp2->getEmpName()."</b>"; ?> </BODY> </HTML>
 
The above example sets the account name and number when instantiating the object. It then the getEmpName (to verify the change), thereby producing the following output:
 
img
 
Getting Information about a PHP Object
 
There are number of ways to find out information about classes. An array of classes to which your script has access can be obtained using the get_declared_classes() function. The class_exists() function can be passed the name of a class to find out if such a class exists. A list of methods in a class can be obtained by passing the class name through to the get_class_methods() function.
 
It is also possible to find out if a class has a parent class using the get_parent_class() function which will either return the name of the parent class, or an empty string if no parent exists. The method_exists() function, when passed an object pointer and method name as arguments, will return a true or false value indicating the existence of the method.
 
Inheritance and sub classing in PHP5
 
Once a class has been defined it is possible to create a new class derived from it that extends the functionality of the original class. The parent class is called the superclass and the child the subclass. The whole process is referred to as 'subclassing.
 
A subclass of a class can be defined using the extends keyword when declaring the subclass. For example we might choose to create a subclass of our employee_details class called tech_employee which defines an interest bearing type of employee:
 
<?php
require ("employee.class.php");
 class tech_employee extends employee_details
 {
  private $dept;//Variable to store Department of the Employee
  private $team_id;//Variable to store Team ID of the employee
  private $prj_name;//Variable to store name
of the Project employee is currently working on private $prj_role; // Variable t
o store Role of the employee in the project //other tech_employee
specific processing logic, methods etc }
 
The important point to note here is that tech_employee inherits all the members and methods of employee_details and adds a new member(s) (such as team id[$team_id], project name[$prj_name], etc.).
 
We can extend the class further by adding a new method to return other tech employee specific details:
 
Source code of tech_employee.class.php
 
<?php
require ("employee.class.php");
 class tech_employee extends employee_details
 {
  private $dept;//Variable to store Department of the Employee
  private $team_id;//Variable to store Team ID of the employee
  private $prj_name; // Variable to store name o
f the Project employee is currently working on private $prj_role; // Variable to s
tore Role of the employee in the project public function __construct($emp_id, $e
mp_name,$addr,$dept,$team_id,$prj_name,$prj_role){ echo "Calling Parent Constructor"; parent::__construct($emp_id,$emp_name,$addr); //Calling Parent Class Constructor with required Parameter $this->dept=$dept; $this->team_id=$team_id; $this->prj_name=$prj_name; $this->prj_role=$prj_role; } public function setDept($dept){ $this->dept=$dept; } public function setTeam_id($team_id){ $this->team_id=$team_id; } public function setPrjName($prj_name){ $this->prj_name=$prj_name; } public function PrjRole($prj_role){ $this->prj_role=$prj_role; } function getDept(){ return $this->dept; } function getTeamId(){ return $this->team_id; } function getPrjName(){ return $this->prj_name; } function getPrjRole(){ return $this->prj_role; } public function display_details(){ parent::display_details(); //calling parent's display method #echo "<pre>"; echo "<br>Employee Department: <b>".$this->dept."</b>"; echo "<br>Team ID :
<b>".$this->team_id."</b>"; echo "<br>Current Project
: <b>".$this->prj_name."</b>"; echo "<br>Role in th
e Current Project:<b>".$this->prj_role."</b>"; } } ?>
 
In PHP parent keyword along with :: (scope resolution) operator is used to access parent class methods and properties.
 
Source code of extended_employee.php
 
<?php
require ("tech_employee.class.php");
?>
<HTML>
<HEAD>
<TITLE> PHP Tutorials: Working with Classes </TITLE>
<META NAME="Generator" CONTENT="jNote-iT">
</HEAD>

<BODY>
<?php
 $emp3=new tech_employee("TECH0031","Ravish Kumar","D-410, S
ector 19, Noida","TECH-PHP","PHP03","MKDTutorials EDUCATION","PHP Developer"); echo "<h3>Details of Employee 1[TECH EMPLOYEE]</h3>"; echo "<pre>"; $emp3->display_details(); echo "</pre>"; ?> </BODY> </HTML>
 
When this page is executed it produces the following output:
 
img
 
Assignment

1. Create a PHP class Simple_class and implement "Hello World!" using hello function in Simple_class

2. In the above Class create another function helloTo, which accepts an argument e.g. name and display "Hello :)".name.

3. Create a class Simple_calculator and implement Add & Subtract operation using member functions. Both functions should accept two arguments and return the result.

4. Create a class Adv_calculator which extends the Simple_calculator and contain three member function multi(), modulo() & division() besides the parent class methods. Call all 5 functions using object of Adv_calculaor.

5. Write a PHP Script to print a list of classes the script has access of. 6. Write PHP Script to check whether a method exists or not.
 
 
 
Working with File System & I/O
 
Working with Directories
 
Working with Directories
 
PHP provides a number of functions that can be used to perform tasks such as identifying and changing the current directory, creating new directories, deleting existing directories and list the contents of a directory.
 
Creating Directories in PHP
 
A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as your PHP script, simply provide the directory name. To create directory in a different directory specify the full path when calling mkdir().
 
A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable):
 
<?php
$result = mkdir ("test", "0777")or die ("Failed to create Directory");
if($result)
  echo "directory created successfully";
?>
 
Deleting a Directory
 
Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub-directories the deletion cannot be performed until those files and sub-directories are also deleted.
 
Finding and Changing the CWD (current working directory)
 
Do you expect a web application to be able to perform all of its file related tasks in a single directory? The answer is NO, it is possible but it will create a mess. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP stript.
 
The current working directory can be identified using the getCwd() function:
 
<html>
<head><title>PHP Tutorial- Working with Directories</title>
</head>
<body>
<?php
$cwd=getCwd();
echo "Current Working Directory is <b>".$cwd."</b>";

?>
</body>
</html>
 
save the above script as getCWdir.php and open the page in browser. If your script is fine then you should get the output given below:
 
img
The current working directory can be changed using the chdir() function. chdir() takes as the only argument the path of the new directory:
 
<html>
<head><title>PHP Tutorial- Working with Directories</title>
</head>
<body>
<?php
$cwd=getCwd();
echo "Current Working Directory is <b>".$cwd."</b>";
chdir ("/e_drive");
$cwd=getCwd();
echo "After Changing the Directory, Current Working Directory is <b>".$cwd."</b>";

?>
</body>
</html>
 
Save the file as chdir.php and open the open the PHP script in browser to view the output:
 
img
Listing Files in a Directory
 
The files in a directory can be read using the PHP scandir() function. scandir() takes two arguments. The first argument is the path the directory to be scanned. The second optional argument specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-alphabetically.
 
If the argument is omitted or set to 0 the list is sorted alphabetically:
 
<html>
<head><title>PHP Tutorial- 
Working with Directories</title> </head> <body> <?php $cwd=getCwd(); echo "Current Working Directory is <b>".$cwd."</b>"; chdir ("/var"); $cwd=getCwd(); echo "<br/>After Changing the Directory,
Current Working Directory is <b>".$cwd."</b><br>"; $array = scandir(".", 1); print_r($array); ?> </body>
 
Save the file and open the page in browser to view the output.
 
Output:

Try it your self.
 
 
 
Working with Files
 
Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files. When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.
 
It is our hope that you will be able to avoid these and other slipups after reading this section. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.
 
Opening and closing File
 
Opening a file
 
to open a file in PHP function fopen is used. fopen takes accepts to parameter
 
1. name of the file
2. file opening mode (such as read-only, read-write, etc)
 
Syntax to open a file:
 
$my_file=fopen("file name", "mode constant");
 
Closing a file
 
function fclose is used to close a file in PHP. fclose takes accepts to parameter
 
syntax to close a file:
 
fclose(file_pointer);
 
File Opening mode
 
The following table lists the various file open attributes together with a brief description of each:
 
Mode Description
r Read only access. Pointer is positioned at start of file.
r+ Read and write access. Pointer is positioned at start of file.
w Write only access. Pointer is positioned at start of file. File is created if it does not already exist.
w+ Read and write access. Pointer is positioned at start of file. File is created if it does not already exist.
a Write only access. Pointer is positioned at end of file. File is created if it does not already exist.
a+ Read and write access. Pointer is positioned at end of file. File is created if it does not already exist.
x Create and open for write only. Pointer is positioned at start of file. Return false if file already exists.
x+ Create and open for read and write. Pointer is positioned at start of file. Return false if file already exists.
 
 
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file. If you wanted to add the latest order to your "employees.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.save the above script as fileopen.php and open the script in browser to view the output.
 
<html>
<head><title>PHP Tutorial- Working with Files</title>
</head>
<body>
<?php
$my_file = fopen("test.txt","r")or die();
echo "<b>File opened successfully</b>";
fclose($my_file);
?>
</body>
</html>
 
img
 
Note: this example assumes that you have a file named test.txt in the directory you have stored the PHP script otherwise you will get an error message.
 
Reading content of a file
 
In PHP you have multiple functions to read content of a file
 
Syntax of fread :
 
string fread ( resource handle, int length ) fread() reads up to length bytes from the file pointer referenced by handle.
 
Syntax of readfile :
 
int readfile ( string filename [, bool use_include_path [, resource context]] ) Reads a file and writes it to the output buffer. Reading file content with fread function:
 
<html>
<head><title>PHP Tutorial- Working with Files</title>
</head>
<body>
<?php
 $file_2_open="test.txt";
 $my_file= @fopen($file_2_open,"r+") or d
ie("Unable to open file : $file_2_open."); $data= @fread($myfile,1024); echo "Content of the file $file_2_open :<br/>".$data; while(!feof($my_file)) { echo fgets($my_file). "<br />"; } ?> </body> </html>
 
The above example should generate the following output:
 
img
It is also possible to read and output the contents of an entire file with the readfile() function. This function reads the entire contents of a file and outputs that content. Assuming you don't need to do anything but output the contents of a file then 'readfile() is an easy solution because it does all the work for you. You do not need to open the file, read the data, close the file and display the data. All you need to do is call readfile() passing in the file path as an argument and it does the rest.
 
PHP file Functions
 
There are several different ways of reading a file, but before you try to read a file, you have to make sure the file exists first. To do this, PHP comes with an inbuilt function called is_readable(), which checks if the file exists and if it's readable by your script. It's possible that your script can't read the file due to permissions, even though the file does exist.
 
Syntax:
 
bool is_readable ( string filename ) Returns TRUE if the filename exists and is readable.
 
It's used like this:
 
<?php

$file = '/home/user/PHP/examples/test.txt';
//on windows replace the path with your file path

if (is_readable($file) == false) {
        die(' doesn\'t exist or File is not readable');
} else {
        echo 'File <b>'.$file.'</b> exists';
}

?>
 
Output:
 
img
 
After you've made sure that the file is readable, you can now read the file data. The easiest way to do this is with the file_get_contents() function, which requires only one argument - the file path - and immediately returns all the file data.
 
Syntax:
 
string file_get_contents ( string filename [, int use_include_path [, resource context]] )
 
It's used like so:
 
<?php
$file = '/home/user/PHP/examples/phpinfo.php';
//on windows replace the path with your file path

if (file_exists($file) == false) {
        die('File $file doesn\'t exist!');
}

// Read file
$data = file_get_contents($file);
echo htmlentities($data);

?>
 
The only downside with file_get_contents() is that it's only supported by PHP 4.3 and later. This means you will probably have to account for versions lower than that, which means you can't use the file_get_contents() function. The next best way is to then use the file() function, which is supported by PHP 3 and up, and is almost identical to the file_get_contents function. The only difference is that the file function returns the file data in an array, with each line as a separate item.
 
If you just want the data as a string (like the file_get_contents function), you have to use the following code:
 
<?php
// Read file
$data = implode('', file($file));
?>
 
This method is probably the best way to read a file, and it's supported by any modern PHP version. But there is yet another way to do it, by manually opening the file, and then reading in the data.
 
To open a file, you have to use the fopen() function, which opens a file, and returns a file resource, which can then be used with the fread() function. When opening a file, you must specify a mode in which to open the file. If all you want to do is read the file, you need to specify the 'r' mode, like in the example below:
 
<?php
// Read file
$f = fopen($file, 'r');
$data = fread($f, filesize($file));
fclose($f);
?>
 
As you can see in the above example, the fread function also needs to know how much data you want to read, which you must specify as the second argument. Since we want to read the whole file, the filesize() function is used, which returns the length of the file. When you're done with the file, you must close it with the fclose() function.
 
 
 
Creating, Copying, moving and Deleting File
 
Writing data to a File
 
The fwrite() function outputs the contents of a string variable to the specified resource.
 
fwrite syntax:
 
int fwrite(resource handle, string string [, int length]) If the optional length parameter is provided, fwrite() will stop writing when length characters have been written. Otherwise, writing will stop when the end of the string is found.
 
Consider this example:
 
   <?php
         // Data we'd like to write to the info.txt file
         $data = "Sanjay Sing|sanjay.kumar@mkdtutorials.com";
         // Open info.txt for writing
         $my_file = fopen("/home/www/data/info.txt", "at");
         // Write the data
         fwrite($my_file, $data);
         // Close the handle
         fclose($my_file);
    ?<
 
 
Moving, Copying and Deleting Files with PHP
 
Files can be copied using the copy() function, renamed using the rename() function and deleted using the unlink() function.
 
Copying and Deleting Files
 
To copy a file, the copy() function is used.
 
bool copy(string source_file,string destination_file)
 
The copy() function will return true if the file was correctly copied, or false if there was an error.
 
<?php
class File_Options{
private $file1;
private $file2;
Private $msg;
 function __construct(){
 $this-<msg=NULL;
 }
 public function doCopy($file, $copyto){
  if (!(copy($file,$copyto))) {
  return $msg;
  }
  else {
  return "<b<File $file successfully copied to $copyto</b<";
  }
 }
 public function doDel($file){
 }
 public function doRen($oldName,$newName){
 }
}
?<
<HTML<
<HEAD<
<TITLE< PHP Tutorial: Working with Files </TITLE<
<META NAME="Generator" CONTENT="jNote-iT"<
</HEAD<

<BODY<
<?php
 $file_opt=new File_Options();
 $msg=$file_opt-<doCopy("test.txt","test1.txt");
 if (!$msg){
  echo "<b<Unable to Copy File to the specified location</b<";
 }
 else
  echo $msg;
?<
</BODY<
</HTML<
 
Assuming that you have a file named test.txt, a successful run of this script should copy the file test1.txt from its current location to your specified location.
 
img
 
The rename() function is very similar in context to the copy() function:
 
Syntax:

bool rename(string old_file,string new_file)
 
Considering the name of the functions so far, it may come as a surprise that the function to delete is called unlink():
 
Syntax:
bool unlink(string filename)
 
Both the rename() and unlink() functions return true upon successful completion, or false if the operation did not complete successfully.
 
Assignment:

1. In the above script, there are two dummy functions, implement delete and rename operations using the function.

2. In the above function, use validation so that the file user is trying to operate is operated only if it exists.

3. Write a PHP script to display contents of a file to user.
 
 
 

SHARE THIS PAGE

0 Comments:

Post a Comment

Circle Me On Google Plus

Subject

Follow Us