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 7+
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;
}

Posted: March 18, 2023

Return to the snippets listing