0% found this document useful (0 votes)
129 views23 pages

Chapter 3 - Files and Directories

The document discusses files and directories in computing. It defines what a file is, the different types of files, and basic file operations like opening, reading, writing and modifying files. It also discusses illegal file characters that cannot be used in filenames. The document then provides examples of how to open, read, write and modify file contents using PHP functions like fopen(), fwrite(), fputs(), file_get_contents() and more. It also discusses how to read contents from remote files over HTTP or FTP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views23 pages

Chapter 3 - Files and Directories

The document discusses files and directories in computing. It defines what a file is, the different types of files, and basic file operations like opening, reading, writing and modifying files. It also discusses illegal file characters that cannot be used in filenames. The document then provides examples of how to open, read, write and modify file contents using PHP functions like fopen(), fwrite(), fputs(), file_get_contents() and more. It also discusses how to read contents from remote files over HTTP or FTP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Chapter 3: Files and Directories

What is File?

A file a container in a computer system that stores data, information, settings, or commands,
which are used with a computer program. In graphical user interface (GUI), such as Microsoft
operating systems, represent the files as icons, which associate to the program that opens the file.
For instance, the picture is shown as an icon; it is related to Microsoft Word. If your computer
contains this file and you double-click on the icon, it will open in Microsoft Word installed on
the computer.
There are several types of files available such as directory files, data files, text files, binary and
graphic files, and these several kinds of files contain different types of information. In the
computer system, files are stored on hard drives, optical drives, discs, or other storage devices.

The basic operations that can be performed on a file are given below:

o Closing or terminating a file operation


o Creation of programs
o Reading of data from the file
o Creation of a new file
o Opening the file in order to make the contents available to other
o Modification of data or file attributes
o Writing data to the file

Illegal file characters


The given below characters are considered illegal with most operating systems, hence cannot be
used. If you try to create a file name with these characters, it would generate an error or make the
file inaccessible.

: * ? " < > | \ /  

PHP create file and write contents


PHP comes with a couple of different ways to do this as well. To write inside the file first file
must be opened with mode. The mode parameter specifies the type of access you require to the
stream.
How to Open a file in PHP
fopen( ) is used to open a file. You have to pass two parameters inside this function. The first one
is file name which you want to open and second is mode(purpose to open) of the file. 
Syntax

<?php

$fo=fopen(filename, mode, include_path, context);
?>

Parameter Description

filename Required. Specifies the file or URL to open

Mode Required. Specifies the type of access you require to the file/stream.

Possible values:

 "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 truncates the file; or creates a new file if it
doesn't exist. Place file pointer at the beginning of the file
 "w+" - Read/Write. Opens and truncates the file; or creates a new file if it
doesn't exist. Place file pointer at the beginning of the file
 "a" - Write only. Opens and writes to the end of the file or creates a new
file if it doesn't exist
 "a+" - Read/Write. 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
 "c" - Write only. Opens the file; or creates a new file if it doesn't exist.
Place file pointer at the beginning of the file
 "c+" - Read/Write. Opens the file; or creates a new file if it doesn't exist.
Place file pointer at the beginning of the file
 "e" - Only available in PHP compiled on POSIX.1-2008 conform
systems.
include_path Optional. Set this parameter to '1' if you want to search for the file in the
include_path (in php.ini) as well
Context Optional. Specifies the context of the file handle. Context is a set of options that
can modify the behavior of a stream

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

//Output lines until EOF is reached


while(! feof($file)) {
  $line = fgets($file);
  echo $line. "<br>";
}

fclose($file);
?>

Write the contents inside file


file_put_contents() accept a filename and path, together with the data to be written to the file,
and then writes the latter to the former 
Syntax
file_put_contents(filename, data, mode, context)

Paramete Description
r

filename Required. Specifies the path to the file to write to. If the file does not exist, this
function will create one

Data Required. The data to write to the file. Can be a string, array, or a data stream

Mode • Optional. Specifies how to open/write to the file. Possible values:


• FILE_USE_INCLUDE_PATH - search for filename in the include
directory
• FILE_APPEND - if file already exists, append the data to it - instead of
overwriting it
• LOCK_EX - Put an exclusive lock on the file while writing to it

