You are on page 1of 32

File Handling with PHP

PHP Workshop

Files and PHP


File Handling
Data Storage
Though slower than a database

Manipulating uploaded files


From forms

Creating Files for download

PHP Workshop

Open/Close 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.

PHP Workshop

File Open Modes


r

Open for reading only. Start at beginning of


file.
r+ Open for reading and writing. Start at
beginning of file.
w
Open for writing only. Remove all previous
content, if file doesnt exist, create it.
a
Open writing, but start at END of current
content.
a+ Open for reading and writing, start at END
and create file if necessary.
PHP Workshop

Checking for Existence

if (file_exists("names.txt"))
echo "names.txt exists\n";

names.txt exists

PHP Workshop

File Open/Close Example


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

PHP Workshop

Now what..?
If you open a file to read, you can use
more in-built PHP functions to read data..
If you open the file to write, you can use
more in-built PHP functions to write..

PHP Workshop

Reading Data
There are two main functions to read data:
fgets($handle,$bytes)
Reads up to $bytes of data, stops at newline

fread($handle,$bytes)
Reads up to $bytes of data, stops at EOF.

So, whats the difference between fgets()


and fread()?
PHP Workshop

Example of using fgets()


<?php
$handle =
fopen('/tmp/readfile.txt', "r");
$contents = '';
if ($handle) {
while (!feof($handle)) {
$contents =
fgets($handle, 10);
echo $contents;
exit;
}
fclose($handle);
}
?>
PHP Workshop

Assume readfile.txt has contents:


abcdefg
123456789
So whats the output?
a) abcdefg
b) abcdefg
123456789
c) abcdefg
123

d) abcdefg
12
e) None of above

Example of using fread()


<?php
$handle =
fopen('/tmp/readfile.txt', "r");
$contents = '';
if ($handle) {
while (!feof($handle)) {
$contents .=
fread($handle, 10);
echo $contents;
exit;
}
fclose($handle);
}
?>

Assume readfile.txt has the


following contents:
abcdefg
123456789
So whats the output?
a) abcdefg
b) abcdefg
123456789
c) abcdefg
123
d) abcdefg
1
e) None of above

PHP Workshop

Summary of fgets() and fread()


fgets() reads one line per time
It gets a line from file pointer

fread() will first read the entire file, then


determine the needed bytes afterward.
You can determine which method to use,
based on how you want to read the file.
If its a big file, we suggest you to use fgets()

PHP Workshop

Reading Data
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.

PHP Workshop

Data Reading Example


$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}

fclose($handle);

PHP Workshop

Data Reading Example


$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}

Open the file and assign the resource to $handle

fclose($handle);

PHP Workshop

Data Reading Example


$handle = fopen('people.txt', 'r');
while (!feof($handle))
(!feof($handle)) {{
while
echo
echo fgets($handle,
fgets($handle, 1024);
1024);
echo
echo '<br
'<br />';
/>';
}
}

fclose($handle);

PHP Workshop

While NOT at the end of the file, pointed


to by $handle,
get and echo the data line by line

Data Reading Example


$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
Close the file

fclose($handle);
fclose($handle);

PHP Workshop

File Open shortcuts..


There are two shortcut functions that dont
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.

PHP Workshop

Writing Data
To write data to a file use:
fwrite($handle,$data)
Write $data to the file.

PHP Workshop

Data Writing Example


$handle = fopen('people.txt', 'a');
fwrite($handle, \nFred:Male);
fclose($handle);

PHP Workshop

Data Writing Example


Open file to append data (mode 'a')

$handle
$handle == fopen('people.txt',
fopen('people.txt', 'a');
'a');
fwrite($handle,
fwrite($handle, \nFred:Male);
'\nFred:Male');
fclose($handle);

PHP Workshop

Write new data (with line


break after previous data)

Other File Operations


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
PHP Workshop

Locking files
<?php
$fh = fopen(testfile.txt, r+) or die(Failed to open file);
$text = fgets($fh);
if(flock($fh, LOCK_EX)){
fseek($fh, 0, SEEK_END);
fwrite($fh, $text) or die(could not write to file);
flock($fh, LOCK_UN);
}
fclose($fh);
echo File testfile.txt successfully updated;
?>

PHP Workshop

$_FILES usage

$_FILES => //HTTP File Upload variables


$_FILES[file][name]: The file name
$_FILES[file][type]: The file type
$_FILES[file][size]: The file size (in byte)
$_FILES[file][tmp_name]: The temporary
file saved on the server
$_FILES[file][error]: The error code
during the upload
PHP Workshop

Uploading file
<html><head><title>PHP form upload</title></head><body>
<form method='post' action='question2.php' enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='10' />
<input type='submit' value='Upload' />
</form>
<?php
if($_FILES){
$name = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'],$name);
echo "Uploaded image '$name'<BR><img src='$name'/>";
}
?>

PHP Workshop

Common multimedia types on the network

application/pdf
image/gif
multipart-form-data
text/xml
application/zip
image/jpeg
text/css video/mpeg
audio/mpeg

PHP Workshop

image/png
text/html
video/mp4
audio/x-wav
image/tiff
text/plain
video/quicktime

Dealing With Directories


Open a directory
$handle = opendir('dirname');
$handle 'points' to the directory

Read entry from directory handle


readdir($handle)
Returns name of next file in directory
Files are sorted as on filesystem

Close a directory
closedir($handle)
Closes directory 'stream'
PHP Workshop

Directory Example
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}

closedir($handle);

PHP Workshop

Directory Example
$handle
$handle == opendir('./');
opendir('./');
Open current directory

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


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

closedir($handle);

PHP Workshop

Directory Example
$handle = opendir('./');
while(false !==
!== ($file=readdir($handle)))
($file=readdir($handle)))
while(false
{ {
echo
"$file<br
/>";
echo
"$file<br
/>";
} }

closedir($handle);

PHP Workshop

While readdir() returns a name, loop


through directory contents, echoing
results

Directory Example
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}

closedir($handle);
closedir($handle);
Close the directory stream

PHP Workshop

Other Directory Operations


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

PHP Workshop

Review

Can open and close files.


Can read a file line by line or all at one go.
Can write to files.
Can upload a file into the server
Can open and cycle through the files in a
directory
Introduce some linux scripts related to the
filesystems
PHP Workshop

You might also like