Sei sulla pagina 1di 25

In this PHP web-programming language we will take a look at file handling.

We will take a look at how to open en close a file,

how to read a file line by line and how to read a file character by character.

File Opening Modes


Before we look how to open a file in PHP you need to know that a file can be opened in different modes. For example you can

open a file in read only mode or in read and write modes. Take a look at the table below for the different modes:

Modes Description

r Read only. Starts at the beginning of the file

r+ Read/Write. Starts at the beginning of the file

w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist

w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist

a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist

a+ Read/Append. Preserves file content by writing to the end of the file

x Write only. Creates a new file. Returns FALSE and an error if file already exists

x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

Opening a File
To open a file PHP you can use the fopen() function. This function takes two parameters, where the first parameter contains

the name of the file and the second parameter is the modes that should be used to open the file.

Take a look at an example:

<html>
<body>

<?php
$file=fopen("test.txt","w");
? >
</body>
</html>

In this example we are trying to open een file test.txt in write modes. If the fopen() function is unable to open the specified

file, it returns 0 (of false).

Closing a File
After you have opened a file and you are done (for instance reading its contents) then you should close the file. A fopen()

function should always match with a fclose() function. Take a look at an example:

<?php
$file = fopen("test.txt","r");

//do something with the file test.txt

fclose($file);
?>

Reading a File Line by Line


The fgets() function is used to read a single line from a file. After the line has been read the file pointer is pointing to the next

line in the file. This is very useful, because we could now read the file line by line.

Before we show you the example we have to talk about the feof() function. This function can be used to check if the “End-Of-

File” (EOF) has been reached. This is very useful because we now can loop through a file of unknown length. We can do this on

every file that is not opened in w, a, and x mode!

Let’s take a look at an example:

<?php
$file = fopen("test.txt", "r") or exit("Unable to open the file!");
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>

First we open the file test.txt in read mode. If this is not possible, we exit with a message. Than we use a while loop to loop

through the file. This is done until we reach the end of the file. In the loop the fgets() function is used to grab one line and

echo this line onto the screen. The last thing that is done is closing the file.

Reading a File Character by Character


The function fgetc() can be used to read a character from a file. We now can use the previous example to read a file character

by character. Take a look at the following example:

<?php
$file = fopen("test.txt", "r") or exit("Unable to open the file!");
while(!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

As you can see it is almost the same as the previous example. The only thing that’s changed is the function fgets() in fgetc()

and the html break is removed.

This chapter will explain following functions related to files −

 Opening a file

 Reading a file

 Writing a file

 Closing a file

Opening and Closing Files


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

Files modes can be specified as one of the six options in this table.

Mode Purpose

r Opens the file for reading only.

Places the file pointer at the beginning of the file.

r+ Opens the file for reading and writing.

Places the file pointer at the beginning of the file.

w Opens the file for writing only.

Places the file pointer at the beginning of the file.


and truncates the file to zero length. If files does not

exist then it attempts to create a file.

w+ Opens the file for reading and writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

a Opens the file for writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

a+ Opens the file for reading and writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

If an attempt to open a file fails then fopen returns a value


of false otherwise it returns a file pointer which is used for further reading
or writing to that file.

After making a changes to the opened file it is important to close it with


the fclose() function. The fclose() function requires a file pointer as its
argument and then returns true when the closure succeeds or false if it
fails.

Reading a file
Once a file is opened using fopen() function it can be read with a function
called fread(). This function requires two arguments. These must be the
file pointer and the length of the file expressed in bytes.

The files length can be found using the filesize() function which takes the
file name as its argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.


 Open a file using fopen() function.

 Get the file's length using filesize() function.

 Read the file's content using fread() function.

 Close the file with fclose() function.

The following example assigns the content of a text file to a variable then
displays those contents on the web page.

<html>

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

<body>

<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "<pre>$filetext</pre>" );
?>

</body>
</html>

It will produce the following result −


Writing a file
A new file can be written or text can be appended to an existing file using
the PHP fwrite() function. This function requires two arguments specifying
a file pointer and the string of data that is to be written. Optionally a third
integer argument can be included to specify the length of the data to write.
If the third argument is included, writing would will stop after the specified
length has been reached.

The following example creates a new text file then writes a short text
heading inside it. After closing this file its existence is confirmed
using file_exist()function which takes file name as an argument

<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );

if( $file == false ) {


echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>

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

<body>

<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "$filetext" );
echo("file name: $filename");
?>

</body>
</html>

It will produce the following result −

PHP File Handling


PHP File System allows us to create file, read file line by line, read file character by character, write file,

append file, delete file and close file.

PHP Open File - fopen()


The PHP fopen() function is used to open a file.

Syntax :
resource fopen ( string $filename , string $mode [, bool $use_include_path =
false [, resource $context ]] )

Example
<?php

