Logging to a file with PHP.

This is a guide on how to log to a file using PHP. Custom PHP logging can be extremely useful if you are trying to debug an issue or collect statistics. In the past, I have resolved a number of issues by simply logging information to a file and then reviewing it.

Do not underestimate the importance of logging!

Logging to a file with PHP.

In PHP, you can use the file_put_contents function to write data to a file. Take a look at the following code example:

An explanation of the PHP code above:

  1. We created an array containing the information that we want to log. In the case above, I am wanting to log the date and time, the user’s IP address and two other pieces of custom information. I store these in an array because I personally find the code easier to read. It also means that I can easily add more data to the log without worrying about delimiters, etc.
  2. We used PHP’s implode function to convert the array data into a single line of text. In the code above, I used the hyphen character as a delimiter. You can obviously change this to meet your own needs. Note that the delimiter should not be found in the rest of your data, as the purpose of a delimiter is to specify the boundary between separate pieces of plain text. Essentially, it allows us to split the log file up into its relevant parts.
  3. We added a newline onto the end of the text. This is important as it makes the log file easier to read. I used the PHP_EOL constant instead of manually typing out a newline because the PHP_EOL constant helps to prevent cross-platform issues.
  4. We created the name of our log file. In the case above, the log file will exist in the same directory of the PHP script that created it. You can also specify a full path to the log file if needs me. Personally, I would suggest that you modify this and supply a full path to the log file you want to create.
  5. Finally, we logged the data to our file using file_put_contents. Note how we used the FILE_APPEND flag as the third parameter. This is extremely important, as it tells the file_put_contents function to log our data at the end of the file. Without it, PHP would overwrite any existing data.

After running the code above, the following text was written to my log:

Facebook Comments