Professional Documents
Culture Documents
Chapter 8
Chapter 8
Chapter 8
Introduction
Opening and Closing File Streams
Read from files
Write to files
Rename and delete files and directories
Create directories
Upload files
Introduction
3
Location of the file pointer when the fopen() function uses a mode
argument of “r+”
Name of Book
…cont’d…
8
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
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
fclose($handle);
File Open shortcuts..
13
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
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\”.
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('./');
closedir($handle);
Other Directory Operations
23
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