context Optional. Specifies the context of the file handle. Context is a set of options
that can modify the behavior of a stream.

Eg

<?php

//write string to file


$data="A fish out of water";

file_put_contents("output.txt",$data) or die('ERROR:Can not write file');

echo "data written inside this file";


?>

If the file specified in the call to file_put_contents() already exists on


disk,.file_put_contents() will overwrite it by default. if instead, you'd prefer to preserve the file's
contents and simply append new data to it, and the special FILE_APPEND flag to your.
file_put_contents() function call as a third argument. Eg

<?php

//write string to file

$data="A fish out of water";

file_put_contents("output.txt",$data,FILE_APPEND)or die('ERROR:Can not write file');

echo "data written inside this file";

?>

Write the contents using fwrite( ) function


An alternative way to write data to a file is to create a file pointer with fopen( ), and then write
data to the pointer using PHP's fwrite( ) function.
The fwrite() writes to an open file.
The function will stop at the end of the file (EOF) or when it reaches the specified length,
whichever comes first.
Syntax
fwrite(file, string, length)

Parameter Description

File Required. Specifies the open file to write to

String Required. Specifies the string to write to the open file

Length Optional. Specifies the maximum number of bytes to write

<?php

$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
//The output of the code above will be:21
?>

 Eg

<?php

//open and lock file

//write string to file

//unlock and close file

$data="A fish out of water";

$fo=fopen("output.txt","w");

flock($fo,LOCK_EX) or die('ERROR:cannot lock file');

fwrite($fo,$data);
flock($fo,LOCK_UN) or die('ERROR:cannot unlock file');

fclose($fo);

echo "Data written to file";

?>

Write the contents using fputs( ) function


An alternative way to write small data to a file is fputs( ) function. Eg

<?php

//open and lock file

//write string to file

//unlock and close file

$data="A fish out of water";

$fo=fopen("output.txt","w");

flock($fo,LOCK_EX) or die('ERROR:cannot lock file');

fputs($fo,$data);

flock($fo,LOCK_UN) or die('ERROR:cannot unlock file');

fclose($fo);

echo "Data written to file";

?>

Read the contents of a file in PHP


PHP comes with a couple of different ways to read the contents of file.
Read the contents using file_get_contents( ) function
The easiest way to read the contents of a disk file with the file_get_contents( ) function. This
function accepts the name and path to a disk file, and read the entire file into a string variable.
This function is the preferred way to read the contents of a file into a string. It will use memory
mapping techniques, if this is supported by the server, to enhance performance.

Syntax

file_get_contents(path, include_path, context, start, max_length)

Parameter Description

Path Required. Specifies the path to the file to read

include_pat Optional. Set this parameter to '1' if you want to search for the file in the
h include_path (in php.ini) as well

Context Optional. Specifies the context of the file handle. Context is a set of options that
can modify the behavior of a stream. Can be skipped by using NULL.

Start Optional. Specifies where in the file to start reading. Negative values count from
the end of the file

max_length Optional. Specifies the maximum length of data read. Default is read to EOF

Eg i

<?php

//read file into string


$str=file_get_contents('output.txt') or die('ERROR:cannot find the file');

echo $str;

?>

Read the contents using file( ) function


An alternative way of reading data from a file is file( ) function, which accepts the name and
path to a file and reads the entire file into an array, with each element of the array representing
one line of the file. Here's an example which reads a file into an array and then displays it
using foreach loop.
Eg ii

<?php

//read file into array

$arr=file('output.txt') or die('ERROR: cannot file file');


// print_r($arr);
foreach($arr as $line)

{
echo $line;

}
?>

Reading remote files contents


All above defined file_get_contents( ) function and file( ) function support reading data
from URLs using either the HTTP or FTP protocols. Here's an example which reads
an HTML file off the Web into an array.

Eg iii

<?php

//read file into array


$arr=file('http://www.google.com') or die('ERROR: cannot file file');
foreach($arr as $line)

echo $line;

?>

In case of slow network links, it's sometimes more efficient to read a remote file in "chunks" to
maximize the efficiency of available network bandwidth.

Read from a file


When reading a file you have the same two primary options that we will look at:

Reading bytes as needed with fread()

Reading the entire file in to a variable with file_get_contents()

