Since file_put_contents() is not included in PHP 4, I wrote a function to allow its use for anyone still on legacy versions.

It has been tested on Windows, but not Linux. However, the f* functions should behave in the same manner.

Usage

$tmpfname = tempnam("C:\\\\foo.txt", "Foo bar");
echo file_put_contents($tmpfname, "Some text"); // "7"

Code

function file_put_contents($filename, $data, $flags = 0, $context = null) {
    $includePath = false;
    if ($flags & FILE_USE_INCLUDE_PATH)
        $includePath = true;

    $appendToFile = false;
    if ($flags & FILE_APPEND)
        $appendToFile = true;

    if ($context != null) {
        $resource = fopen($filename, $appendToFile ? "a" : "w", $includePath, $context);
    } else {
        $resource = fopen($filename, $appendToFile ? "a" : "w", $includePath);
    }

    if ($flags & LOCK_EX)
        flock($resource, LOCK_EX);

    if (is_array($data))
        $data = implode("", $data);
    $bytes = fwrite($resource, $data);

    if (PHP_VERSION_ID > 50302 && $flags & LOCK_EX)
        flock($resource, LOCK_UN);

    fclose($resource);

    return $bytes;
}

Next Post Previous Post