How to Implement file_put_contents and file_get_contents in PHP?


We can implement (re-invent the wheel) file_put_contents and file_get_contents in PHP to write string to a file and read content as a string from file.

file_put_contents is a PHP5 function that writes a string into a file. It is a very convenient function to allow fast logging, caching etc. Due to backward compatability, PHP code using this function will not run in PHP4. You can simply add the following to enable this function in PHP4. However, the PHP process needs the write permission for file writing.

1
2
3
4
5
6
7
8
9
10
if (!function_exists("file_put_contents")) {
  function file_put_contents($filename, $filedata) {
    if ($fp = fopen($filename, "wb")) {
      fwrite($fp, $filedata);
      fclose($fp);
      return(true);
    }
    return(false);
  }
}
if (!function_exists("file_put_contents")) {
  function file_put_contents($filename, $filedata) {
    if ($fp = fopen($filename, "wb")) {
      fwrite($fp, $filedata);
      fclose($fp);
      return(true);
    }
    return(false);
  }
}

Using function_exisits will suppress the error of including (and require) the file more than once. It may be a better approach than include_once, require_once. Similarly, the file_get_contents can be substitute by the following. However, file_get_contents is supported in both PHP4 (Version >= 4.3.0) and PHP5.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (!function_exists('file_get_contents')) {
  function file_get_contents($filename) {
    if ($fp = fopen($filename, "rb")) {
      $rawData = "";
      do {
        $buffer = fread($fp, 8192);
        $rawData .= $buffer;
      } while (strlen($buffer) > 0);
      fclose($fp);
      return($rawData);
    }
    return(false);
  }
}
if (!function_exists('file_get_contents')) {
  function file_get_contents($filename) {
    if ($fp = fopen($filename, "rb")) {
      $rawData = "";
      do {
        $buffer = fread($fp, 8192);
        $rawData .= $buffer;
      } while (strlen($buffer) > 0);
      fclose($fp);
      return($rawData);
    }
    return(false);
  }
}

See also: The Java Method to Read Content of File into a String

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
297 words
Last Post: Downloading URL using Python
Next Post: Javascript Page404 Colour Screen

The Permanent URL is: How to Implement file_put_contents and file_get_contents in PHP?

Leave a Reply