READ BYTES

This example will read N number of bytes in to a variable with fread(). In this case, it will read
all the bytes based on the length of the file. You could just read one or two bytes at a time. It will
return FALSE if it fails. You can check if the end of file has been reached with feof().

<?php

$filename = 'test.txt';

$number_of_bytes_to_read = filesize($filename);

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

$contents = fread($file, $number_of_bytes_to_read);

echo $contents;

// You can check for EOF with `feof()`

echo feof($file);
READ ENTIRE FILE AT ONCE

This is more memory intensive but convenient. It is best for smaller files that will not exhauset
the system RAM.

<?php

$contents = file_get_contents('test.txt');

echo $contents;

READ ALL LINES OF A TEXT FILE

To quickly get an array containing each line of a file, use the file() function.

<?php

$lines = file('test.txt'); // Each line will still have it's line ending character

print_r($lines);

Common file tasks

Here are some examples of other common tasks to perform with files like:

 Getting file size

 Checking if a file exists

 Check if a file is a directory

 Get a lock on a file

 Read and write JSON

GET FILESIZE

You can quickly get the size of a file in bytes using the filesize() function.

<?php

echo filesize('hello.txt');
CHECK IF FILE EXISTS

You can easily check if a file exists with the file_exists() function.

<?php

echo file_exists('hello.txt');

GET AN EXCLUSIVE LOCK ON A FILE

This is useful when you want to ensure only one write operation is happening at a time. For
example, if you have a file that stores an integer called hit_counter.txt you will want to make
sure there is no race condition and that multiple writes are not happening at once.

<?php

$file = fopen('safe.txt', 'a');

flock($file, LOCK_EX); // Get exclusive lock on file

// Perform read/write actions while holding the lock

fwrite($file, "Test\n");

flock($file, LOCK_UN); // Release file lock

fclose($file);

fgets( ) function used to read a specific number of bytes from a file. Here's an example which
reads an HTML file using fgets( ) function.

Eg iv

<?php

//read file into array chunks


$fo=fopen('http://www.google.com','r') or die('ERROR: cannot open file');

while(!feof($fo))

$str.=fgets($fp,512);

}
echo $str;

fclose($fo);

?>

Read the external PHP file using include( ) or require( ) function


There are 4 functions to include external PHP files.

1. inculde( )
2. require( )
3. inculde_once( )
4. require_once( )

The include() function in PHP is mostly used to include the code/data of one PHP file
to another file. During this process if there are any kind of errors then this include()
function will display/give a warning but unlike the require() function in which the
execution comes to a halt, the include() function will not stop the execution of the
script rather the script will continue its process.
In order to use the include() function, we will first need to create two PHP files. Then
using the include() function put one PHP file into another one. After that, you will see
two PHP files combined into one HTML file. This include() will not see whether the
code is already included in the specified file, rather it will include the code number of
times the include() is been used.

Example: Assume we have a file called includegfg.php.

<?php
   echo "<p>Visit Again; " . date("Y") . " Geeks for geeks.com</p>
";
?>

We have created a file demo.php. Using the include() method we will include


the  includegfg.php file into the demo.php file.

<html>
<body>
  <h1>Welcome to geeks for geeks!</h1>
  <p>Myself, Mr. Someone</p>
  <p>Thank you</p>
  
  <?php 
    include 'includegfg.php';
  ?>
</body>
</html>

include_once ():
The include_once() function in PHP is mainly used to include one PHP file into another PHP
file. It provides us with a feature that if a code from a PHP file is already included in a
specified file then it will not include that code again. It means that this function will add a file
into another only once. In case this function locates an error then it will produce a warning but
will not stop the execution.
If ABC.php file calls XYZ.php file using include_once() and any error occurs then it will
produce a warning but will not stop the script execution.

Example: Below we have created a sample PHP file called demo.php, which displays the
message “Hello from Geeks for Geeks.”

<?php

   echo "Hello from Geeks for Geeks";

?>

In the following PHP file include_once_demo.php, we have called the  demo.php file twice


using the include_once(), but it will not execute the second call.

<?php
   include_once('demo.php');

   include_once('demo.php');

?>

Difference between include () and include_once ():


