Log String or Array to File

Description: This snippet will write a string or a single dimension array of strings to file. It also has the optional parameter to for if you want to add a timestamp to it.
Tested Platform: PHP 5
Language: PHP
// Writes a string or an array of strings to a specified file.
// Expects: filename and a string or array of strings.
// Returns: True or false on success/failure

function logToFile($filename, $strItem, $prependTimeStamp = false) {
     if (file_exists($filename)) { 
          if (!is_writable($filename)) { return false; }
     }
		
     $timeStamp = ($prependTimeStamp !== false) ? "[" . date("Y-m-d H:i:s") . "] " : "";
		
     $fptr = @fopen($filename,"a");
     if ($fptr) {
          if (is_array($strItem)) {
               foreach ($strItem as $key => $value) {
                    fwrite($fptr, $timeStamp . $value . "\n");
               }
          }
          else {
               fwrite($fptr, $timeStamp . $strItem . "\n");
          }
          fclose($fptr);
          return true;
     }
     return false;
}

Submitted: December 24, 2012

Return to the snippets listing