Yesterday, I kind-of neglected to show you an example of how perform basic file access. Today I will remedy that! File access can be done various ways and each has its own reasons. Here is an example of a CSV read:
-
-
if (!is_file($name))
-
die ("File is missing!");
-
-
$file = fopen($name, "r");
-
-
$news = array();
-
while ($row = fgetcsv($file)) {
-
$news[] = $row;
-
}
-
-
fclose($file);
This is perfect for storing flat-file news. Personally, I would prefer to use a database/caching if the news items change frequently.
Another example is when you want to read an entire of a file:
-
$file = fopen("EULA.txt", "r");
-
-
$contents = "";
-
while ($line = fread($file)) {
-
$contents .= $line;
-
}
-
-
fclose($file);
-
-
// The easier way
-
$contents = implode("\r\n", file("EULA.txt"));
-
-
// The easiest way
-
$contents = file_get_contents("EULA.txt");
PHP gives you options in this case: you can either read in each line with fread(), return an array of lines with file(), or get the entire contents with file_get_contents(). There is may also be an occasion where you would want to display the contents of a file right to the screen, you can either read in the entire file and echo it or this:
-
// so the brower knows to act accordingly
-
header("content-type: video/mpeg");
-
readfile("videos/intro.mpeg");
Readfile() displays the file data right to the screen.
Tomorrow I’ll talk about directory access.