include() include_once()
The include() function is used to The include_once () will first check whether a
include a PHP file into another file is already included or not and if it is already
irrespective of whether the file is included then it will not include it again.
included before or not.
This include() function is mainly used This include_once() function is mainly used
where you want to include a certain where you want to include a certain code just
code again and again. for once.
The include() function will execute The include_once() function will not execute
every time it is called in the program. every time it is called (ie. It will not execute if
the file to be included is included before)
Mostly include() function is used to Mostly include_once() function is used to load
load optional template-like files. optional dependencies (classes, functions,
constants).

PHP require() Function: The require () function in PHP is mostly used to include the
code/data of one PHP file to another file. During this process, if there are any kind of errors
then this require() function will display a warning along with a fatal error which will
immediately stop the execution of the script. 
In order to use this, require() function, we will first need to create two PHP files.  Include one
PHP file into another one by using the require() function. The two PHP files are combined
into one HTML file. This require() function will not see whether the code is included in the
specified file before, rather it will include the code as many times the require() function is
used.
Example:

<html>

<body>

    <h1>Welcome to geeks for geeks!</h1>

    <p>Myself, Mr Somebody</p>

      <p>Thank you</p>

      <?php require 'require.php'; ?>

</body>

</html>

//8_require.php

<?php

      echo "<p>visit Again-" . date("Y") 

        . " geeks for geeks.com</p>";


  ?>

PHP require_once() Function: The require_once() function in PHP is used to include one


PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is
already included in a specified file then it will not include that code again if we use
the require_once() function. It means that this function will add a file into another only once.  
In case this function does not locate a specified file then it will produce a fatal error and will
immediately stop the execution.
Example:
 PHP

<?php
    require_once('demo.php');
    require_once('demo.php');
?>

The following code is used in the above PHP code.

<?php
    echo "Hello from Geeks for Geeks";
?>

Difference between require() and require_once():

                                    require()                                                 require_once()
The require() function is used to The require_once() will first check whether a file
include a PHP file into another is already included or not and if it is already
irrespective of whether the file is included then it will not include it again.
included before or not.
This function is mostly used where This function is mostly used where you want to
you want to include a certain code include a certain code just once.
again and again.
 Use require() to load template-like Use require_once() to load dependencies
files. ( classes, functions, constants).
The require() function will execute The require_once() function will not execute
every time it is called. every time it is called (It will not execute if the file
to be included is included before)
Work With Directory PHP
Directory is the collection of related files.

How to create a directory using PHP


Syntax

<?php

mkdir("your_dir_name");

?>

Eg

<?php

mkdir("mydocs");

?>

In the above example in this program we use mkdir()function . Pass the directory name inside
this function to create the directory.

Create a sub directory inside existing directory


Syntax

<?php

mkdir("your_dir_name/your_sub_dir_name");

?>

Eg

<?php

mkdir("mydocs/new updated docs");

?>
In the above example use mkdir( ) function . pass the directory name/sub directory name inside
mkdir() function sub directory create inside the main directory(make sure first must create a
directory).

How to remove(delete) a directory in PHP


Syntax

<?php

rmdir("your_dir_name");

?>

Eg

<?php

rmdir("mydocs");

?>
In the above example We want to delete existing directory. Pass directory name "mydocs" inside
rmdir( ) function. it will delete the directory.

How to rename a directory


Syntax

<?php

rename("your_old_dir_name","new _ dir _name");

?>

Eg

<?php

rename("mydocs","my updated docs");

?>
In the above example if we want to rename a directory name. rename( ) function is used. it
accept two argument first "the existing directory name" and second "new name which replace
first directory name".

How to check existence of directory


Syntax

<?php

