Learn

Whenever we’re working with the file system, there’s a lot that can go wrong. If a file operation is unsuccessful, PHP attempts to continue running our program as seamlessly as possible, meaning that any errors can be difficult to pin down. However, we can find out what’s wrong by looking for two indicators:

  1. The file operation returns false.
  2. An error or warning message is printed to the console.

To see this in action, let’s take a look at what happens if we misspell a file name:

$read_me = file_get_contents("reed-me.txt"); echo $read_me;

This should print the contents of read-me.txt, but because we got the file name wrong, this won’t work. In fact, we might not even know that an error occurred — sometimes, all we’ll see is a blank screen. This is because file_get_contents returned false, a value that echo and print statements display as an empty string.

Ideally, our applications would let us know about the error using some sort of error message. To make this happen, we can check the value returned from file_get_contents and handle failure cases explicitly:

$read_me = file_get_contents("reed-me.txt"); if ($read_me == false) { echo "Cannot read file"; } else { echo $read_me; }

Like other file operations in PHP, file_get_contents indicates errors by returning false. By explicitly handling this scenario, we can make bugs much easier to diagnose.

PHP can also inform us of the problem by printing a message to the console:

PHP Warning: file_get_contents(reed-me.txt): Failed to open stream: No such file or directory in index.php on line 2

To hone our debugging skills, let’s try this out ourselves!

Instructions

1.

We have been hired to create a website for a client. While creating the website, we ran into a problem: the home page won’t show up! Let’s figure this out. To start, take a look at the code we have written so far and click Run to see it in action. Then, check the console for a warning message.

2.

In the console, you should see a message like this:

PHP Warning:  file_get_contents(home.htm): Failed to open stream: No such file or directory

This means home.htm does not exist. However, our client would prefer a more user-friendly error message.

Using an if statement, update the script to print "File not found" if the file_get_contents call was unsuccessful.

3.

Now, if the file_get_contents() function is unsuccessful, the script prints “file not found”. However, it still prints the $home variable — even if its value is false. To clean up our code, use an else statement to print the value of $home only if the file read was successful.

4.

Finally, let’s correct the error. The file name appears to be misspelled, so update the file_get_contents call to read home.html instead of home.htm.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?