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速度全攻略
Oct 09 PHP
下载文件的点击数回填
Oct 09 PHP
解密ThinkPHP3.1.2版本之模板继承
Jun 19 PHP
几道坑人的PHP面试题 试试看看你会不会也中招
Aug 19 PHP
ThinkPHP V2.2说明文档没有说明的那些事实例小结
Jul 01 PHP
使用PHP实现生成HTML静态页面
Nov 18 PHP
PHP PDOStatement::fetchColumn讲解
Jan 31 PHP
php实现的支付宝网页支付功能示例【基于TP5框架】
Sep 16 PHP
php模式设计之观察者模式应用实例分析
Sep 25 PHP
php更新cookie内容的详细方法
Sep 30 PHP
php上传后台无法收到数据解决方法
Oct 28 PHP
PhpStorm2020.1 安装 debug - Postman 调用的详细教程
Aug 17 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开发模式(简写版)
2007/03/15 PHP
php实现查询百度google收录情况(示例代码)
2013/08/02 PHP
PHP高效获取远程图片尺寸和大小的实现方法
2017/10/20 PHP
Laravel中为什么不使用blpop取队列详析
2018/08/01 PHP
PHP 二维array转换json的实例讲解
2018/08/21 PHP
event对象的方法 兼容多浏览器
2009/06/27 Javascript
jquery 常用操作整理 基础入门篇
2009/10/14 Javascript
再谈javascript面向对象编程
2012/03/18 Javascript
ExtJS下书写动态生成的xml(兼容火狐)
2013/04/02 Javascript
js类式继承的具体实现方法
2013/12/31 Javascript
js实现图片拖动改变顺序附图
2014/05/13 Javascript
JavaScript lastIndexOf方法入门实例(计算指定字符在字符串中最后一次出现的位置)
2014/10/17 Javascript
JS表格组件神器bootstrap table详解(基础版)
2015/12/08 Javascript
Linux下为Node.js程序配置MySQL或Oracle数据库的方法
2016/03/19 Javascript
折叠菜单及选择器的运用
2017/02/03 Javascript
vue2.0实现倒计时的插件(时间戳 刷新 跳转 都不影响)
2017/03/30 Javascript
微信小程序 检查接口状态实例详解
2017/06/23 Javascript
JavaScript之DOM插入更新删除_动力节点Java学院整理
2017/07/03 Javascript
微信小程序实现动态获取元素宽高的方法分析
2018/12/10 Javascript
JS实现骰子3D旋转效果
2019/10/24 Javascript
vue点击页面空白处实现保存功能
2019/11/06 Javascript
vue+vuex+axios从后台获取数据存入vuex,组件之间共享数据操作
2020/07/31 Javascript
three.js中多线程的使用及性能测试详解
2021/01/07 Javascript
Python通过RabbitMQ服务器实现交换机功能的实例教程
2016/06/29 Python
Python中几种导入模块的方式总结
2017/04/27 Python
详解Python使用tensorflow入门指南
2018/02/09 Python
Python 对输入的数字进行排序的方法
2018/06/23 Python
浅谈Python的方法解析顺序(MRO)
2020/03/05 Python
Python实现UDP程序通信过程图解
2020/05/15 Python
详解用Python爬虫获取百度企业信用中企业基本信息
2020/07/02 Python
幼儿园综治宣传月活动总结
2015/05/07 职场文书
教师理论学习心得体会
2016/01/21 职场文书
详解TypeScript中的类型保护
2021/04/29 Javascript
tensorflow中的梯度求解及梯度裁剪操作
2021/05/26 Python
使用Python+OpenCV进行卡类型及16位卡号数字的OCR功能
2021/08/30 Python
详解nginx安装过程并代理下载服务器文件
2022/02/12 Servers