Chapter 8

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

CHAPTER 8

Files and Directories


Outline
2

 Introduction
 Opening and Closing File Streams
 Read from files
 Write to files
 Rename and delete files and directories
 Create directories
 Upload files
Introduction
3

 To work with files and directories we should first know file


types and permissions
 File type – affects how information is stored in files and
retrieved from them
 Binary files
 Text files
 Permission – determines the actions that a specific user can
or cannot perform on a file or directory
 Read(r)
 Write (w)
 Execute (x)
Opening and Closing File Streams
4

 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)
 The output stream writes data to a resource
1. Open the file stream with the fopen() function
2. Write data to or read data from the file stream
3. Close the file stream with the fclose() function
…cont’d…
5

 A handle is a special type of variable that PHP uses


to represent a resource such as a file
 A file is opened with fopen() as a “stream”, and PHP
returns a ‘handle’ to the file that can be used to
reference the open file in other functions.
 Each file is opened in a particular mode.
 A file is closed with fclose() or when your script ends.
 A file pointer is a special type of variable that refers
to the currently selected line or character in a file
File Open Modes
…cont’d…
7

$handle = fopen(“bowlers.txt”, “r+”);

Location of the file pointer when the fopen() function uses a mode
argument of “r+”

Name of Book
…cont’d…
8

$handle = fopen(“bowlers.txt”, “a+”);

Location of the file pointer when the fopen() function uses a mode
argument of “a+”

Name of Book
Example
9

<?php
// open file to read
$toread = fopen(‘some/file.txt’,’r’);
// open (possibly new) file to write
$towrite = fopen(‘some/file.txt’,’w’);
// close both files
fclose($toread);
fclose($towrite);
?>
Reading from files
10

 There are two main functions to read data:


 fgets($handle,$bytes)
 Reads up to $bytes of data, stops at newline or end of
file (EOF)
 fread($handle,$bytes)
 Reads up to $bytes of data, stops at EOF.
…cont’d…
11

 We need to be aware of the End Of File (EOF)


point..
 feof($handle)
 Whether the file has reached the EOF point. Returns
true if have reached EOF.
Example
12

$handle = fopen('people.txt', 'r');

while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}

fclose($handle);
File Open shortcuts..
13

 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.
Writing to files
14

 To write data to a file use:


 fwrite($handle,$data)
 Write $data to the file.
 file_put_contents(($handle,$data)
 function writes or appends a text string to a file
Example
15

$handle = fopen('people.txt', 'a');

fwrite($handle, “\nFred:Male”);

fclose($handle);
Other File Operations
16

 Delete file
 unlink('filename');
 Rename (file or directory)
 rename('old name', 'new name');
 Copy file
 copy('source', 'destination');
 And many, many more!
 www.php.net/manual/en/ref.filesystem.php
Handling Magic Quotes
17

 Magic quotes automatically adds a backslash (\) to


any:
 Single quote (')
 Double quote (”)
 NULL character contained in data that a user submits
to a PHP script
My best friend's nickname is “Bubba”
My best friend\'s nickname is \”Bubba\”
…cont’d…
18

 The following are magic quote directives

 Disable magic quotes in your php.ini configuration


file and instead manually escape the strings with the
addslashes() function
…cont’d…
19

 addslashes() function
 Accepts a single argument representing the text string
you want to escape and returns a string containing the
escaped string
$Nickname = addslashes($_GET['nickname']);
echo $Nickname;
// My best friend\'s nickname is \”Bubba\”.

 With magic quotes enabled:


My best friend\\\'s nickname is \\\”Bubba\\\”
…cont’d…
20

 stripslashes() Function
 Removes slashes that were added with the
addslashes() function
 To prevent the display of escaped characters, use the
stripslashes() function with the text you want
to print
echo stripslashes($Nickname);
// My best friend's nickname is ”Bubba”.
Dealing With Directories
21

 Open a directory
 $handle = opendir('dirname');
 $handle 'points' to the directory
 Read contents of directory
 readdir($handle)
 Returns name of next file in directory
 Files are sorted as on filesystem
 Close a directory
 closedir($handle)
 Closes directory 'stream'
Directory Example
22

$handle = opendir('./');

while(false !== ($file=readdir($handle)))


{
echo "$file<br />";
}

closedir($handle);
Other Directory Operations
23

 Get current directory


 getcwd()
 Change Directory
 chdir('dirname');
 Create directory
 mkdir('dirname');
 Delete directory (MUST be empty)
 rmdir('dirname');
 And more!
 www.php.net/manual/en/ref.dir.php
Handling file upload
24

 A PHP script can be used with a 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.
 temporary directory that is used for file uploads
is upload_tmp_dir
…cont’d…
25

 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
 Default size is 2M.
 You can edit these based on your requirement.
…cont’d…
26

 When you create a form for file upload:


 Add a form attribute ‘enctype’ with value
‘multipart/form-data’
 ‘multipart/form-data’ is MIME (Multipurpose Internet
Mail Extension) or content type
 Create an input with type ‘file’ with name attribute
 Create a button

<form enctype=“multipart/form-data” method=“post”>


Sample file:<input type=“file” name=“myfile” >
…cont’d…
27

 In the PHP script:


 Use a two dimensional supper global array
$_FILES[myfile][xxx] to handle file in php
 xxx can be one of the following:
 name-represents filename
 type- represents file type or mime
 size- represents the size of file
 error- represents the error code from upload
 tmp_name-represents temporary name on server
…cont’d…
28

 Common MIME list


Functions to be used
29

 is_uploaded_file()
 Used to test if a file is uploaded or not
 Accepts one parameter (the uploaded file name)
 Returns 1 on success
 move_uploaded_file(tmp,perm)
 Used to move file to permanent location for later access
 Takes two parameters
 Temporary name and Destination name
 Returns 1 on success
Example
30

<?php // upload.php
echo <<<_END
<html><head><title>PHP Form Upload</title></head><body>
<form method='post' action='upload.php‘
enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='10'>
<input type='submit' value='Upload'>
</form>
_END;
…cont’d…
31

if ($_FILES)
{
$name = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'],
$name);
echo "Uploaded image '$name'<br><img src='$name'>";
}
echo "</body></html>";
?>
For ANY problem during upload
32

 Check the following in php.ini


 file_uploads = On | Off [on]
 max_input_time = integer [60]
 max_file_uploads = integer [20 simultaneous uploads]
 memory_limit = integerM [16M]
 post_max_size = integerM [8M]
 upload_max_filesize = integerM [2M]
 should be less than post_max_size
Exercise
33

 Create a php file program to receive a file upload


from an html form and do the following:
 Check the file type and display it
 Check the file size and display it
 Read the content of the file and display it
 Improve the above php file to do the following:
 Restrict the file type to txt only
 Restrict the file size to 1MB only
34 THE END

You might also like