Wow, this thread has been resurrected from January last year 🙂
I found quoting the $data variable helpful to recognize a simple number as a string.
If you do that, is_string() must always return true since you are casting $data to string. With that in mind, I think that one can actually just skip the validation and typecast immediately.
You are returning here without closing your file resource ...
That probably doesnt matter for the most part since the file would be closed anyway when the script ends. Still, one does not even need to check the return value of fwrite() since it returns false if the write fails.
Adding support for the exclusive lock option, I would contribute:
if (!function_exists('file_put_contents')) {
// Define flags related to file_put_contents(), if necessary
if (!defined('FILE_USE_INCLUDE_PATH')) {
define('FILE_USE_INCLUDE_PATH', 1);
}
if (!defined('FILE_APPEND')) {
define('FILE_APPEND', 8);
}
function file_put_contents($filename, $data, $flags = 0) {
// Handle single dimensional array data
if (is_array($data)) {
// Join the array elements
$data = implode('', $data);
}
// Flags should be an integral value
$flags = (int)$flags;
// Set the mode for fopen(), defaulting to 'wb'
$mode = ($flags & FILE_APPEND) ? 'ab' : 'wb';
$use_include_path = (bool)($flags & FILE_USE_INCLUDE_PATH);
// Open file with filename as a string
if ($fp = fopen("$filename", $mode, $use_include_path)) {
// Acquire exclusive lock if requested
if ($flags & LOCK_EX) {
if (!flock($fp, LOCK_EX)) {
fclose($fp);
return false;
}
}
// Write the data as a string
$bytes = fwrite($fp, "$data");
// Release exclusive lock if it was acquired
if ($flags & LOCK_EX) {
flock($fp, LOCK_UN);
}
fclose($fp);
return $bytes; // number of bytes written
} else {
return false;
}
}
}