echo file_exists("your_dir_name"");

?>

Eg

<?php

echo file_exists("mydocs");

?>
In the above example if we want to check the existence of a directory. file_exist( ) function is
used with (directory name) . if directory exist it gives true("1")

How to get files(contents) from directory


Note first manually store some files inside your directory Syntax

<?php

scandir("your_dir_name"");

?>

Eg

<?php

$files = scandir("mydocs");

print_r($files);
?>

in the above example We get the contents of a directory. use scandir( ) function , directory name
declare inside this. scandir( ) function returns the files in array so stored the return value in a
variable( $files). Now print this using print_r($files) function i.e specially used to print the value
and index of array. it gives an output of an array type with index and their corresponding value.

How to open a directory


Syntax

<?php

opendir("your_dir_name"");

?>

Eg

<?php

$od = openddir("mydocs");

?>

In the above example if we open the directory use opendir( ) function with directory name
("mydocs"). store in variable $files because these open directory variable is going to used in
further communication(for reading the contents).

How to read all files from a directory


Syntax

<?php

$files = readdir($od);

?>
Eg

<?php

$od = opendir("mydocs");

while($files = readdir("mydocs"))

echo $files."<br/>";

?>

In the above example first we open the directory of name("mydocs") and stores the values in
$files(in previous example). Now start to read the file using readdir( ) function till the file ends
because here we are using while( ) loop. To display the file name we have used echo statement in
while loop.

PHP copying a file

To copy a file, we can use copy() function in PHP. Let’s suppose we have one file with some
content, we need to create another file somewhere in the project. Now the copy() function will
copy the content of the first file to another. Once the file is copied you will get true otherwise
false, and accordingly, you can set the output message.

The following example shows how to copy the test1.txt file to test2.txt file.

Note: both the files are at the same location in the below script. You can change it and add the
location with the file name.
<?php
$first = 'test1.txt';
$second = 'test2.txt';
if(copy($first,$second))
echo 'The file was copied successfully';
else
echo 'An error occurred';
?>

PHP renaming a file

To rename a file, we can use rename() function in PHP. This function rename the file with given
name as in the below code.

For example, to rename the test1.txt file to test2.bak file, you use the following code:

<?php
$first = 'test1.txt';
$second = 'test2.bak';
if(rename($first,$second)){
echo 'file renamed successfully';
}else{
echo 'An error occurred';
}

Notice that the  rename() function returns  true if the file is renamed successfully,
otherwise it returns  false

PHP deleting a file


To delete a file, we can use unlink() function in PHP. you just need to pass the file name in
unlink() function with the correct file path. The function returns true if successful or false if
failure.

<?php
$file = 'test1.txt';
if(unlink($file)){
echo "file deleted";
}else{
echo "An error occurred";
}

Notice it is a good practice to check the files on the server directory using file_exists()
function before using the copy(), rename() and unlink() functions because if file not found,
that raises warning-level errors which can create problems in the project if you have
some condition based output.

Appendix
Common PHP File and Directory Functions
PHP Comes with a whole range of file and directory manipulation functions.

These Predefined Function allow you to check file attributes like copy, move delete etc.

Sr Function What it Does


No
1 file_exists() Tests if a file or directory exists or not. This function work for file and
Directory Both
2 filesize() Returns the size of a file in bytes
3 realpath() Returns the absolute path of a file
4 pathinfo() Returns an array of information about a file and its path
5 stat() Provides information on file attributes and its permissions
6 is_readable() Tests if a file is readable
7 is_writable() Tests if a file is writable
8 is_executable Tests if a file is executable
9 fopen() Open a file(Write mode of file why want to open)
10 fread() Read a file(Files must be opened in read mode)
11 fgets() Read first line of a file(File must be opened in read mode)
12 fgetc() Read first Character of a file(File must be opened in read mode)
13 fwrite() Write Contents/information inside a file(File must be opened in write
mode)
14 file_put_contents() Write Contents/information inside a file(it accept 2 parameters, file
name and content)
15 file_get_contents() Read information from a file(it accpet 1 parameters file name only)
16 is_file() Tests if a directory is a file
17 copy() Copies a file
18 rename() Rename a file
19 unlink() Deletes a file
20 include() Reads an external file into the current PHP Script
21 require() Reads an external file into the current PHP Script
22 include_once() Reads an external file into the current PHP Script(One time only)
23 require_once() Reads an external file into the current PHP Script(One time only)
24 fclose() Close a open file
25 is_dir() Tests if a directory entry is a directory
26 is_dir() Tests if a directory entry is a directory
27 mkdir() Creates a directory
28 rmdir() Removes a directory
29 opendir() Open a directory
30 readdir() Read a directory(It reads a signle file at a time, so must use loop to
read entire directory)
31 scandir() Read a directory(Return result in array format)

You might also like