CodeSOD: A Large Ol' Log

[ad_1]

We've already picked on dangerous logging code this week, however we haven't picked on PHP in awhile, so let's have a look at some dangerous PHP logging code, from Kris.

        $path = self::getPath();

        if (file_exists($path)) {
            $content material = file_get_contents($path);
        } else {
            $content material = "";
        }
        $content material .= "n" . date('Y-m-d H:i') . " | " . $message;
        file_put_contents($path, $content material);

That is the inside of the log perform, which takes a logging message and outputs it to a file.

The "magic" on this code is the decision to file_get_contents, which masses a complete file into reminiscence as a string. That is performed for each log message. We load the complete file, append the brand new message, after which write the whole string again to the file. And, I'm not sure about PHP's concatenate implementation, but when it's like most languages, strings are immutable, and I think this makes a full copy of the unique file contents as a part of concatenation.

For small log recordsdata, that is dangerous. This explicit software incessantly ended up with multi-gigabyte log recordsdata. This, because it turned out, wasn't good for efficiency, however was a superb approach to make use of as a lot RAM as attainable and stress check their disk.

[Advertisement]
Otter – Provision your servers robotically with out ever needing to log-in to a command immediate. Get began in the present day!

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *