PHP实现的文件操作类及文件下载功能示例


Posted in PHP onDecember 24, 2016

本文实例讲述了PHP实现的文件操作类及文件下载功能。分享给大家供大家参考,具体如下:

文件操作类:

<?php
 // Copyright 2005, Lee Babin (lee@thecodeshoppe.com)
 // This code may be used and redistributed without charge
 // under the terms of the GNU General Public
 // License version 2.0 or later -- www.gnu.org
 // Subject to the retention of this copyright
 // and GPL Notice in all copies or derived works
 class cfile {
  //The path to the file we wish to work with.
  protected $thepath;
  //Error messages in the form of constants for ease of use.
  const FOUNDERROR = "Sorry, the file in question does not exist.";
  const PERMERROR = "Sorry, you do not have the proper permissions on this file";
  const OPENERROR = "Sorry, the file in question could not be opened.";
  const CLOSEERROR = "Sorry, the file could not be closed.";
  //The constructor function.
  public function __construct (){
   $num_args = func_num_args();
   if($num_args > 0){
    $args = func_get_args();
    $this->thepath = $args[0];
   }
  }
  //A function to open the file.
  private function openfile ($readorwrite){
    //First, ensure the file exists.
    try {
      if (file_exists ($this->thepath)){
        //Now, we need to see if we are reading or writing or both.
        $proceed = false;
        if ($readorwrite == "r"){
          if (is_readable($this->thepath)){
            $proceed = true;
          }
        } elseif ($readorwrite == "w"){
          if (is_writable($this->thepath)){
            $proceed = true;
          }
        } else {
          if (is_readable($this->thepath) && is_writable($this->thepath)){
            $proceed = true;
          }
        }
        try {
          if ($proceed){
            //We can now attempt to open the file.
            try {
              if ($filepointer = fopen ($this->thepath, $readorwrite)){
                return $filepointer;
              } else {
                throw new exception (self::OPENERROR);
                return false;
              }
            } catch (exception $e) {
              echo $e->getmessage();
            }
          } else {
            throw new exception (self::PERMERROR);
          }
        } catch (exception $e) {
          echo $e->getmessage();
        }
      } else {
        throw new exception (self::FOUNDERROR);
      }
    } catch (exception $e) {
      echo $e->getmessage();
    }
  }
  //A function to close a file.
  function closefile () {
    try {
      if (!fclose ($this->thepath)){
        throw new exception (self::CLOSEERROR);
      }
    } catch (exception $e) {
      echo $e->getmessage();
    }
  }
  //A function to read a file, then return the results of the read in a string.
  public function read () {
    //First, attempt to open the file.
    $filepointer = $this->openfile ("r");
    //Now, return a string with the read data.
    if ($filepointer != false){
      //Then we can read the file.
      return fgets ($filepointer);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to write to a file.
  public function write ($towrite) {
    //First, attempt to open the file.
    $filepointer = $this->openfile ("w");
    //Now, return a string with the read data.
    if ($filepointer != false){
      //Then we can read the file.
      return fwrite ($filepointer, $towrite);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to append to a file.
  public function append ($toappend) {
    //First, attempt to open the file.
    $filepointer = $this->openfile ("a");
    //Now, return a string with the read data.
    if ($filepointer != false){
      //Then we can read the file.
      return fwrite ($filepointer, $toappend);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to set the path to a new file.
  public function setpath ($newpath) {
    $this->thepath = $newpath;
  }
 }
?>
<?php
  $myfile = new cfile ("test.txt");
  //Now, let's try reading it.
  echo $myfile->read();
  //Then let's try writing to the file.
  $myfile->write ("Hello World!");
  //Then, let's try appending.
  $myfile->append ("Hello Again!");
?>

文件下载:

<?php
$filename = 'file1.txt';
$file = fopen($filename, 'r');
Header("Expires: 0");
Header("Pragma: public");
Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
Header("Cache-Control: public");
Header("Content-Length: ". filesize($filename));
Header("Content-Type: application/octet-stream");
Header("Content-Disposition: attachment; filename=".$filename);
readfile($filename);
?>

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP 和 COM
Oct 09 PHP
一个分页的论坛
Oct 09 PHP
php file_put_contents()功能函数(集成了fopen、fwrite、fclose)
May 24 PHP
PHP中怎样保持SESSION不过期 原理及方案介绍
Aug 08 PHP
php银联网页支付实现方法
Mar 04 PHP
PHP实现远程下载文件到本地
May 17 PHP
PHP通过CURL实现定时任务的图片抓取功能示例
Oct 03 PHP
PHP单态模式简单用法示例
Nov 16 PHP
PHP检查网站是否宕机的方法示例
Jul 24 PHP
php删除二维数组中的重复值方法
Mar 12 PHP
PHP 计算两个时间段之间交集的天数示例
Oct 24 PHP
PHP安全之register_globals的on和off的区别
Jul 23 PHP
PHP文件与目录操作示例
Dec 24 #PHP
PHP数组操作实例分析【添加,删除,计算,反转,排序,查找等】
Dec 24 #PHP
PHP常见字符串处理函数用法示例【转换,转义,截取,比较,查找,反转,切割】
Dec 24 #PHP
PHP会话控制实例分析
Dec 24 #PHP
PHP面向对象程序设计方法实例详解
Dec 24 #PHP
PHP数据库处理封装类实例
Dec 24 #PHP
如何判断php mysqli扩展类是否开启
Dec 24 #PHP
You might like
PHP自动生成表单代码分享
2015/06/19 PHP
PHP-FPM运行状态的实时查看及监控详解
2016/11/18 PHP
js 发个判断字符串是否为符合标准的函数
2009/04/27 Javascript
基于jsTree的无限级树JSON数据的转换代码
2010/07/27 Javascript
JS获取时间的方法
2015/01/21 Javascript
js实现数字每三位加逗号的方法
2015/02/05 Javascript
EasyUi combotree 实现动态加载树节点
2016/04/01 Javascript
jQuery悬停文字提示框插件jquery.tooltipster.js用法示例【附demo源码下载】
2016/07/19 Javascript
$.browser.msie 为空或不是对象问题的多种解决方法
2017/03/19 Javascript
Javascript中click与blur事件的顺序详析
2017/04/25 Javascript
json的结构与遍历方法实例分析
2017/04/25 Javascript
JavaScript中正则表达式判断匹配规则及常用方法
2017/08/03 Javascript
vue双花括号的使用方法 附练习题
2017/11/07 Javascript
vue 文件目录结构详解
2017/11/24 Javascript
使用Nuxt.js改造已有项目的方法
2018/08/07 Javascript
vue动态设置img的src路径实例
2018/09/18 Javascript
Layui实现数据表格默认全部显示(不要分页)
2019/10/26 Javascript
js实现数字滚动特效
2019/12/16 Javascript
手机浏览器唤起微信分享(JS)
2020/10/11 Javascript
[02:36]DOTA2亚洲邀请赛小组赛精彩集锦:奇迹哥卡尔秀翻全场
2017/03/28 DOTA
Tensorflow 同时载入多个模型的实例讲解
2018/07/27 Python
Python面向对象之静态属性、类方法与静态方法分析
2018/08/24 Python
numpy向空的二维数组中添加元素的方法
2018/11/01 Python
python简单实现AES加密和解密
2019/03/28 Python
django的ORM操作 删除和编辑实现详解
2019/07/24 Python
python3中的logging记录日志实现过程及封装成类的操作
2020/05/12 Python
Larsson & Jennings官网:现代瑞士钟表匠
2018/03/20 全球购物
DIY蛋糕店的创业计划书范文
2013/12/26 职场文书
给朋友的道歉信
2014/01/09 职场文书
秋季运动会加油稿200字
2014/01/11 职场文书
开学季活动策划方案
2014/02/28 职场文书
大学四年个人自我小结
2014/03/05 职场文书
小小商店教学反思
2014/04/27 职场文书
计算机系本科生求职信
2014/05/31 职场文书
写给医院的感谢信
2015/01/22 职场文书
Python函数式编程中itertools模块详解
2021/09/15 Python