HomePHP Page 2 - File And Directory Manipulation In PHP (part 2)
Stripping It To The Bone - PHP
Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.
You may remember, from the first part of this article, how I used the fgets() function to read the contents of a file and print it to the browser. In case you don't, here's a quick reminder:
<?php
// set file to read
$filename = "mindspace.txt";
// open file
$fh = fopen ($filename, "r") or die("Could not open file");
PHP also offers the fgetss() function, which works just like the regular fgets() function, except that it also strips out HTML and PHP code from the lines it reads. So, for example, if you had a file containing intermingled HTML code and ASCII text (as most HTML files are), like in the following example,
<HTML>
<HEAD>
</HEAD>
<BODY>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR>
<TD>
<FONT FACE="Verdana, Arial" SIZE="2" COLOR="#66CC00">
<B><A HREF="article.php?id=169"><IMG SRC="/images/sm_arrow.jpg"
WIDTH=20 HEIGHT=20 ALT="" BORDER=0 ALIGN="ABSMIDDLE" HSPACE=4>Learning
To SMILe</A></B> </FONT> </TD> </TR> <TR>
<TD> <FONT FACE="Verdana, Arial" SIZE="1" COLOR="Black">
Use SMIL to quickly build new Web-based multimedia applications | 20 Dec 2002
</FONT>
</TD>
</TR>
<TR>
<TD HEIGHT=25>
</TD>
</TR>
<TR>
<TD>
<FONT FACE="Verdana, Arial" SIZE="2" COLOR="#66CC00">
<B><A HREF="article.php?id=168"><IMG SRC="/images/sm_arrow.jpg"
WIDTH=20 HEIGHT=20 ALT="" BORDER=0 ALIGN="ABSMIDDLE" HSPACE=4>Writing
A User Manual (part 1)</A></B> </FONT> </TD> </TR>
<TR> <TD> <FONT FACE="Verdana, Arial" SIZE="1"
COLOR="Black"> It ain't easy writing a user manual...but our cheat
sheet should help | 20
Dec 2002
</FONT>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
you could retrieve just the ASCII from it with the following example script:
<?php
// set file to read
$filename = "data.html";
// open file
$fh = fopen ($filename, "r") or die("Could not open file");
// read file
while (!feof($fh))
{
// strip out tags
$data = fgetss($fh, 999);
// if nothing present after stripping tags, move on
// else print the cleaned line
if (trim($data) != "")
{
echo trim($data) . "\r\n";
}
}
// close file
fclose ($fh);
echo "-- ALL DONE --";
?>
Here's what the output looks like:
Learning To SMILe Use SMIL to quickly build new Web-based multimedia applications | 20 Dec 2002 Writing A User Manual (part 1) It ain't easy writing a user manual...but our cheat sheet should help | 20 Dec 2002