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为什么选mysql作为数据库? Mysql 创建用户方法
Jul 02 PHP
php数组函数序列之array_pop() - 删除数组中的最后一个元素
Nov 07 PHP
Java中final关键字详解
Aug 10 PHP
PHP上传文件参考配置大文件上传
Dec 16 PHP
php中preg_replace_callback函数简单用法示例
Jul 21 PHP
PHP基于MySQLI函数封装的数据库连接工具类【定义与用法】
Aug 11 PHP
Yii2语言国际化的配置教程
Aug 19 PHP
PHP PDOStatement::rowCount讲解
Feb 01 PHP
使用tp框架和SQL语句查询数据表中的某字段包含某值
Oct 18 PHP
yii框架结合charjs实现统计30天数据的方法
Apr 04 PHP
解决PhpStorm64不能启动的问题
Jun 20 PHP
详解phpstorm2020最新破解方法
Sep 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
Discuz!5的PHP代码高亮显示插件(黑暗中的舞者更新)
2007/01/29 PHP
基于PHP生成简单的验证码
2016/06/01 PHP
W3C Group的JavaScript1.8 新特性介绍
2009/05/19 Javascript
Javascript/Jquery——简单定时器的多种实现方法
2013/07/03 Javascript
js触发select onchange事件的小技巧
2014/08/05 Javascript
javascript随机显示背景图片的方法
2015/06/18 Javascript
Jquery检验手机号是否符合规则并根据手机号检测结果将提交按钮设为不同状态
2015/11/26 Javascript
JS使用onerror捕获异常示例
2016/08/03 Javascript
JS原型链 详解及示例代码
2016/09/06 Javascript
JS判断来路是否是百度等搜索索引进行弹窗或自动跳转的实现代码
2016/10/09 Javascript
浅谈javascript中的 “ &amp;&amp; ” 和 “ || ”
2017/02/02 Javascript
js return返回多个值,通过对象的属性访问方法
2017/02/21 Javascript
node-sass安装失败的原因与解决方法
2017/09/04 Javascript
JS实现的将html转为pdf功能【基于浏览器端插件jsPDF】
2018/02/06 Javascript
详解Angular6.0使用路由步骤(共7步)
2018/06/29 Javascript
JavaScript基础教程之如何实现一个简单的promise
2018/09/11 Javascript
highCharts提示框中显示当前时间的方法
2019/01/18 Javascript
Vue 子组件与数据传递问题及注意事项
2019/07/11 Javascript
Layui 动态禁止select下拉的例子
2019/09/03 Javascript
[41:20]2014 DOTA2华西杯精英邀请赛 5 24 NewBee VS DK
2014/05/26 DOTA
Python实现控制台进度条功能
2016/01/04 Python
利用Python实现颜色色值转换的小工具
2016/10/27 Python
python中 chr unichr ord函数的实例详解
2017/08/06 Python
Python list运算操作代码实例解析
2020/01/20 Python
Python3.7安装pyaudio教程解析
2020/07/24 Python
15个Pythonic的代码示例(值得收藏)
2020/10/29 Python
完美解决Pycharm中matplotlib画图中文乱码问题
2021/01/11 Python
BIFFI美国站:意大利BIFFI BOUTIQUES豪华多品牌时装零售公司
2020/02/11 全球购物
团员个人的自我评价
2013/12/02 职场文书
母亲七十大寿答谢词
2014/01/18 职场文书
财务总经理岗位职责
2014/02/16 职场文书
单位活动策划方案
2014/08/17 职场文书
运动会400米加油稿(8篇)
2014/09/22 职场文书
小学二年级数学教学计划
2015/01/20 职场文书
母亲节主题班会
2015/08/14 职场文书
深入理解以DEBUG方式线程的底层运行原理
2021/06/21 Java/Android