Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

Files


As you have learned elsewhere in the book, the UNIX philosophy is that
everything is a file. In PHP, this is also the case: A selection of basic file
functions is suitable for opening and manipulating files, but those same
functions can also be used for opening and manipulating network sockets. We
cover both here.


Two basic read and write functions for files make performing these basic
operations easy. They are file_get_contents(), which takes a
filename as its only parameter and returns the file’s contents as a string, and
file_put_contents(), which takes a filename as its first parameter and
the data to write as its second parameter.


Using these two functions, you can write a script that reads all the text from
one file, filea.txt, and writes it to another, fileb.txt:


Click here to view code image
<?php
$text = file_get_contents("filea.txt");
file_put_contents("fileb.txt", $text);
?>


Because PHP enables you to treat network sockets like files, you can also use
file_get_contents() to read text from a website, like this:


Click here to view code image
<?php
$text = file_get_contents("http://www.slashdot.org");
file_put_contents("fileb.txt", $text);
?>


The problem with using file_get_contents() is that it loads the whole
file into memory at once; that’s not practical if you have large files or even
smaller files being accessed by many users. An alternative is to load the file
piece by piece, which can be accomplished by using the following five
functions: fopen(), fclose(), fread(), fwrite(), and feof().
The f in these function names stands for file, so they open, close, read from,
and write to files and sockets. The last function, feof(), returns true if the
end of the file has been reached.


On the surface, the fopen() function looks straightforward, though it takes
a bit of learning to use properly. Its first parameter is the filename you want to
open, which is easy enough. However, the second parameter is where you
specify how you want to work with the file, and you should specify one of the
following:

Free download pdf