$handle = fopen("c:\\folder\\file.txt", "r");

?>

PHP Close File - fclose()


The PHP fclose() function is used to close an open file pointer.

Syntax :

ool fclose ( resource $handle )

Example
<?php

fclose($handle);

?>

PHP Read File - fread()


The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and

file size.

Syntax :

string fread ( resource $handle , int $length )


Example
<?php

$filename = "c:\\myfile.txt";

$handle = fopen($filename, "r");//open file in read mode

$contents = fread($handle, filesize($filename));//read file

echo $contents;//printing data of file

fclose($handle);//close file

?>

Output : hello php file

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax :

int fwrite ( resource $handle , string $string [, int $length ] )

Example
<?php

$fp = fopen('data.txt', 'w');//open file in write mode

fwrite($fp, 'hello ');

fwrite($fp, 'php file');

fclose($fp);

echo "File written successfully";

?>
output : File written successfully

PHP Delete File - unlink()


The PHP unlink() function is used to delete file.

Syntax :

bool unlink ( string $filename [, resource $context ] )

Example
<?php

unlink('data.txt');

echo "File deleted successfully";

?>

Using PHP file handling mechanism, we can get external file resources to store
as a reference. We have slightly touched about file resources while
discussing PHP Resource Data.

PHP provides set of in-built functions to handle files. Some of the functions
are, fopen(), file_exists(), file_get_contents() and etc.

Some of the basic operations to deal with files are listed below.

 Opening file
 Working with file read, write and append
 Closing file

Opening file
To open a file, we need to specify the name of that file and mode. The mode
of operation deals with the access limitation of the file to be opened.
Mode of Operation

In PHP file handling, there are four set of possible modes. These are,

 {r and r+} – To read existing file.


 {w and w+} – To change the entire file content.
 {a and a+} – To add content after existing file content.
 {x and x+} – To create a new file and work with it.

Read existing file.

In PHP, the following types of two file handling modes are used to read
existing file. The file pointer will point to the start of the file.

Mode of Operation File Mode File Pointer Position

r read-only Start of the file content

r+ read-write Start of the file content

Using fopen() function, we can open a file by it’s name and corresponding
mode. For example,

$filePointer = fopen("hello.txt","r");
while(!feof($filePointer)){
echo fgets($filePointer). "<br>";
}

Note: We should ensure that the specified file exists. If not, the following error
will occur,
Warning: fopen(hello.txt) [function.fopen]: failed to open stream: No such
file or directory in ...

Warning: fgets() expects parameter 1 to be resource, boolean given in ...

Write into a file.

To perform the write operation, we have two choices to select the mode of the
file to be opened. These are,

Mode of Operation File Mode File Pointer Position

w write-only Start of the file content

w+ read-write Start of the file content

By using these modes, the entire file content will be cleared and the pointer
will focus the start position of the file content. This method is used to change
the existing file content, completely.

For example,

$filePointer = fopen("hello.txt","w");
fwrite( $filePointer, "PHP POT: MySQL Query\n" );

Append content to the file

In this operation, the existing content of the file will not be cleared. Rather, we
can add new content continuously. Here, file pointer will point end of the file.
And the possible mode of operations are,
Mode of Operation File Mode File Pointer Position

a write-only Start of the file content

a+ read-write Start of the file content

The code will be similar to that of file-write except the mode specified to open
the file. For example,

$filePointer = fopen("hello.txt","a");

Note: In PHP, write and append mode will open the specified file if exists.
Otherwise, a new file will be created for performing file write and append.

create a new file

Here also two file handling modes available that are used to write into a newly
created file.

Mode of Operation File Mode File Pointer Position

x write-only. –

x+ read-write. –

For example,

$filePointer = fopen("hello.txt","x");
fwrite( $filePointer, "PHP POT: FUNCTIONS\n" );

Caution: is already exists, then the execution will be stopped with the
following error.
Warning: fopen(hello.txt) [function.fopen]: failed to open stream: File exists
in ... on line ...
Warning: fwrite() expects parameter 1 to be resource, boolean given in ... on
line ...

Closing File

After performing all the above file operations of PHP, we need to close it by
using the fclose() function. fclose() function should hold the file pointer which
is the reference for the file resources. In PHP, we can use fclose() as shown
below.

fclose( $filePointer);

File handling is an important part of any web application. You often need to open and process a
file for different tasks.

PHP Manipulating Files


PHP has several functions for creating, reading, uploading, and editing files.

Be careful when manipulating files!

When you are manipulating files you must be very careful.

You can do a lot of damage if you do something wrong. Common errors are: editing the wrong file,
filling a hard-drive with garbage data, and deleting the content of a file by accident.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.

Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows (the readfile() function
returns the number of bytes read on success):

Example
<?php
echo readfile("webdictionary.txt");
?>

The readfile() function is useful if all you want to do is open up a file and read its contents.

PHP Open File - fopen()


