天空小小岛技术论坛

 找回密码
 注册
搜索
查看: 7998|回复: 0
打印 上一主题 下一主题

[其他] PHP4.x 下自定义函数 file_put_contents , 完全模拟

[复制链接]
跳转到指定楼层
1#
一粒米 发表于 2010-5-26 18:23:56 | 只看该作者 回帖奖励 |正序浏览 |阅读模式
  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. ?>
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|天空小小岛  |京ICP备2025130156号|

GMT+8, 2025-6-22 00:49 , Processed in 0.089959 second(s), 20 queries , Gzip On.

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表