- <?php
- //note 兼容 PHP 4 无 file_put_contents 函数
- if (!function_exists('file_put_contents')) {
- function file_put_contents($filename, $content, $flags = null, $resource_context = null) {
- //note 数组转成字符串
- if (is_array($content)) {
- $content = implode('', $content);
- }
- //note 写入的数据必须是标量
- if (!is_scalar($content)) {
- trigger_error('file_put_contents(): supplied resource is not a valid stream resource', E_USER_WARNING);
- return false;
- }
- //note 获取数据长度
- $length = strlen($content);
- //note 确定写入模式
- $mode = ($flags & FILE_APPEND) ? $mode = 'a' : $mode = 'w';
- //note 检查是否使用内置路径
- $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH) ? true : false;
- //note 打开文件准备写入
- if (($fh = @fopen($filename, $mode, $use_inc_path)) === false) {
- trigger_error('file_put_contents(): failed to open stream: Permission denied', E_USER_WARNING);
- return false;
- }
- //note 写入文件
- $bytes = 0;
- if (($bytes = @fwrite($fh, $content)) === false) {
- $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s', $length, $filename);
- trigger_error($errormsg, E_USER_WARNING);
- return false;
- }
- //note 关闭
- @fclose($fh);
- //note 检查写入是否正常
- if ($bytes != $length) {
- $errormsg = sprintf('file_put_contents(): Only %d of %d bytes written, possibly out of free disk space.', $bytes, $length);
- trigger_error($errormsg, E_USER_WARNING);
- return false;
- }
- //note 返回写入到文件内数据的字节数
- return $bytes;
- }
- }
- ?>
复制代码 |