A better method to open files is with the fopen() function. This function gives you more options than
the readfile() function.

We will use the text file, "webdictionary.txt", during the lessons:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The first parameter of fopen() contains the name of the file to be opened and the second parameter
specifies in which mode the file should be opened. The following example also generates a message if
the fopen() function is unable to open the specified file:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Run example »

Tip: The fread() and the fclose() functions will be explained below.

The file may be opened in one of the following modes:

Modes Description

r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File
pointer starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file.
Creates a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File
pointer starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the
file. Creates a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists

PHP Read File - fread()


The fread() function reads from an open file.

The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.

The following PHP code reads the "webdictionary.txt" file to the end:

fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.

It's a good programming practice to close all files after you have finished with them. You don't want
an open file running around on your server taking up resources!

The fclose() requires the name of the file (or a variable that holds the filename) we want to close:

<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>

PHP Read Single Line - fgets()


The fgets() function is used to read a single line from a file.

The example below outputs the first line of the "webdictionary.txt" file:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

Run example »

Note: After a call to the fgets() function, the file pointer has moved to the next line.

PHP Check End-Of-File - feof()


The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

Run example »

PHP Read Single Character - fgetc()


The fgetc() function is used to read a single character from a file.

The example below reads the "webdictionary.txt" file character by character, until end-of-file is
reached:

Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);
?>

Note: After a call to the fgetc() function, the file pointer moves to the next character.

PHP Create File - fopen()


The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created
using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing
(w) or appending (a).

The example below creates a new file called "testfile.txt". The file will be created in the same directory
where the PHP code resides:

Example
$myfile = fopen("testfile.txt", "w")
PHP File Permissions
If you are having errors when trying to get this code to run, check that you have granted your PHP file
access to write information to the hard drive.

PHP Write to File - fwrite()


The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is
the string to be written.

The example below writes a couple of names into a new file called "newfile.txt":

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string
$txt that first contained "John Doe" and second contained "Jane Doe". After we finished writing, we
closed the file using the fclose() function.

If we open the "newfile.txt" file it would look like this:

John Doe
Jane Doe

PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing file
for writing. All the existing data will be ERASED and we start with an empty file.

In the example below we open our existing file "newfile.txt", and write some new data into it:

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just
wrote is present:

Mickey Mouse
Minnie Mouse

This chapter will explain following functions related to files:


 Opening a file
 Reading a file
 Writing a file
 Closing a file

Opening a File
The 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.
The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode
the file should be opened:

<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>

Files modes can be specified as one of the six options in this table.

Mod
Description
e
Read only. Opens the file for reading only.
r
Places the file pointer at the beginning of the file.
Read/Write.Opens the file for reading and writing.
r+
Places the file pointer at the beginning of the file.
w Write only.Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
Mod
Description
e
exist then it attemts to create a file.
Read/Write.Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
w+
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
Append.Opens the file for writing only.
a Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
Read/Append.Opens the file for reading and writing only.
a+ Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
Write only.Creates a new file. Returns FALSE and an error if file
x
already exists
Read/Write.Creates a new file. Returns FALSE and an error if file
x+
already exists
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further
reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file
pointer as its argument and then returns true when the closure succeeds or false if it fails.
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).
Example
The following example generates a message if the fopen() function is unable to open the specified file:

<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>

Closing a File
The fclose() function is used to close an open file:

<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>

Check End of file


The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!

if (feof($file)) echo "End of file";


 

Reading a file
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments.
These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file
expressed in bytes.
So here are the steps required to read a file with PHP.
 Open a file using fopen() function.
 Get the file's length using filesize() function.
 Read the file's content using fread() function.
 Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents on the web page.

<html>

<head>

<title>Reading a file using PHP</title>

</head>

<body>

<?php

$filename = "/home/user/guest/tmp.txt";

$file = fopen( $filename, "r" );

if( $file == false )

echo ( "Error in opening file" );

exit();

$filesize = filesize( $filename );

$filetext = fread( $file, $filesize );

fclose( $file );
echo ( "File size : $filesize bytes" );

echo ( "<pre>$filetext</pre>" );

?>

</body>

</html>

 
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br>";
  }
fclose($file);
?>
 

Reading a File Character by Character


The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);
?>
 

Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite()function. This function requires two
arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to
specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been
reached.
The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed
using file_exist() function which takes file name as an argument

<?php

$filename = "/home/user/guest/newfile.txt";

$file = fopen( $filename, "w" );

if( $file == false )

echo ( "Error in opening new file" );

exit();

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

fclose( $file );

?>

<html>

<head>

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

</head>

<body>

<?php

if( file_exist( $filename ) )

{
$filesize = filesize( $filename );

$msg = "File created with name $filename ";

$msg .= "containing $filesize bytes";

echo ($msg );

else

echo ("File $filename does not exit" );

?>

</body>

</html>