Internet Programming II
Chapter 3
Files and Directories in PHP
Outlines
Reading files/ Directories
File Functions
Reading a file
Writing a file
Locking files
Copying files
Creating directories
Renaming and Deleting Files and Directories
File Uploads in PHP
PHP File Inclusions
2
Reading files/ Directories
Files and directories have three levels of access:
User,
Group and
Other.
The three typical permissions for files and directories
are:
Read (r),
Write (w) and
Execute (x)
3
Cont’d
A stream is a channel used for accessing a resource that
we can read from and write to.
o The input stream reads data from a resource (such as a
file) and
o The output stream writes data to a resource.
4
File Functions
fopen() function :- used to open a file.
Syntax:-
variable= fopen(“text file”, “mode”);
where mode mean r, r+, w, w+ etc.
filesize() function:- used to Get the file's length.
syntax:- filesize($filename);
fread() function:-used to Read the file's content.
syntax:-
variable = fread( filename, filesize);
fclose() function:- used to Close the file.
Syntax:-
fclose(file name that contains the opened files);
5
File modes
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
r+
the 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
w+ beginning of the file. and truncates the file to zero length. If files 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
a+
the file. If files does not exist then it attempts to create a file.
6
Reading a file
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 = "a.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>
7
Writing a File
A new file can be written or text can be appended to an
existing file using the PHP function .
The functions require 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.
Syntax:
fwrite(file we write on it, string what we write[,length of string]);
8
Cont’d
Example:
<?php
$filename = "D/2007/php/ch3.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_exists($filename)){
$filesize = filesize($filename);
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg);}
else{ echo ("File $filename does not exist" );}
9 ?></body></html>
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_SH to acquire a shared lock (reader).
LOCK_EX to acquire an exclusive lock (writer).
LOCK_UN to release a lock (shared or exclusive).
10
Cont’d
Example:
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) // acquire an exclusive lock
{
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
}
else
{
echo "Couldn't get the lock!";
}
fclose($fp);
?>
11
Copying Files
Use the copy() function to copy a file with PHP.
The function returns a value of true if it is successful or
false if it is not.
The syntax for the copy() function is:
copy(source, destination);
For the source and destination arguments:
Include just the name of a file to make a copy in the
current directory, or Specify the entire path for each
argument.
12
Cont’d
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
echo ("<p>The directory does not exist!</p>");
}
else
echo ("<p>The file does not exist!</p>");
13
Creating Directories
The basic functions/methods that are used to open
directories, read directories and close directories are;-
opendir(), readdir() and closedir().
The following example is used to demonstrate how gare
directory contents of files are displayed.
<?php
$Dir = "C:\\gare";
$DirOpen = opendir($Dir);
while ($CurFile = readdir($DirOpen)) {
echo $CurFile . "<br />";}
closedir($DirOpen);
?>
14
Cont’d
Use the mkdir()function to create a new directory.
Example :-
mkdir("bowlers");
mkdir("..\\tournament");
mkdir("C:\\PHP\\utilities");
15
Renaming and Deleting Files and Directories
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.
The syntax is:
rename(old_name, new_name);
Use unlink() function to delete files and
Use rmdir() function to delete directories.
Use the file_exists() function to determine whether a file or
directory name exists.
16
File Uploads in PHP
Files are uploaded through an HTML form using the "post" method
and enctype attribute with value of "multipart/form-data".
The file input field creates a browser button for the user to navigate to
the appropriate file to upload.
Syntax:-
<form method="post" action= " "enctype="multipart/form-data">
<input type="file" name="picture_file" />
</form>
You can specify the maximum number of bytes allowed in the uploaded file
by using MAX_FILE_SIZE attribute of a hidden form field.
Example:<input type = “hidden” name=“MAX_FILE_SIZE” value=“1000”>
17
Cont’d
Example:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">File name:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit"
value="Submit" />
</form>
</body>
</html>
18
Cont’d
//save this file as "upload_file.php"
<?php
if($_FILES["file"]["error"] > 0)
{
echo "Error:".$_FILES["file"]["error"]."<br/>";
}
else
{
echo "Upload: ".$_FILES["file"]["name"]."<br/>";
echo "Type: ".$_FILES["file"]["type"] ."<br/>";
echo "Size: ".($_FILES["file"]["size"]/1024) . "
Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
19
PHP File Inclusions
In PHP , we can include the content of a PHP file into
another PHP file before the server executes it.
This is done by functions such as include()and
require()function statements.
Syntax:-
include 'filename'; or
require 'filename';
20
Cont’d
The two functions are identical in every way, except how
they handle errors.
⁃ The include() function generates a warning (but the script
will continue execution) while
⁃ the require() function generates a fatal error (and the script
execution will stop after the error).
These two functions are used to create functions, headers,
footers, or elements that can be reused on multiple pages.
21
Cont’d
The include () Function:
The include()function takes all the text in a specified file
and copies it into the file that uses the include function.
Example:- let's we have a standard menu file that should be
used on all pages that is saved as "menu.php“.
<html>
<body>
<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">Contact Us</a>
</body>
</html>
22
Cont’d
Now lets have home page code that includes "menu.php" file
as follows:
//save this file as "Home.php"
<html>
<head><title>Include file example</title><head>
<body>
<?php
include("menu.php");
?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
When we run "home.php" we get this result.
23
Cont’d
The require() Function:
The require()function is identical to include (), they
only handle errors differently.
The include() function generates a warning (but the
script will continue execution) while
The require()function generates a fatal error (and the
script execution will stop after the error).
24
Cont’d
Example <html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Hello World!
Notice that the echo statement is still executed! This is because a Warning
does not stop the script execution.
25
Cont’d
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
The echo statement was not executed because the script execution stopped after the
26 fatal error.
Cont’d
It is recommended to use the require() function instead of
include(), because scripts should not continue executing if
files are missing or misnamed.
There are also the include_once() and require_once()
functions.
These functions will not re-include the file if it has already
been called.
27
Questions?
28