Chapter 3 - Files and Directories
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:
: * ? " < > | \ /
<?php
$fo=fopen(filename, mode, include_path, context);
?>
Parameter Description
Mode Required. Specifies the type of access you require to the file/stream.
Possible values:
<?php
$file = fopen("test.txt", "r");
fclose($file);
?>
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
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
<?php
?>
Parameter Description
<?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
$fo=fopen("output.txt","w");
fwrite($fo,$data);
flock($fo,LOCK_UN) or die('ERROR:cannot unlock file');
fclose($fo);
?>
<?php
$fo=fopen("output.txt","w");
fputs($fo,$data);
fclose($fo);
?>
Syntax
file_get_contents(path, include_path, context, start, max_length)
Parameter Description
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
echo $str;
?>
<?php
{
echo $line;
}
?>
Eg iii
<?php
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 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);
echo $contents;
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;
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);
Here are some examples of other common tasks to perform with files like:
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');
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
fwrite($file, "Test\n");
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
while(!feof($fo))
$str.=fgets($fp,512);
}
echo $str;
fclose($fo);
?>
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.
<?php
echo "<p>Visit Again; " . date("Y") . " Geeks for geeks.com</p>
";
?>
<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
?>
<?php
include_once('demo.php');
include_once('demo.php');
?>
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>
<p>Myself, Mr Somebody</p>
<p>Thank you</p>
</body>
</html>
//8_require.php
<?php
<?php
require_once('demo.php');
require_once('demo.php');
?>
<?php
echo "Hello from Geeks for Geeks";
?>
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.
<?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.
<?php
mkdir("your_dir_name/your_sub_dir_name");
?>
Eg
<?php
?>
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).
<?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.
<?php
?>
Eg
<?php
?>
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".
<?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")
<?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.
<?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).
<?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.
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.
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';
?>
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
$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.