2
\$\begingroup\$

This might not even warrant posting here, but I"m enjoying it and thought I would share.

//For Testing
function write_to_file($message){
        $handle = fopen("/path/to/logs/a_log_file.php", "a+");
        if (is_array($message)):
            fwrite($handle, "\nMessage is array.\t ");
            fclose($handle);
            file_put_contents('/path/to/logs/a_log_file.php', print_r($message, true),
                              FILE_APPEND | LOCK_EX);
        else:
            fwrite($handle, "\nMessage:\t " . $message);
            fclose($handle);
        endif;

        }

Haven't actually tested with multidimensional array yet and might be a good opportunity for some recursion.

Comments, suggestions and criticism are of course welcome.

\$\endgroup\$
2
\$\begingroup\$

Mixing fwrite and file_put_contents usage is a little strange, as they are functions which overlap in functionality. file_put_contents in fact is just a wrapper to call fopen, fwrite and fclose - expanding that call to it's component parts would therefore make what the code is doing more obviously repetitive.

So, the first goal I would suggest is to avoid repeatedly opening the file to append text to it; the goal of the function is simply to append bytes to a file - so make the function do that, in one write call. An example of what I mean is:

function write_to_file($message)
{
    $header = "\nMessage:\t ";

    if (is_array($message)) {
        $header = "\nMessage is array.\n";
        $message = print_r($message, true);
    }

    file_put_contents(
        '/path/to/logs/a_log_file.php', 
        $header . $message, 
        FILE_APPEND | LOCK_EX
    );
}
|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ very nice, and insightful as far as file_put_contents. \$\endgroup\$ – MikeiLL Nov 6 '15 at 0:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.