You are on page 1of 23

Chapter 5 – part 2

Files and Directories


Contents

Opening files writing to a file

Looking a file reading a file content

Handling file upload

Working with directories

CoSc 3101 – Internet Programming 2


File Handling
 File handling is an important part of any web
application.
 You often need to open and process a file for different
tasks.
 PHP has several functions for creating, reading,
uploading, and editing files.

CoSc 3101 – Internet Programming 3


Opening File
 readfile() function reads file & writes it to the output buffer
returns the number of bytes read on success
 Assume we have a text file called “text.txt", stored on the
server, that looks like this:
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
XML = EXtensible Markup Language
<?php
echo readfile(“text.txt");
?>
 readfile() function is useful if all you want to do is open up a
file and read its contents
CoSc 3101 – Internet Programming 4
File Open
 fopen() – better method to open files - gives more options
than readfile()
<?php
$myfile = fopen(“text.txt", "r") or die("Unable to open
file!");
echo fread($myfile,filesize(" text.txt"));
fclose($myfile);
?>
 first parameter of fopen() contains name of the file to be opened
 second parameter specifies in which mode file should be opened
 The following generates a message if the fopen() function is
unable to open the specified file

CoSc 3101 – Internet Programming 5


Cont’d
 file may be opened in one of the following modes
Mode Description
s
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
CoSc 3101 – Internet Programming 6
Read File
fread() function reads from an open file
Syntax:
fread($myfile,filesize(“text.txt"));
 first parameter contains name of the file to read from and
 second parameter specifies the maximum number of
bytes to read
This code reads the “text.txt" file to the end:

CoSc 3101 – Internet Programming 7


Close File
 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!
 requires the name of the file (or a variable that holds the filename)
we want to close
 Syntax:
fclose($myfile);
<?php
$myfile = fopen(“text.txt", "r");
// some code to be executed....
fclose($myfile);
?>
CoSc 3101 – Internet Programming 8
Delete File
 unlink() – used to destroy (delete) a file
 If you unlink a file, you are effectively causing the system to
forget about it or delete it!
 Before you can delete (unlink) a file, you must first be sure
that it is not open in your program. Use the fclose function
to close down an open file.
 Syntax:
unlink($myfile);

$my_file = 'file.txt';
unlink($my_file);

CoSc 3101 – Internet Programming 9


Read Single Line
fgets() - read a single line from a file
Example:
<?php
$myfile = fopen(“text.txt", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>

CoSc 3101 – Internet Programming 10


Check End-Of-File
 feof() function checks if the "end-of-file" (EOF) has
been reached
 useful for looping through data of unknown length
 Example: read file line by line, until end-of-file is
reached:
<?php
$myfile = fopen(“text.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
if (feof($file)) echo "End of file";
fclose($myfile);
?>
CoSc 3101 – Internet Programming 11
Read Single Character
 fgetc() – used to read a single character from a file
 Example: read file character by character, until end-of-
file is reached
<?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); <?php
$file = fopen("test2.txt","r");
} echo fgetc($file);
fclose($myfile); fclose($file);
?>
?>

CoSc 3101 – Internet Programming 12


File Create
 fopen() – 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:
$myfile = fopen("testfile.txt", "w")

CoSc 3101 – Internet Programming 13


Write to File
 fwrite() – 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
 Example: write couple of names into a new file
<?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);
CoSc 3101 – Internet Programming 14
File Upload
 PHP script can be used with HTML form to allow users to
upload files to the server
 Initially files are uploaded into a temporary directory and
then relocated to a target destination by a PHP script
 Information in the phpinfo.php page describes the
temporary directory that is used for file uploads as
upload_tmp_dir and the maximum permitted size of files
that can be uploaded is stated as upload_max_filesize
 These parameters are set into PHP configuration file php.ini

CoSc 3101 – Internet Programming 15


Cont’d
 The process of uploading a file follows these steps
 The user opens the page containing a HTML form featuring a text
files, a browse button and a submit button.
 The user clicks the browse button and selects a file to upload from
the local PC.
 The full path to the selected file appears in the text filed then the
user clicks the submit button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's
action attribute checks that the file has arrived and then copies the
file into an intended directory.
 The PHP script confirms the success to the user.
 An uploaded file could be a text file or image file or any
document.
CoSc 3101 – Internet Programming 16
Creating an Upload Form
 form needs an attribute enctype set to multipart/form-data. It
specifies which content-type to use when submitting the form
<table width="500" border="0" align="center" cellpadding="0"
cellspacing="1" bgcolor="#CCCCCC">
<tr><form action="upload_ac.php" method="post"
enctype="multipart/form-data" name="form1"
id="form1"><td><table width="100%" border="0"
cellpadding="3" cellspacing="1"
bgcolor="#FFFFFF"><tr><td><strong>Single File Upload
</strong></td></tr><tr><td>Select file <input
name="fileToUpload" type="file" id="fileToUpload" size="50"
/></td></tr><tr><td align="center"><input type="submit"
name="submit" value="Upload"
/></td></tr></table></td></form></tr></table>
CoSc 3101 – Internet Programming 17
Creating an Upload Script
 global PHP variable called $_FILES - an associate double
dimension array and keeps all the information related to uploaded file
 So if the value assigned to the input's name attribute in
uploading form was file, then PHP would create the
following five variables:
 $_FILES['file']['tmp_name']- uploaded file in the temporary
directory on the web server  temporary file name
 $_FILES['file']['name'] - actual name of the uploaded file
 $_FILES['file']['size'] - size in bytes of the uploaded file
 $_FILES['file']['type'] - MIME type of the uploaded file
 $_FILES['file']['error'] - error code associated with this file
upload

CoSc 3101 – Internet Programming 18


Cont’d
<?php
uploader.php
$target_dir = "/Users/ADDI/Desktop/upload/";
$file_name = basename($_FILES["fileToUpload"]['name']);//returns filename from
path
$target_file = $target_dir . $file_name;
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);//The pathinfo()
funciton returns an array that contains information about a path.
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check != false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
CoSc 3101 – Internet Programming 19
Cont’d
// Check if file already exists
uploader.php
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
} CoSc 3101 – Internet Programming 20
Cont’d
// Check if $uploadOk is set to 0 by an error
uploader.php
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} // if everything is ok, try to upload file
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". $file_name. " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?><html><head><title>Uploading Complete</title></head>
<body> <h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul> </body> </html>
CoSc 3101 – Internet Programming 21
Cont’d
PHP Script explained:
 $target_dir = "uploads/" - specifies the directory where
the file is going to be placed
 $target_file specifies the path of the file to be
uploaded
 $uploadOk=1 is not used yet (will be used later)
 $imageFileType holds the file extension of the
file
 Next, check if the image file is an actual image or
a fake image

CoSc 3101 – Internet Programming 22


Thank You For your
Patience!

You might also like