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数据库的一些要注意的问题
Oct 09 PHP
PHP采集相关教程之一 CURL函数库
Feb 15 PHP
php快速url重写 更新版[需php 5.30以上]
Apr 20 PHP
使用session判断用户登录用户权限(超简单)
Jun 08 PHP
php+ajax实现无刷新分页的方法
Nov 04 PHP
试用php中oci8扩展
Jun 18 PHP
分享微信扫码支付开发遇到问题及解决方案-附Ecshop微信支付插件
Aug 23 PHP
浅析PHP关键词替换的类(避免重复替换,保留与还原原始链接)
Sep 22 PHP
Yii 2.0实现联表查询加搜索分页的方法示例
Aug 02 PHP
ThinkPHP5.0框架使用build 自动生成模块操作示例
Apr 11 PHP
laravel 数据迁移与 Eloquent ORM的实现方法
Apr 12 PHP
PHP获取学生成绩的方法
Nov 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 echo,print,printf,sprintf函数之间的区别与用法详解
2013/11/27 PHP
php实现上传图片保存到数据库的方法
2015/02/11 PHP
php遍历替换目录下文件指定内容的方法
2016/11/10 PHP
jquery实现类似EasyUI的页面布局可改变左右的宽度
2020/09/12 Javascript
JavaScript插件化开发教程 (三)
2015/01/27 Javascript
js鼠标点击按钮切换图片-图片自动切换-点击左右按钮切换特效代码
2015/09/02 Javascript
Angularjs中使用Filters详解
2016/03/11 Javascript
javascript 小数乘法结果错误的处理方法
2016/07/28 Javascript
JS设置时间无效问题的解决办法
2017/02/18 Javascript
Angular.js中$resource高大上的数据交互详解
2017/07/30 Javascript
详解Nodejs mongoose
2018/06/10 NodeJs
Vue中实现权限控制的方法示例
2019/06/07 Javascript
浅谈vue中$event理解和框架中在包含默认值外传参
2020/08/07 Javascript
python利用beautifulSoup实现爬虫
2014/09/29 Python
python关闭windows进程的方法
2015/04/18 Python
Python正规则表达式学习指南
2016/08/02 Python
python之PyMongo使用总结
2017/05/26 Python
解决安装tensorflow遇到无法卸载numpy 1.8.0rc1的问题
2018/06/13 Python
python实时获取外部程序输出结果的方法
2019/01/12 Python
深入解析Python小白学习【操作列表】
2019/03/23 Python
使用python接入微信聊天机器人
2020/03/31 Python
应用OpenCV和Python进行SIFT算法的实现详解
2019/08/21 Python
Python3和pyqt5实现控件数据动态显示方式
2019/12/13 Python
python 使用递归实现打印一个数字的每一位示例
2020/02/27 Python
突袭HTML5之Javascript API扩展1—Web Worker异步执行及相关概述
2013/01/31 HTML / CSS
美国职棒大联盟官方网上商店:MLBShop.com
2017/11/12 全球购物
英国领先的瓷砖专家:Walls and Floors
2018/04/27 全球购物
英国游戏机和游戏购物网站:365games.co.uk
2018/06/18 全球购物
意大利咖啡、浓缩咖啡和浓缩咖啡机:illy caffe
2019/03/20 全球购物
绝对经典成功的大学生推荐信
2013/11/08 职场文书
市场开发与营销专业求职信
2013/12/31 职场文书
党员组织关系介绍信
2014/02/13 职场文书
年度献血先进个人事迹材料
2014/02/14 职场文书
《小动物过冬》教学反思
2014/04/17 职场文书
群众路线教育实践活动对照检查材料思想汇报(副处级领导)
2014/10/04 职场文书
千与千寻观后感
2015/06/04 职场文书