The ftell() Function—Finding the Current Position in a File
If you have read some data from a file and want to keep track of where you were in the file when you stopped reading,
the ftell() function will return the current byte position, the number of bytes from the beginning of the file, and
where the next read operation will start. This can be used in conjunction with the seek() function to return to the
correct position in the file. (If you are using text mode, the carriage return and linefeed translation will be part of the
byte count.)
Format
int ftell ( resource handle )
%
Example:
$filehandle("myfile", "r"); $contents=fgets($filehandle, 1024); echo ftell(
$filehandle); // Current read postion in bytes, //
starting at byte 1024
Example 11.9.
4)3#%!"#$c%
<html><head><title>The ftell() Function</title></head>
<body bgcolor="lavender">
<h3>Marking a Position in a File</h3>
<pre>
<?php
//$filename="c:/wamp/www/exemples/data.file";
$filename="$_SERVER[DOCUMENT_ROOT]/exemples/data.file";
if (!file_exists($filename)){
print "No such file or directory";
exit();
}
1 $fh=fopen($filename,"r");
2 $substring="eastern";
while( !feof($fh)){
$line_of_text=fgets($fh);
echo "$line_of_text";
3 if(substr_count($line_of_text, $substring)) {
4 $bytes=ftell($fh);
}
}
if (! isset($bytes)){
echo "$substring not found<br />";
exit();
}
5 fseek($fh, $bytes, SEEK_SET);
echo "<hr />";
echo "<b>Start reading again from byte position $bytes</b>
<br />";
while( !feof($fh)){
6 $line_of_text=fgets($fh);
echo "$line_of_text";
}
fclose($fh);
?> </pre> </body> </html>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
D
W%7"8#%"'%)/#*#3%7)1%1#23"*>-
C
R=#%621"2T8#.%$substring.%"'%2''">*#3%&=#%'&1"*>%"eastern".%2%'&1"*>%&=2&%$"88%T#%
'#21(=#3%7)1%"*%&=#%7"8#%&=2&%$2'%d<'&%)/#*#3-
O
W'%#2(=%8"*#%"'%1#23%71)5%&=#%7"8#.%&=#%substr_count()%7<*(&")*%$"88%'#21(=%7)1%
&=#%'&1"*>%"eastern"%"*%2%8"*#%2*3%1#&<1*%&=#%*<5T#1%)7%&"5#'%"&%$2'%7)<*3-%
R=#%7"1'&%&"5#%&="'%7<*(&")*%1#&<1*'%D%)1%5)1#.%&=#%*#;&%8"*#%$"88%T#%#*#3-
@
R=#%ftell()%7<*(&")*%$"88%1#&<1*%&=#%T0&#%/)'"&")*%)7%$=#1#%&=#%*#;&%1#23%
)/#12&")*%$"88%&2N#%/82(#-%R=#%8"*#%()*&2"*"*>%"eastern"%=2'%281#230%T##*%
1#23-%R=#%T0&#%/)'"&")*%"'%&=#%*<5T#1%)7%(=212('%71)5%&=#%T#>"**"*>%)7%&=#%
7"8#-%R="'%628<#%"'%'26#3%"*%$bytes.%&)%T#%<'#3%82%$"&=%&=#%fseek()%7<*(&")*-
I
R=#%fseek()%7<*(&")*%$"88%'&21&%2&%&=#%T#>"**"*>%)7%&=#%7"8#.%T0&#%A.%2*3%5)6#%&)%
&=#%/)'"&")*%1#&<1*#3%71)5%ftell().%T0&#%CiD.%"*%&="'%#;25/8#-%M##%`"><1#%
DD-DA-
K
B=#*%fgets()%'&21&'%1#23"*>%8"*#'%71)5%&=#%7"8#%"&%/"(N'%</%1">=&%27%&=#%8"*#%
$=#1#%&=#%'<T'&1"*>%"eastern"%$2'%7)<*3-
Figure 11.10. Marking a position with ftell(). Output from Example 11.9.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
11.2.6. Opening a URL for Reading
You can open files with FTP or HTTP with the fopen() function. (Note: If opening the URL fails, check if the
allow_url_fopen directive in the php.ini file is disabled.)
Format
resource fopen ( string filename, string mode [, bool
use_include_path [, resource zcontext]] )
%
Example:
$filehandle=fopen('
$filehandle=fopen('ftp://username:/pub/index' , 'r');
Example 11.10.
<html><head><title>Open a File</title></head>
<body bgcolor="lavender">
<?php
1 $filename="
2 $fh=fopen("$filename", "r");
3 while( !feof($fh) ){
4 $contents=htmlspecialchars(fgets($fh, 1024));
print "<pre>$contents</pre>";
}
fclose($fh);
?>
</body>
</html>
Explanation
D
R=#%7"8#%"'%&=#%P?Z%)7%2%B#T%'"&#-
C
R=#%B#T%/2>#%"'%)/#*#3%7)1%1#23"*>%2*3%2%7"8#=2*38#%"'%1#&<1*#3.%(288#3%$fh-
O
R=#%#;/1#''")*%"*%&=#%while%8))/%<'#'%&=#%feof()%7<*(&")*%&)%(=#(N%$=#&=#1%$#%21#%*)&%
0#&%2&%&=#%#*3%)7%&=#%7"8#-
@
R=#%fgets()%7<*(&")*%1#23'%DAC@%T0&#'%2&%2%&"5#%71)5%&=#%/2>#-%R=#%
htmlspecialchars()%7<*(&")*%()*6#1&'%2*0%'/#("28%(=212('%&)%VR9Z%#*&"&"#'J%7)1%
#;25/8#.%2*%&%$)<83%T#()5#%&%2*3%2%<%$)<83%T#()5#%<.%2*3%')%)*-%R=#%)<&/<&%
'=)$*%"*%`"><1#%DD-DD%"'%&=#%2(&<28%')<1(#%/2>#%+!"#$%M)<1(#,%&=2&%$2'%<'#3%&)%(1#2&#%
&=#%/2>#-
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 11.11. Viewing the contents of a Web page opened as a URL.
%
11.2.7. Reading from Files Without a Filehandle
PHP provides functions that allow you to read the contents of a file without first opening a filehandle.
The file_get_contents() Function—Reading the Whole File into a String
An easy way to read the contents of an entire file is with the file_get_contents() function. You do not even
need to get a filehandle, just pass the name of the file to the function and it will get the contents of the whole file and
store it in a string. You can also start reading from a specified offset in the file and specify how many bytes you want to
read. The file_get_contents() function will return FALSE, if it fails. The PHP manual suggests this as the most
efficient way to read a file into a string.
Format
string file_get_contents ( string filename [, bool use_include_path [,
resource context [, int offset [, int maxlen]]]] )
%
Example:
$contents=file_get_contents("datafile.txt");
The file() Function—Reading the Whole File into an Array
Without using a filehandle, you can read an entire file into an array with PHP’s file() function. The filename can be
a full path, relative path, or even a URL (if each element of the array corresponds to a line in the file, with the newline
still attached. The function returns FALSE if it fails. If you do not want the end-of-line character at the end of each of
the array elements, use the rtrim() function, described in Chapter 6, “Strings.”
[5]
This function is identical to
file_get_contents(), except that it returns the file in an array.
[5]
If PHP does not recognize the line endings (Macintosh), see the php.ini file to enable the
auto_detect_line_endings runtime configuration option.
Format
array file ( string filename [, int use_include_path [, resource
context]] )
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 11.11.
<html><head><title>Parsing Lines</title></head>
<body bgcolor="lightgreen">
<font face=verdana" size="+2">
<?php
if( ! isset($_POST['submit'])){
1 show_form();
}
else{
2 process_file();
}
3 function show_form(){
?>
<h2>Exploding and Imploding</h2>
<form method=POST
action="<?php echo $_SERVER['PHP_SELF'];?>">
<table cellspacing="0" cellpadding="2">
<tr>
<b> Select a first name from the file.</b>
<td><input type="text" size=30
name="first_name" </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><input type="submit" name="submit"
</tr><br />
</table>
</form>
<?php
}
4 function process_file(){
$filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/datebook";
5 $lines = file($filename); // Lines of file stored in an
array
6 $first_name=trim($_POST['first_name']);
7 foreach ($lines as $line_value) {
8 $fields=explode(":", $line_value);
9 $fullname=explode(" ", $fields[0]);
$phone=$fields[1];
$address=$fields[2];
$birthday=$fields[3];
$salary=$fields[4];
10 if( strcasecmp($fullname[0],$first_name) == 0 ){
11 $birth=explode("/",$birthday);
12 $newstring=implode("<br
/>",array($fields[0],$phone,
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
$address,"19".$birth[2], '$'.number_format($salary,2)));
13 echo "$newstring<br />";
14 $count++;
echo "<hr />";
}
}
15 if($count==0){
echo "$first_name is not in the file.<br />";
}
}
?>
</b>
</font>
</body>
</html>
Explanation
D
R=#%621"2T8#.%$filename.%"'%2''">*#3%&=#%/2&=%&)%2%7"8#%(288#3%data.file%)*#%8#6#8%
2T)6#%&=#%3)(<5#*&%1))&%)7%&=#%'#16#1%"*%2%3"1#(&)10%(288#3%mydir-
C
R=#%T<"8&Q"*%file()%7<*(&")*%&2N#'%&=#%7"8#*25#%2'%"&'%21><5#*&%+*)&%2%7"8#=2*38#,%
2*3%1#&<1*'%2*%21120%$=#1#%#2(=%8"*#%"'%2*%#8#5#*&%)7%&=#%21120-
O
R=#%foreach%8))/%(0(8#'%)6#1%#2(=%#8#5#*&%)7%&=#%21120%)7%8"*#'.%#;&12(&"*>%&=#%"*3#;%
2*3%&=#%628<#%)7%&=#%8"*#-
@
f0%233"*>%)*#%&)%&=#%628<#%)7%$line_number.%&=#%"*3#;%"*%&=#%21120.%$#%(2*%'&21&%&=#%
()<*&%2&%D-%R="'%628<#%$"88%T#%/82(#3%"*%71)*&%)7%#2(=%8"*#%#6#10%&"5#%&=#%8))/%T)30%"'%
#;#(<-
I
:2(=%8"*#%2*3%"&'%8"*#%*<5T#1%21#%3"'/820#3%2'%'=)$*%"*%`"><1#%DD-DC-
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 11.12. Using the file() function, creating line numbers.
Using explode() and implode()
After you have read in a line from a file or you get input from a file, you might want to break the lines into individual
fields or create a string from an array of input items. This is where the array functions explode() and implode()
can be useful, array functions discussed in Chapter 8, “Arrays.”
Example 11.12 demonstrates how to use these functions. This example uses the text file called datebook.
[6]
Below are
two lines from this file. Notice that the fields are separated by colons.
[6]
The datebook file can be found on the CD in the back of this book.
Steve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300
Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
%
Example 11.12.
4)3#%!"#$c%
<html><head><title>Parsing Lines</title></head>
<body bgcolor="lightgreen">
<font face=verdana" size="+2">
<?php
if( ! isset($_POST['submit'])){
1 show_form();
}
else{
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
2 process_file();
}
3 function show_form(){
?>
<h2>Exploding and Imploding</h2>
<form method=POST
action="<?php echo $_SERVER['PHP_SELF'];?>">
<table cellspacing="0" cellpadding="2">
<tr>
<b> Select a first name from the file.</b>
<td><input type="text" size=30
name="first_name" </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><input type="submit" name="submit"
</tr><br />
</table>
</form>
<?php
}
4 function process_file(){
$filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/datebook";
5 $lines = file($filename); // Lines of file stored in an
array
6 $first_name=trim($_POST['first_name']);
7 foreach ($lines as $line_value) {
8 $fields=explode(":", $line_value);
9 $fullname=explode(" ", $fields[0]);
$phone=$fields[1];
$address=$fields[2];
$birthday=$fields[3];
$salary=$fields[4];
10 if( strcasecmp($fullname[0],$first_name) == 0 ){
11 $birth=explode("/",$birthday);
12 $newstring=implode("<br
/>",array($fields[0],$phone,
$address,"19".$birth[2], '$'.number_format($salary,2)));
13 echo "$newstring<br />";
14 $count++;
echo "<hr />";
}
}
15 if($count==0){
echo "$first_name is not in the file.<br />";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
}
}
?>
</b>
</font>
</body>
</html>
Explanation
D
\7%&=#%7)15%=2'%*)&%T##*%'<T5"&%0#&.%&=#%show_form()%7<*(&")*%$"88%3"'/820%"&-
C
\7%&=#%'<T5"&%T<&&)*%$2'%/1#''#3.%&=#%7)15%=2'%281#230%T##*%7"88#3%)<&.%2*3%*)$%"&%"'%
&"5#%&)%/1)(#''%"&-%R=#%process_file()%7<*(&")*%"'%(288#3-
O
R="'%"'%$=#1#%&=#%show_form()%7<*(&")*%"'%3#(821#3.%$="(=%/1)3<(#'%2%6#10%'"5/8#%
VR9Z%7)15%$"&=%)*#%&#;&%T);%2*3%2%'<T5"&%T<&&)*-%R=#%<'#1%$"88%&0/#%"*%&=#%7"1'&%
*25#%)7%')5#)*#%71)5%2*%#;*28%&#;&%7"8#.%(288#3%datebook-%M##%`"><1#%DD-DO-
@
R="'%"'%$=#1#%&=#%process_file()%7<*(&")*%"'%(288#3-%\&%$"88%1#23%2%7"8#%"*&)%2*%21120%
2*3%T1#2N%#2(=%8"*#%)7%&=#%7"8#%"*&)%7"#83'-%\7%2%8"*#%52&(=#'%&=#%7"1'&%*25#%)7%&=#%
"*/<&%628<#%&0/#3%"*&)%&=#%7)15.%&=2&%32&2%7)1%&=2&%/#1')*%$"88%T#%3"'/820#3-
I
R=#%^V^%file()%7<*(&")*%1#23'%2*%#*&"1#%7"8#%2*3%2''">*'%"&%&)%2*%21120.%$=#1#%#2(=%
8"*#%)7%&=#%7"8#%"'%2*%#8#5#*&%)7%&=#%21120-
K
R=#%628<#%)7%&=#%621"2T8#%(288#3%$first_name%"'%$=2&%&=#%<'#1%&0/#3%"*%&=#%7)15%2*3%
$2'%'#*&%6"2%&=#%POST%5#&=)3%&)%&="'%^V^%/1)>125-%W*0%$="&#'/2(#%"'%'&1"//#3%)<&%
$"&=%&=#%T<"8&Q"*%trim()%7<*(&")*-
E
R=#%foreach%8))/%"&#'%&=1)<>=%#2(=%628<#%"*%&=#%21120%)7%8"*#'%&=2&%$2'%(1#2%
$=#*%&=#%file()%7<*(&")*%1#23%"*%&=#%32&#T))N%7"8#%)*%8"*#%I-
Y
R=#%explode()%7<*(&")*%'/8"&'%</%2%'&1"*>.%$line.%T0%2%'/#("7"#3%3#8"5".%"*%&="'%
(2'#.%T0%2%()8)*-%\&%(1#2&#'%2*%21120%$=#1#%#2(=%)7%&=#%#8#5#*&'%1#/1#'#*&'%&=#%
"*3"6"3<28%7"#83'%&=2&%$#1#%(1#2-
i
R=#%7"1'&%#8#5#*&%)7%&=#%21120%(288#3%$fields[0]%()*&2"*'%2%7"1'&%2*3%82'&%*25#-%R=#%
explode()%7<*(&")*%$"88%(1#2&#%2%&$)Q#8#5#*&%21120.%(288#3%$fullname.%()*'"'&"*>%)7%
2%7"1'&%2*3%82'&%*25#-
DA
R=#%strcasecmp()%7<*(&")*%()5/21#'%&$)%'&1"*>'.%(2'#%"*'#*'"&"6#-%\7%&=#%628<#%&=2&%
(25#%"*%71)5%&=#%7)15.%$first_name.%2*3%&=#%628<#%)7%$fullname[0]%21#%#U<28.%&=#*%
8"*#%DD%"'%#*#3-
DD
R=#%explode()%7<*(&")*%(1#2&#'%&=#%$birth%21120%T0%'/8"&&"*>%$birthday;%7)1%
#;25/8#.%03/16/78.%T0%'82'=#'-
DC.%
DO
R=#%implode()%7<*(&")*%d)"*'%)1%a>8<#'b%&=#%21120%#8#5#*&'%&)>#&=#1%"*&)%)*#%
'&1"*>.%(288#3%"$newstring".%3"'/820#3%)*%8"*#%DO%2*3%'=)$*%"*%`"><1#%DD-D@-
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
DO
'&1"*>.%(288#3%"$newstring".%3"'/820#3%)*%8"*#%DO%2*3%'=)$*%"*%`"><1#%DD-D@-
D@
W%621"2T8#%(288#3%$count%$"88%T#%"*(1#5#*%#2(=%&"5#%&=1)<>=%&="'%8))/%&)%N##/%
&12(N%)7%&=#%*<5T#1%)7%8"*#'%7)<*3%52&(="*>%&=#%*25#%()5/21#3%"*%8"*#%DA-
DI
\7%&=#%628<#%)7%&=#%$count%"'%A.%&=#1#%$#1#%*)%52&(=#'.%2*3%&=#%/1)>125%3"'/820'%2%
5#''2>#%'20"*>%')-
%
Figure 11.13. The HTML form.
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 11.14. After the lines in the file have been parsed. Output from Example 11.12.
The readfile() Function—Reading and Writing a File
The readfile() function reads from a file and writes it to the output buffer. It returns the number of bytes read from
the file. If an error occurs, FALSE is returned and an error message is printed.
Format
int readfile ( string filename [, bool use_include_path [,
resource context]] )
%
Example:
readfile("myfile.txt");
Example 11.13.
<html><head><title>Reading and Outputting a File</title></head>
<body bgcolor="lightblue">
<h3>Reading and Outputting a File</h3>
<b>
1 <pre>
<?php
2 $number_of_bytes=@readfile("data.file");
echo "<br />Read $number_of_bytes bytes from the file.<br
/>";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
?>
</pre>
</b>
</body>
</html>
Explanation
D
R=#%VR9Z%<pre>%&2>%"'%<'#3%=#1#%')%&=2&%$=#*%&=#%7"8#%"'%3"'/820#3.%&=#%
*#$8"*#'%$"88%T#%/1#'#16#3.%2'%'=)$*%"*%`"><1#%DD-DK-
C
R=#%readfile()%7<*(&")*%$"88%1#23%"*%&=#%()*&#*&'%)7%data.file%2*3%'#*3%&=#%
)<&/<&%&)%&=#%&=#%)<&/<&%'&1#25J%7)1%#;25/8#.%T1)$'#1%)1%"*28-%\&%1#&<1*'%
&=#%*<5T#1%)7%T0&#'%1#23-%R=#%7<*(&")*%$2'%(288#3%2'%@readfile()%&)%'<//1#''%
&=#%/1"*&"*>%)7%2*%#11)1%5#''2>#%"7%2*%#11)1%)((<11#3-
Figure 11.15. Reading a file and outputting its contents.
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
11.2.8. Opening a File for Writing and Appending
When you open a file for writing, the file is created if it does not exist, and truncated if it does. If you open a file for
appending, the file will not be overwritten if it exists and the data will be appended to the bottom of the file. If it does
not exist, opening for appending creates the file.
To open a file for writing, the fopen() function returns a filehandle to either a text or binary file. Although UNIX and
MacOS do not distinguish between text and binary files, Windows does. If a file is to be shared by multiple operating
systems, it is safer to open it in binary mode in conjunction with one of the other modes. (As of PHP 4.3.2, the default
mode is set to binary for all platforms that distinguish between binary and text mode.)
UNIX and MacOS X represent the end-of-line character with \n, whereas Windows uses \r\n. If you use Windows,
the "t" mode can be used with plain-text files to translate the \n to \r\n. Otherwise, the "b" mode should be used,
which does not interpret data but treats it as just a series of bytes. If the file contents look weird when it is opened or
you have a lot broken images, use the "b" mode.
$handle = fopen("/home/marko/file.txt", "wb"); $handle =
fopen(" "w"); $handle =
fopen("ftp://user:/myfile.txt", "a");
%
The fwrite() and fputs() Functions
The fwrite() function writes a string text to a file and returns the number of bytes written. An alias for the
fwrite() function is fputs(). It takes two arguments: the filehandle returned by fopen() and an optional length
argument, how many bytes to write to the file. If it fails, fwrite() returns FALSE.
The file_put_contents() Function
The file_put_contents() also writes a string to a file and returns the number of bytes written, but does not
require a filehandle. Otherwise it is the same as fwrite() and fputs().
Format
int fwrite ( filehandle, string, [ int length] )
%
Example:
$bytes=fwrite( $filehandle, "Peter Piper picked a peck of pickled
peppers.\n"); $bytes=fwrite( $filehandle, "Jack in the Beanstalk", 4);
Example 11.14.
%%% <html><head><title>Open a File</title></head>
<body bgcolor="lavender">
<?php
1 $name="Joe Shmoe Jr.";
$address="100 Main St.";
$email="";
$title="Major";
2 $outputstring="$name\t$address\t$email\t$title\n";
3 $filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/info.txt";
4 $filehandle=fopen($filename, "wb");
5 fwrite($filehandle, $outputstring, strlen($outputstring));
fclose($filehandle);
?>
</body>
</html>
(Output: Contents of info.txt)
Joe Shmoe Jr. 100 Main St. Major
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
D
W%'#&%)7%'(2821%621"2T8#'%21#%3#7"*#3.%&=#%"*7)152&")*%&=2&%$"88%T#%$1"&&#*%&)%2%
7"8#-
C
W%'&1"*>%"'%(1#2%$"&=%#2(=%$)13%'#/212%T0%2%&2T-
O
f#(2<'#%&=#%7"8#%5<'&%T#%2%$1"T8#%7"8#.%"&%"'%'&)1#3%)<&'"3#%&=#%'#16#1S'%1))&%
3"1#(&)10-%\&%"'%8)(2%"*%&=#%2%3"1#(&)10%(288#3%mydir.%2*3%&=#%*25#%)7%&=#%7"8#%
"'%info.txt-
@
R=#%7"8#=2*38#%1#&<1*#3%71)5%fopen()%"'%)/#*#3%7)1%$1"&"*>-%R=#%"b"%+T"*210,%
5)3#%"'%1#()55#*3#3%$=#*%<'"*>%'0''%&=2&%3"77#1#*&"2&#%T#&$##*%T"*210%
2*3%&#;&%7"8#'J%&=2&%"'.%B"*3)$'-
I
R=#%fwrite()%7<*(&")*%$1"&#'%&=#%'/#("7"#3%'&1"*>.%$outputstring%&)%&=#%
7"8#=2*38#.%$filehandle-%R=#%*<5T#1%)7%T0&#'%$1"&&#*%21#%1#&<1*#3%T0%&=#%
strlen()%7<*(&")*-
Appending to a File
When a file is opened for appending, the write will start at the end of the file. If the file does not exist, it will be created.
Example 11.15.
4)3#%!"#$c%
<html><head><title>Appending</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
$name="John Doe";
$address="1001 Logic Dr.";
$email="";
$title="VP";
1 $outputstring="$name\t$address\t$email\t$title\n";
$filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/info.txt";
2 $filehandle=fopen($filename, "ab");
3 if( fwrite($filehandle, $outputstring,
strlen($outputstring))==FALSE){
echo "You cannot write to the $filename.<br />";
}
else{
4 $text= file_get_contents("$filename");
echo "<pre>$text</pre>";
}
fclose($filehandle);
?>
</body>
</font>
</html>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
D
R=#%628<#'%)7%&=#%621"2T8#'%21#%2''">*#3%&)%&=#%621"2T8#.%$outputstring-%:2(=%628<#%"'%
'#/212%T0%2%&2T%2*3%&=#%'&1"*>%#*3'%$ "& =%2%*#$8"*#-
C
R=#%7"8#%info.txt%"'%)/#*#3%7)1%2//#*3"*>.%$="(=%5#2*'%&=#%"**28%7"8#%/)"*%$"88%
'&21&%$1"&"*>%2&%&=#%#*3%)7%&=#%7"8#.%12&=#1% & =2*%&=#%T#>"**"*>-
O
\7%&=#%fwrite()%7<*(&")*%72"8'.%&=#%/1)>125%$"88%/1)3<(#%2*%#11)1-%F&=#1$"'#.%&=#%'&1"*>%
"*%$outputstring%$"88%T#%2//#*3#3%&)%&=#%7"8#-%F<&/<&%"'%'=)$*%"*%`"><1#%DD-DK-%R=#%8"*#%
'&21&"*>%$"&=%Joe Doe%=2'%T##*%2//#*3#3-
@
R=#%()*&#*&'%)7%&=#%7"8#%21#%1#23%2*3%3"'/820#3-
%
Figure 11.16. After writing and appending. Output from Example 11.15.
%
Locking Files with flock()
What if two or more customers are trying to write to a Web site at the same time? To prevent this, you can lock the file
so that a user has exclusive access to it and then unlock it when he or she has finished using it. PHP supports a portable
way of locking complete files with the flock() function. This is called advisory locking because all accessing
programs have to use the same locking mechanism or it will not work. See Table 11.6 for a list of flock() operations.
Table 11.6. flock() Operations
Operation
(Constant)-Numeric-
Value
Operation-It-Peforms
LOCK_EX
C
W(U<"1#'%2*%#;(8<'"6#%8)(N%+$1",-
LOCK_NB
@
[)*T8)(N"*>%+*)%$2"&"*>,%$="8#%&=#%8)(N%"'%T#"*>%
2(U<"1#3-
LOCK_SH
D
W(U<"1#'%2%'=21#3%8)(N%+1#23#1,-
LOCK_UN
O
?#8#2'#'%2%8)(N%+'=21#3%)1%#;(8<'"6#,-
%
The flock() function uses a filehandle returned from the fopen() function. The lock can be released by
fclose(), which is also called automatically when the script finished. The function returns TRUE on success or
FALSE on failure. Whether or not this function works properly is entirely dependent on your operating system; for
example, it is not supported on older systems like Windows 98 or for networked file systems (NFS), and so on.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Format
bool flock ( resource handle, int operation [, int &wouldblock] )
Example 11.16.
4)3#%!"#$c%%
<html><head><title>File Locking</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
$name="Jane Doe";
$address="1 Sensible Ave.";
$email="";
$title="Dean";
$outputstring="$name:$address:$email:$title\n";
$filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/info.txt";
1 $filehandle=fopen($filename, "ab");
2 if (flock($filehandle, LOCK_EX)){ // Acquire an exclusive
lock
3 fwrite($filehandle, $outputstring,
strlen($outputstring));
4 flock($filehandle, LOCK_UN); // Release the lock
}
else{
echo "Couldn't lock this file.<br />";
exit();
}
$text= file_get_contents("$filename");
echo "<pre>$text</pre>";
5 fclose($filehandle); // This would also release the lock
?>
</body>
</font>
</html>
Explanation
D
W%7"8#%"'%)/#*#3%7)1%2//#*3"*>-
C
R=#%flock()%7<*(&")*%2&/&'%&)%/<&%2*%#;(8<'"6#%8)(N%)*%&=#%7"8#J%&=2&%"'.%&=#%
7"8#%(2**)&%T#%'=21#3%$="8#%"&%"'%T#"*>%$1"&&#*% & )-
O
\7%&=#%8)(N%"'%'<((#''7<880%'#&.%&=#%/1)>125%(2*%*)$%$1"&#%&)%&=#%7"8#-
@
F*(#%&=#%/1)>125%=2'%7"*"'=#3%$1"&"*>%&)%&=#%7"8#.%&=#%#;"'"&"*>%8)(N%"'%1#8#2'#3%
$"&=%&=#%LOCK_UN%)/#12&")*-
I
\7%&=#%8)(N%$2'%*)&%)77"("2880%1#8#2'#3%$"&=%flock().%&=#%fclose()%7<*(&")*%$"88%
(2<'#%&=#%8)(N%&)%T#%1#8#2'#3%$=#*%"&%(8)'#'%&=#%7"8#=2*38#-
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
11.2.9. File Checks
Before performing operations on files or directories, it is a good practice to verify whether or not the file even exists, if
it is readable, writable, executable, and so on. PHP provides a set of functions for testing the status of a file. See Table
11.7.
Table 11.7. File Testing Functions
Function
Description
file_exists()
4=#(N'%"7%&=#%7"8#%)1%3"1#(&)10%#;"'&'-
is_dir()
4=#(N'%"7%&=#%7"8#*25#%"'%2%3"1#(&)10-
is_file()
4=#(N'%"7%&=#%7"8#*25#%"'%2%7"8#-
is_link()
4=#(N'%"7%&=#%7"8#*25#%"'%2%'05T)8"(%8"*N-
is_readable()
4=#(N'%"7%&=#%7"8#%"'%1#232T8#-
is_uploaded_file()
4=#(N'%"7%&=#%7"8#%$2'%</8)23#3%T0%2*%VRR^% =)'&-
is_writable()
4=#(N'%"7%&=#%7"8#%"'%$1"&2T8#-
is_writeable()
W*%28"2'%7)1%is_writable-
stat()
L"6#'%"*7)152&")*%2T)<&%2%7"8#-
%
The file_exists() Function
The file_exists() function checks to see whether a file or directory exists. It returns TRUE if it does, and FALSE
if it does not.
Format
bool file_exists ( string filename );
%
Example:
if ( file_exists("filetest.php");
Example 11.17.
<html><head><title>Appending</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
1 $filename="c:\wamp\www\logo_i.gif"; // Windows
if(
file_exists("$filename")){
echo "<img src='logo_i.gif'><br />";
}
else{
echo "<em>$filename</em> doesn't exist.<br />";
exit();
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
?>
</body>
</font>
</html>
Explanation
D
R=#%file_exists()%7<*(&")*%(=#(N'%&)%'##%"7%&=#%"52>#%7"8#%2''">*#3%&)%
$filename%#;"'&'%T#7)1#%3"'/820"*>%"&-
The is_file() Function
The is_file() function checks to see if a file exists and is a regular file; that is, not a directory. It takes the name of
the file as its argument and returns TRUE if the file is a regular file, and FALSE if it is not.
[7]
[7]
Processing is faster if you use a relative path name rather than an absolute path.
Format
bool is_file ( string filename )
%
Example:
if ( is_file("myfile.php"){ print "True<br />"; }
Example 11.18.
<html><head><title>Is it a Regular File?</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
$filename="c:\wamp\www";
1 if(is_file($filename)){
echo "$filename exists and is a regular file.<br />";
}
else{
2 echo "<em>$filename</em> is not a regular file.<br />";
exit();
}
?>
</body>
</font>
</html>
Explanation
D
R=#%is_file()%7<*(&")*%*)&%)*80%(=#(N'%&)%'##%"7%&=#%7"8#%#;"'&'.%T<&%28')%"7%"&%"'%2%1#><821%
7"8#J%&=2&%"'.%*)&%2%3"1#(&)10-
C
R="'%8"*#%"'%3"'/820#3%"*%`"><1#%DD-DE-%R=#%7"8#%c:\wamp\www%"'%*)&%2%1#><821%7"8#-
%
%
%
%
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 11.17. The file exist, but it is not a plain file. Output from Example 11.18.
%
The is_readable() Function
The is_readable() function checks to see if you can read from a file. It takes the filename as its argument and
returns TRUE if the filename exists and is readable. If the PHP script is being executed by the server, the server’s
permissions (usually limited) determine whether or not the PHP program can read from the file, and if it is being
executed at the shell prompt, the permissions of the user running the script are the deciding factor. Normally, the file
should be readable by others.
Format
bool is_readable ( string filename );
%
Example:
if ( is_readable("file.txt")) { echo "File is readable<br />";}
Example 11.19.
<html><head><title>Is Readable?</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
$filename="testing.txt";
1 if( is_readable($filename)){
echo "<em>$filename</em> is readable<br />";
}
2 else{
echo "Can't read from <em>$filename.</em><br />";
exit();
}
?>
</body>
</font>
</html>
Explanation
D
R=#%is_readable()%7<*(&")*%1#&<1*'%&1<#%"7%$filename%"'%1#232T8#%T0%&="'%^V^%
'(1"/&-
C
\7%is_readable()%1#&<1*'%728'#.%&=#%else%T8)(N%"'%#;#(<.%2*3%&=#%/1)>125%
#;"&'-
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The is_writable() Function
When opening a file for writing, you might run into a problem with permissions if you are trying to put the file in a
directory not accessible to the Web. Because the PHP script is executed on behalf of the server, it shares the same
permissions. Normally, the server does not have world-write permissions turned on to prevent hackers from breaking
into your site and causing havoc.
The is_writable() (or is_writeable) function returns true if a file exists and is writable, and false if it is not.
Format
bool is_writable ( string filename )
%
Example:
if (is_writable($filename)) {echo "$filename is writable";}
Example 11.20.
<html><head><title>Appending</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
$name="John Doe";
$address="1001 Logic Dr.";
$email="";
$title="VP";
1 $outputstring="$name\t$address\t$email\t$title\n";
2 $filename="testing.txt";
3 if( is_writable($filename)){
$filehandle=fopen($filename, "wb");
fwrite($filehandle, $outputstring,
strlen($outputstring));
}
else{
4 echo "Can't write to <em>$filename.</em><br />";
exit();
}
fclose($filehandle);
?>
</font></body></html>
Explanation
D
W%'&1"*>%(288#3%$outputstring%"'%(1#2%71)5%&=#%*25#.%2331#''.%#Q52"8%2331#''.%2*3%
&"&8#%)7%j)=*%X)#-%R="'%'&1"*>%$"88%T#%'#*&%&)%&=#%7"8#%8"'%)*%8"*#%C-
C
R=#%621"2T8#%$filename%"'%2''">*#3%&=#%*25#%)7%&=#%7"8#%&=2&%$"88%T#%$1"&&#*%&)-%^V^%5<'&%
=26#%/#15"''")*%&)%$1"&#%&)%&="'%7"8#-
O
R=#%is_writable()%T<"8&Q"*%7<*(&")*%1#&<1*'%&1<#%"7%^V^%(2*%$1"&#%&)%&="'%7"8#.%2*3%&=#%
fopen()%7<*(&")*%$"88%2&/&%&)%)/#*%"&-
@
\7%&=#%is_writeable()%7<*(&")*%1#&<1*'%728'#.%&="'%8"*#%"'%#;#(<%2*3%&=#%/1)>125%#;"&'-%
M##%`"><1#%DD-DY-
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 11.18. This file is not writable. Output from Example 11.20.
Example 11.21.
4)3#%!"#$c%
<html><head><title>Handling Errors</title></head>
<body bgcolor="lavender">
<font face="verdana" size="+1">
<?php
$name="Joe Shmoe Jr.";
$address="100 Main St.";
$email="";
$title="Major";
$outputstring="$name\t$address\t$email\t$title\n";
1 $filename="info.txt";
// Suppress error message, if there is one
2 @ $fp=fopen($filename, "w");
3 if (! $fp ){
4 echo "Error: You don't have permission to open
this file.<br />";
exit();
}
fwrite($fp, $outputstring, strlen($outputstring));
echo "Output was sent to $filename<br />";
fclose($fp);
?>
</body>
</font>
</html>
Explanation
D
R="'%"'%&=#%7"8#%&=2&%$"88%T#%$1"&&#*%&)-%\7%"&%281#230%#;"'&'%"&%$ "8 8 %T #%)6#1$1"&&#*J%
)&=#1$"'#%fopen()%$"88%&10%&)%(1#2&#%"&-
C
\7%&=#%fopen()%7<*(&")*%(2**)&%(1#2&#%)1%)/#*%&=#%7"8#%7)1%$1"&"*>.%"&%"'%/1)T2T80%T#(2<'#%
"&%3)#'%*)&%=26#%$1"&#%/#15"''")*%"*%&=#%3"1#(&)10.%"*%$="(=%(2'#%2*%#11)1%5#''2>#%
$)<83%*)152880%)((<1-%f0%/1#(#3"*>%&=#%'&2#*&%$"&=%&=#%@%'05T)8.%2*0%#11)1'%$"88%
T#%'<//1#''#3-
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
O.%
@
\7%&=#%fopen()%7<*(&")*%)*%8"*#%C%72"8#3.%2%7"8#=2*38#%$)<83%*)&%=26#%T##*%1#&<1*#3-%R="'%
8"*#%&#'&'%&)%'##%"7%&=#1#%"'%*)&%2%628<#%7)1%$fp.%2*3%"7%*)&%>)#'%&)%8"*#%@.%/1"*&'%&=#%#11)1%
5#''2>#.%2*3%#;"&'-%F<&/<&%"'%'=)$*%"*%`"><1#%DD-Di-
%
Figure 11.19. Suppressing PHP errors and printing your own. Output from Example 11.21.
11.2.10. Creating, Copying, Renaming, and Deleting Files
Table 11.8 lists functions for creating, copying, renaming, and removing files. This section examines these functions.
Table 11.8. Functions to Manipulate Files
Function
Description
copy()
4)/"#'%2%7"8#-
rename()
?#*25#'%2%7"8#-
touch()
P/32&#'%"&'%&"5#'&25/%+5)3"7"(2&")*%2*3%2((#''%&"5#',%)1%(1#2&#'%&=#%7"8#-
unlink()
?#5)6#'%2%7"8#-
%
The copy() Function—Making a Copy of a File
To make a copy of a file, the copy() function is used. The copy() function will return true if the file was correctly
copied, or false if there was an error. To copy a file, you will need write permission on the directory where the new
copy will be stored.
Format
bool copy(string source_file,string destination_file)
Example 11.22.
<html><head><title>Copy a File</title></head>
<body bgcolor="lavender">
<?php
1 $oldfilename="data.file";
2 $newfilename="data.file.bck";
3 if(! copy($oldfilename, $newfilename)){
echo "Copy failed\n<br />";
exit();
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
}
else { echo "Copy succeeded!\n<br />";}
?>
</body>
</html>
Explanation
D
R="'%"'%&=#%*25#%)7%&=#%)1">"*28%7"8#.%&=#%')<1(#-%\&%5<'&%#;"'&%)1%&=#%()/0%$"88%
72"8-
C
R="'%"'%&=#%*25#%)7%&=#%3#'&"*2&")*%7"8#.%&=#%7"8#%&=2&%$"88%T#%(1#2-
O
\7%&=#%()/0%72"8'.%2*%#11)1%$"88%T#%/1"*%2*3%&=#%/1)>125%$"88%#;"&-
The rename() Function—Renaming and/or Moving a File
The rename() function is used to give a file or directory another name. If the destination file is in another directory,
then you are essentially moving the file. It returns true on success, and false if it fails.
Format
bool rename(string old_file,string new_file)
%
Example:
rename("/tmp/tmpfile", "/home/ellie/exemples/data.txt");
The unlink() Function—Removing a File
The unlink() function is used to remove a file. It returns true if it can remove the file and false if not.
Format
bool unlink ( string filename [, resource context] )
%
Example:
unlink("datafile.txt"); // Deletes the file from the directory
11.3. Directories
PHP supports a number of functions to allow you to work with directories in the file system. From a PHP script, you
can open a directory and read its contents (similar to the ls (UNIX) or dir /b (DOS). You can change to a new
directory, list the current working directory, remove a directory, and so on. Table 11.9 lists functions that will be used
in the following examples.
Table 11.9. PHP Directory Functions
Function
Description
chdir()
4=2*>#'%&=#%3"1#(&)10-
chroot()
4=2*>#'%&=#%1))&%3"1#(&)10-
closedir()
48)'#'%2%3"1#(&)10%=2*38#%/1#6")<'80%)/#*#3%$"&=%opendir()-
getcwd()
L#&'%&=#%(<11#*&%$)1N"*>%3"1#(&)10-
opendir()
?#&<1*'%2%3"1#(&)10%=2*38#%&=2&%(2*%T#%<'#3%$"&=%readdir().%closedir().%2*3%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 11.9. PHP Directory Functions
Function
Description
rewinddir()-
readdir()
?#23'%&=#%*#;&%7"8#%71)5%2%3"1#(&)10%=2*38#%)/#*#3%$"&=%opendir()-
rewinddir()
?#$"*3'%3"1#(&)10%=2*38#%/)"*%&)%&=#%T#>"**"*>%)7%&=#%3"1#(&)10-
rmdir()
X#8#&#'%2%3"1#(&)10-%\&%5<'&%T#%#5/&0%2*3%=26#%$1"&#%/#15"''")*-
scandir()
?#&<1*'%2*%21120%)7%7"8#'%2*3%3"1#(&)1"#'%71)5%2%>"6#*%/2&=-
unlink()
X#8#&#'%2%7"8#%71)5%2%3"1#(&)10-
%
11.3.1. Opening and Reading from a Directory
When you open a directory with the opendir() function, you create a directory handle to allow access to the
directory as it is stored on the disk by the operating system regardless of its internal structure. Once it is opened, you
can access the directory with the PHP functions listed in Table 11.9.
The opendir() Function
The opendir() function is used to open a directory, similar to the fopen() function for opening files. Once a
handle to the directory is returned, the other directory functions, such as readdir(), rewindir(), and
closedir(), can be applied to the directory filehandle. If the directory cannot be opened, false will be returned.
Format
resource opendir ( string path [, resource context] )
%
Example:
// $dirhandle is a resource similar to a filehandle
$dirhandle=opendir("/home/john");
The readdir() Function
A directory can be read by anyone who has read permission on the directory. When we speak of reading a directory, we
are talking about looking at its contents with the readdir() function. readdir() reads an entry from a directory
handle, given as its argument, and returns the name of a file from the directory. Each file appears in the order in which
it is stored by the file system on the disk. You can use this function in a loop to list the contents of the entire directory,
one file at at time. The readdir() function returns either a filename, or false if it fails. If it succeeds, it moves its
internal pointer to the next file in the directory, until it reaches the end of the list.
Format
string readdir ( resource dir_handle )
%
Example:
$dirhandle=opendir("/home"); // Gets one file from the directory. Use a loop to
get them all $one_file=readdir($dirhandle);
Example 11.23.
<html><head><title><Directory Functions</title></head>
<body bgcolor="aqua">
<font face="verdana">
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
<h3>Listing the Contents of a Directory</h3>
<b>
<?php
1 $dirhandle=opendir("c:/wamp/mysql");
// List all files in the directory
2 while(false !== ($file=readdir($dirhandle))){
echo $file,"<br />";
}
closedir($dirhandle);
?>
</font>
</b>
</body>
</html>
Explanation
D
R=#%opendir()%7<*(&")*%1#&<1*'%2%3"1#(&)10%=2*38#%&)%c:/wamp/mysql-
C
R=#%7)152&%7)1%&="'%8))/%$2'%236"'#3%2'%&=#%()11#(&%5#&=)3%&)%8))/%&=1)<>=%
&=#%3"1#(&)10%"*%&=#%^V^%52*<28%$"&=%&="'%#;/82*2&")*c%aB#%21#%#;/8"("&80%
&#'&"*>%$=#&=#1%&=#%1#&<1*%628<#%"'%"3#*&"(28%&)% %`WZM:%'"*(#%)&=#1$"'#.%2*0%
3"1#(&)10%#*&10%$=)'#%*25#%#628<2&#'%&)%`WZM:%$"88%'&)/%&=#%8))/%+#-> %2%
3"1#(&)10%*25#3%A,-b%M##%=&&/ckk<'O-/=/-*#&k52*<28k#*k7<*(&")*-1#233"1-/=/-%
F<&/<&%"'%'=)$*%"*%`"><1#%DD-CA-
Figure 11.20. Open a directory and list its contents.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.