天空小小岛技术网站

标题: PHP4.x 下自定义函数 file_put_contents , 完全模拟 [打印本页]

作者: 一粒米    时间: 2010-5-26 18:23
标题: PHP4.x 下自定义函数 file_put_contents , 完全模拟
  1. <?php
  2. //note 兼容 PHP 4 无 file_put_contents 函数
  3. if (!function_exists('file_put_contents')) {
  4.         function file_put_contents($filename, $content, $flags = null, $resource_context = null) {
  5.                 //note 数组转成字符串
  6.                 if (is_array($content)) {
  7.                         $content = implode('', $content);
  8.                 }

  9.                 //note 写入的数据必须是标量
  10.                 if (!is_scalar($content)) {
  11.                         trigger_error('file_put_contents(): supplied resource is not a valid stream resource', E_USER_WARNING);
  12.                         return false;
  13.                 }

  14.                 //note 获取数据长度
  15.                 $length = strlen($content);

  16.                 //note 确定写入模式
  17.                 $mode = ($flags & FILE_APPEND) ? $mode = 'a' : $mode = 'w';

  18.                 //note 检查是否使用内置路径
  19.                 $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH) ? true : false;

  20.                 //note 打开文件准备写入
  21.                 if (($fh = @fopen($filename, $mode, $use_inc_path)) === false) {
  22.                         trigger_error('file_put_contents(): failed to open stream: Permission denied', E_USER_WARNING);
  23.                         return false;
  24.                 }

  25.                 //note 写入文件
  26.                 $bytes = 0;
  27.                 if (($bytes = @fwrite($fh, $content)) === false) {
  28.                         $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s', $length, $filename);
  29.                         trigger_error($errormsg, E_USER_WARNING);
  30.                         return false;
  31.                 }

  32.                 //note 关闭
  33.                 @fclose($fh);

  34.                 //note 检查写入是否正常
  35.                 if ($bytes != $length) {
  36.                         $errormsg = sprintf('file_put_contents(): Only %d of %d bytes written, possibly out of free disk space.', $bytes, $length);
  37.                         trigger_error($errormsg, E_USER_WARNING);
  38.                         return false;
  39.                 }

  40.                 //note 返回写入到文件内数据的字节数
  41.                 return $bytes;
  42.         }
  43. }
  44. ?>
复制代码





欢迎光临 天空小小岛技术网站 (http://tkxxd.net/) Powered by Discuz! X3.1