Hello and welcome back to another post about PHP.

Today I want to talk about using PHP for File Handling, remembering that these are files on the server, and not on the user machine.

So, the best way to start this is getting a very simple txt file and displaying as HTML, and for that we can use “Hello World!”.

Hello World!

Then we just ask PHP to read it and echo it to the page, with the command

<?php
 echo readfile("hello_world.txt");
 ?>

And the result is “Hello World!12”. So readfile will print not only the content of the txt file, but also the amount of character on the file.

Now let’s try changing the txt file and include some HTML tags to see what happens, still using the readfile function.

<h2>Hello World!</h2>

And the result is:

Hello World!

21

Ok…. so it still counts the characters, but use the tags and with this we can add not only marking elements, but also scripts as this:

<script> alert("hi"); </script>

And the readfile will actually pop the “hi” alert. So be careful when reading files to make sure they will not affect the DOM on a unwanted way.

But what happen if the file we are trying to open doesn’t exist? It will crash the page and that is not fun. To avoid that, it’s safer to first open the file and then read it.

<?php
  $myfile = fopen("hello_world.txt", "r") or die ("Unable to open file");
  echo fread($myfile, filesize("hello_world.txt"));
  fclose($myfile);
?>

This option to open, read and close the file will not display the length of the text string, but will keep the inside formatting and print

<h2>Hello World</h2>

as

Hello World!

and the alert script would still pop up a “hi” to your screen.

When using the fopen function before, I used “r” right after the file name, and that stands for reading only. Some other options are:

  • w for writing only that overwrites the contents of file, or creates one
  • a for writing only that appends to the file, or creates one
  • x to create a new file for writing only (will return FALSE if file exists)

And since r doesn’t create a file if it doesn’t exists, I added the “or die” option to echo an error message.

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");

Then I used the function fread, that will read the amount of characters I want from the file. To show the whole file, I used the function filesize, that counts the amount of characters on the file.

echo fread($myfile,filesize("webdictionary.txt"));

And finally, closing the file with

fclose($myfile);

Another way to read the file is reading line by line, and for that we can use the function fgets and the txt file as below.

<h2>Hello World!</h2>
This is the second line
This is the third line

And the PHP code that prints the first line will be

<?php
  $myfile = fopen("hello_world.txt", "r") or die ("Unable to open file");
  echo fgets($myfile);
  fclose($myfile);
?>

So, how about looping and printing the whole file?

<?php
  $myfile = fopen("hello_world.txt", "r") or die ("Unable to open file");
  while (!feof($myfile)) {
    echo fgets($myfile) . "<br>";
  }
  fclose($myfile);
?>

The way fgets works is very similar to what we know from Java Scanner class, where reading a char, int, line, etc will move a pointer through our file, and the next reading will start from that pointer.

So to work with fgets, we can get a specific number of characters with fgetc, and using this code

<?php
 $myfile = fopen("hello_world.txt", "r") or die ("Unable to open file");
 while (!feof($myfile)) {
 echo fgetc($myfile) . "<br>";
 }
 fclose($myfile);
?>

will result in (I’m sorry for this, just scroll down…)

<
h
2
>
H
e
l
l
o

W
o
r
l
d
!
<
/
h
2
>

T
h
i
s

i
s

t
h
e

s
e
c
o
n
d

l
i
n
e

T
h
i
s

i
s

t
h
e

t
h
i
r
d

l
i
n
e

Ok…. So now we can read stuff from a text file, just like 1st semester Java. And still in 1st semester, let’s start writing on this text file.

For that I’ll start with the fopen function and a brand new file

$myfile = fopen("newfile.txt", "w");

And again, similar to Java, I can just call a write function (in this case, fwrite).

$str = "<h2>This is the header</h2>\n";
fwrite($myfile, $str);
fwrite($myfile, "This is another line<br>");

And do not forget to close the file, and the whole code is

<?php
 $myfile = fopen("newfile.txt", "w");
 $str = "<h2>This is the header</h2>\n";
 fwrite($myfile, $str);
 fwrite($myfile, "This is another line<br>");
 fclose($myfile);
?>

Which creates the text file with

<h2>This is the header</h2>
This is another line<br>

Again, this is so very similar to reading/writing in Java that is almost cheating the system…

Remember that every time I run this script it will erase all the content of the file and rewrite over it. To keep the info and append the new content, the fopen should use “a” instead of “w”.

So, that’s all for this post.

This series is a requirement for my INTP-362-A – Emerging Trends in Tech. course in SAIT ITSD program, but I enjoyed so much creating content that I will keep doing it.

I’ll keep track of my next projects (which includes a Raspberry Pi, php, and also WordPress) and create blog posts about my progress.

Thank you very much and see you soon.

Thiago