Chapter 4
Chapter 4
Chapter Four
Read (r)
Write (w)
Execute (x)
A stream is a channel used for accessing a resource that you can read from and write to. The
input stream reads data from a resource (such as a file) while the output stream writes data to a
resource. In file operation, we do have the following steps or procedures:-
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
Page 1 of 13
Chapter Four Files and Directories
} fclose($handle);
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.
Opens the file for reading and writing. Places the file pointer at the beginning of the
r+
file.
Opens the file for 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 attempts to create a
file.
Opens the file for reading and writing only. Places the file pointer at the beginning
w+ of the file and truncates the file to zero length. If file does not exist then it attempts
to create a file.
Opens the file for writing only. Places the file pointer at the end of the file. If files
a
does not exist then it attempts to create a file.
Opens the file for reading and writing only. Places the file pointer at the end of the
a+
file. If files does not exist then it attempts to create 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.
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>
Page 2 of 13
Chapter Four Files and Directories
<?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>
Note That:- There are two ‘shortcut’ functions that don’t require a file to be opened:
$lines = file($filename) :Reads entire file into an array with each line a separate entry in
the array.
$str = file_get_contents($filename) :Reads entire file into a single string.
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_exists() function which takes file name as an
argument. See the following example how open file, write in file and close files
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
Page 3 of 13
Chapter Four Files and Directories
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 that:-
The file_put_contents() function can also writes or appends a text string to a file, doesn’t
need to use fopen or fclose. If no data was written to the file, the function returns a value
of 0 which can determine if data was successfully written to the file. The FILE_APPEND
constant appends data to any existing contents in the specified filename instead of
overwriting it
Page 4 of 13
Chapter Four Files and Directories
In general;
Page 5 of 13
Chapter Four Files and Directories
Example 3:
<?php
Locking Files
To prevent multiple users from modifying a file simultaneously use the flock() function
The syntax for the flock() function is:flock($handle, operation) where operations could
be LOCK_EX, LOCK_NB, etc. The followings are possible file lock functions and their
descriptions.
Page 6 of 13
Chapter Four Files and Directories
Copying Files
Example:-
if (file_exists(“a.txt”)) {
if(is_dir(“history”)) {
if (copy(“a.txt”,“history\\b.txt”))
echo “<p>File copied successfully.</p>”;
else
echo “<p>Unable to copy the file!</p>”; }
else
Page 7 of 13
Chapter Four Files and Directories
Example 1:- This is used to demonstrate how gare directory contents of files are displayed.
<?php
$Dir = "C:\\gare";
$DirOpen = opendir($Dir);
closedir($DirOpen);
?>
Example 2:- The following example shows how the content of the current directory opened
$handle = opendir('./');
closedir($handle);
There are also different functions which have different purposes. Some of them are listed below:-
Page 8 of 13
Chapter Four Files and Directories
To create directories:-
Use the mkdir() function to create a new directory. To create a new directory pass just the name
of the directory we want to create to the mkdir() function.
Example
mkdir(“bowlers”);
mkdir(“..\\tournament”);
mkdir(“C:\\PHP\\utilities”);
Warning will appear if directory already exists
Example:-
<?php
$Dir = "C:\\Wamp";
if(is_dir($Dir)) {
echo "<table border='1‘ width='100%'>";
echo "<tr><th>Filename</th><th>File Size</th>
<th>File Type</th></tr>";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry) {
echo "<tr><td>$Entry</td><td>" . filesize($Dir . "\\"
. $Entry) . "</td><td>" . filetype($Dir . "\\"
. $Entry) . "</td></tr>";
}
echo "</table>";
Page 9 of 13
Chapter Four Files and Directories
}
else echo "<p>The directory does not exist.</p>";
?>
Use the rename() function to rename a file or directory with PHP. This function returns a
value of true if it is successful or false if it is not
Files are uploaded through an HTML form using the “post” method and enctype attribute with
value of “multipart/form-data,” which instructs the browser to post multiple sections – one for
regular form data and one for the file contents. The file input field creates a browser button for
the user to navigate to the appropriate file to upload
<form method=”post” action=” ” enctype= multipart/form-data >
<input type="file" name="picture_file" />
</form>
The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum
number of bytes allowed in the uploaded file and it must appear before the file input field.
When the form is posted, information for the uploaded file is stored in the $_FILES auto global
array.
Page 10 of 13
Chapter Four Files and Directories
$_FILES['picture_file']['tmp_name'] contents
c. // Contains the name of the original file
$_FILES['picture_file']['name']
d. // Contains the size of the uploaded file in bytes
$_FILES['picture_file']['size']
e. // Contains the type of the file
$_FILES['picture_file']['type']
Example:-The following HTM code below creates an upload form. This form is having
method attribute set to post and enctype attribute is set to multipart/form-data
<html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=””/><br />
<input type="submit" value="Upload File" />
</form></body></html>
<?php
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
if( copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
echo "file uploded successfully";
else
die("unable to upload!");
?>
<h2>Uploaded File Info:</h2>
<ul><li>Sent file: <?php echo $_FILES['photo']['name']; ?>
<li>File size: <?php echo $_FILES['photo']['size']; ?> bytes
<li>File type: <?php echo $_FILES['photo']['type']; ?>
</ul><a href=<?php echo $target; ?>>Click here to open</a></body></html>
Example2: Inserting the above file to a database: First create a table with two columns such as
id(int auto increment) and file_path (varchar(50)).
<?php
$server="localhost";
Page 11 of 13
Chapter Four Files and Directories
$dbuser="root";
$dbpass="";
$dbname="sims";
$connection = mysql_connect($server, $dbuser, $dbpass) or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $connection) or die("Couldn't select database");
?><html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=""/><br />
<input type="submit" value="Upload File" name="upload" />
</form></body></html>
<?php
if(isset($_POST['upload']))
{
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
//uploading a file into uploadedfiles folder
if(copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
{
//inserting a file to a file table in sims database
$result = mysql_query("INSERT INTO file(file_path) VALUE ('$target')");
if(!$result)
{
echo "File uploaded successfully";
}
//retrieving records from file table
$result = mysql_query("select * from file");
echo "<table border=1><tr><th>Id</th><th>File</th></tr>";
while($row=mysql_fetch_array($result))
{
echo "<tr><th>".$row['id']."</th><th><a href='".$row['file_path']."'>".$row['file_path']."</a></th></tr>";
}
echo "</table>";
}else
Page 12 of 13
Chapter Four Files and Directories
Page 13 of 13