Fatal error: Call to undefined function: file_put_contents()

Two functions that I’ve found invaluable recently have been file_get_contents() and file_put_contents(). When used along with serialize(), these have allowed me to maintain very simple “databases” using files in the directory, rather than having to store data in specially made MySQL tables.

One of the interesting things I discovered when trying to use these functions on a different machine today, is that file_get_contents is supported after PHP 4.3.0, while file_put_contents is only supported in PHP 5.

If your system doesn’t support file_put_contents, you’ll probably run into the following error message:

Fatal error: Call to undefined function: file_put_contents()

All you need to do to make sure your code can be run on older versions of PHP is to include the following code:

<?php
  if(!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data, $file_append = false) {
      $fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
        if(!$fp) {
          trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
          return;
        }
      fputs($fp, $data);
      fclose($fp);
    }
  }
?>

This checks to see if the file_put_contents function exists, and uses a custom declaration of the function if it doesn’t.

Voila!

[via drupal]