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 相关文章推荐
拼音码表的生成
Oct 09 PHP
第十一节--重载
Nov 16 PHP
使用TinyButStrong模板引擎来做WEB开发
Mar 16 PHP
php中邮箱地址正则表达式实现与详解
Apr 24 PHP
基于PHP+Ajax实现表单验证的详解
Jun 25 PHP
php生成excel列序号代码实例
Dec 24 PHP
php目录遍历函数opendir用法实例
Nov 20 PHP
php实现随机生成易于记忆的密码
Jun 19 PHP
利用PHP脚本在Linux下用md5函数加密字符串的方法
Jun 29 PHP
php中array_column函数简单实现方法
Jul 11 PHP
PHP排序算法之归并排序(Merging Sort)实例详解
Apr 21 PHP
thinkphp5修改view到根目录实例方法
Jul 02 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中header和session_start前不能有输出原因分析
2013/01/11 PHP
php+mysql实现无限分类实例详解
2015/01/15 PHP
Yii框架多语言站点配置方法分析【中文/英文切换站点】
2020/04/07 PHP
用jquery实现下拉菜单效果的代码
2010/07/25 Javascript
JS常用正则表达式总结
2013/11/12 Javascript
Node.js中HTTP模块与事件模块详解
2014/11/14 Javascript
对比分析json及XML
2014/11/28 Javascript
JavaScript中DOM详解
2015/04/13 Javascript
jquery操作select元素和option的实例代码
2016/02/03 Javascript
JS简单实现表格排序功能示例
2016/12/20 Javascript
js实现动态改变radio状态的方法
2018/02/28 Javascript
从源码里了解vue中的nextTick的使用
2018/11/22 Javascript
webpack-mvc 传统多页面组件化开发详解
2019/05/07 Javascript
浅谈Vue的响应式原理
2019/05/30 Javascript
Vue路由模块化配置的完整步骤
2019/08/14 Javascript
微信小程序实现聊天室
2020/08/21 Javascript
JQuery基于FormData异步提交数据文件
2020/09/01 jQuery
5个很好的Python面试题问题答案及分析
2018/01/19 Python
详解python单元测试框架unittest
2018/07/02 Python
python matlibplot绘制多条曲线图
2021/02/19 Python
在Python运行时动态查看进程内部信息的方法
2019/02/22 Python
10行Python代码实现Web自动化管控的示例代码
2020/08/14 Python
使用tensorflow进行音乐类型的分类
2020/08/14 Python
借助HTML5 Canvas来绘制三角形和矩形等多边形的方法
2016/03/14 HTML / CSS
Laura Geller官网:美国彩妆品牌
2018/12/29 全球购物
物流专业大学生求职信范文
2013/10/28 职场文书
法学毕业生自荐信
2013/11/13 职场文书
大学校庆策划书
2014/01/31 职场文书
学习全国两会精神心得体会范文
2014/03/17 职场文书
感恩母亲节演讲稿
2014/05/07 职场文书
护士节策划方案
2014/05/19 职场文书
2014县委书记四风对照检查材料思想汇报
2014/09/21 职场文书
事业单位考察材料范文
2014/12/25 职场文书
民事起诉状范文
2015/05/19 职场文书
新员工实习期个人工作总结
2015/10/15 职场文书
一文带你理解vue创建一个后台管理系统流程(Vue+Element)
2021/05/18 Vue.js