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
经典的PHPer为什么被认为是草根?
Apr 02 PHP
IStream与TStream之间的相互转换
Aug 01 PHP
PHP5.3.1 不再支持ISAPI
Jan 08 PHP
php 求质素(素数) 的实现代码
Apr 12 PHP
解析PHP计算页面执行时间的实现代码
Jun 18 PHP
curl不使用文件存取cookie php使用curl获取cookie示例
Jan 26 PHP
Yii不依赖Model的表单生成器用法实例
Dec 04 PHP
php实现获取文件mime类型的方法
Feb 11 PHP
php实现按天数、星期、月份查询的搜索框
May 02 PHP
PHP常用函数总结(180多个)
Dec 25 PHP
phpstudy默认不支持64位php的解决方法
Feb 20 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 无限分类的树类代码
2009/12/03 PHP
PHP5中使用DOM控制XML实现代码
2010/05/07 PHP
php入门学习知识点六 PHP文件的读写操作代码
2011/07/14 PHP
PHP得到某段时间区间的时间戳 php定时任务
2012/04/12 PHP
PHP简单实现数字分页功能示例
2016/08/24 PHP
PHP批量删除jQuery操作
2017/07/23 PHP
Extjs学习笔记之八 继承和事件基础
2010/01/08 Javascript
extjs grid设置某列背景颜色和字体颜色的方法
2010/09/03 Javascript
js indexOf()定义和用法
2012/10/21 Javascript
javascript计算用户打开网页的停留时间
2014/01/09 Javascript
JavaScript实现点击按钮切换网页背景色的方法
2015/10/17 Javascript
详解vue跨组件通信的几种方法
2017/06/15 Javascript
JS设计模式之访问者模式定义与用法分析
2018/02/05 Javascript
NodeJS加密解密及node-rsa加密解密用法详解
2018/10/12 NodeJs
详解基于iview-ui的导航栏路径(面包屑)配置
2019/02/22 Javascript
简单两步使用node发送qq邮件的方法
2019/03/01 Javascript
Vue中util的工具函数实例详解
2019/07/08 Javascript
Python中计算三角函数之cos()方法的使用简介
2015/05/15 Python
python实现旋转和水平翻转的方法
2018/10/25 Python
python实现Flappy Bird源码
2018/12/24 Python
python-itchat 统计微信群、好友数量,及原始消息数据的实例
2019/02/21 Python
Python图像处理之图片文字识别功能(OCR)
2019/07/30 Python
Python实现线性判别分析(LDA)的MATLAB方式
2019/12/09 Python
基于pycharm实现批量修改变量名
2020/06/02 Python
Python实现我的世界小游戏源代码
2021/03/02 Python
英国轻奢珠宝品牌:Astley Clarke
2016/12/18 全球购物
奢华时尚的创新平台:Baltini
2020/10/03 全球购物
寻找迷宫的一条出路,o通路;X:障碍
2016/07/10 面试题
先进班级集体事迹材料
2014/01/30 职场文书
三好学生个人先进事迹材料
2014/05/17 职场文书
团支部推优材料
2014/05/21 职场文书
中学生勤俭节约倡议书
2015/04/29 职场文书
部门主管竞聘书
2015/09/15 职场文书
体育部部长竞选稿
2015/11/21 职场文书
Mysql 如何查询时间段交集
2021/06/08 MySQL
总结三种用 Python 作为小程序后端的方式
2022/05/02 Python