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 相关文章推荐
PHP5 安装方法
Oct 09 PHP
针对初学PHP者的疑难问答(2)
Oct 09 PHP
来自PHP.NET的入门教程
Oct 09 PHP
php中iconv函数使用方法
May 24 PHP
phpinfo 系统查看参数函数代码
Jun 05 PHP
ExtJS与PHP、MySQL实现存储的方法
Apr 02 PHP
Windows7下PHP开发环境安装配置图文方法
May 20 PHP
php分页思路以及在ZF中的使用
May 30 PHP
PHP实现加密的几种方式介绍
Feb 22 PHP
PHP登录验证功能示例【用户名、密码、验证码、数据库、已登陆验证、自动登录和注销登录等】
Feb 25 PHP
php利用array_search与array_column实现二维数组查找
Jul 08 PHP
php array_map()函数实例用法
Mar 03 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计算页面执行时间的实现代码
2013/06/18 PHP
ThinkPHP之M方法实例详解
2014/06/20 PHP
php中ob_flush函数和flush函数用法分析
2015/03/18 PHP
php实现专业获取网站SEO信息类实例
2015/04/02 PHP
JavaScript Prototype对象
2009/01/07 Javascript
IE的事件传递-event.cancelBubble示例介绍
2014/01/12 Javascript
jquery实现多条件筛选特效代码分享
2015/08/28 Javascript
Javascript基于对象三大特性(封装性、继承性、多态性)
2016/01/04 Javascript
jQuery实现的兼容性浮动层示例
2016/08/02 Javascript
Node.js connect ECONNREFUSED错误解决办法
2016/09/15 Javascript
jquery网页日历显示控件calendar3.1使用详解
2016/11/24 Javascript
概述BootStrap中role=&quot;form&quot;及role作用角色
2016/12/08 Javascript
js学习总结之dom2级事件基础知识详解
2017/07/27 Javascript
JS实现移动端触屏拖拽功能
2018/07/31 Javascript
微信小程序中显示倒计时代码实例
2019/05/09 Javascript
vue.js基于v-for实现批量渲染 Json数组对象列表数据示例
2019/08/03 Javascript
vue 使用高德地图vue-amap组件过程解析
2019/09/07 Javascript
python中xrange和range的区别
2014/05/13 Python
Python 正则表达式实现计算器功能
2017/04/29 Python
关于python的list相关知识(推荐)
2017/08/30 Python
Python快速查找list中相同部分的方法
2018/06/27 Python
完美解决Django2.0中models下的ForeignKey()问题
2020/05/19 Python
全球性的在线商店:Vogca
2019/05/10 全球购物
在线实验室测试:HealthLabs.com
2020/05/03 全球购物
怎么处理XML的中文问题
2015/03/26 面试题
饲料采购员岗位职责
2013/12/19 职场文书
党员批评与自我批评发言
2014/10/02 职场文书
大学生在校表现评语
2014/12/31 职场文书
助学感谢信范文
2015/01/21 职场文书
房产销售员2015年终工作总结
2015/10/22 职场文书
2016年教师党员公开承诺书
2016/03/24 职场文书
python中Tkinter 窗口之输入框和文本框的实现
2021/04/12 Python
简单聊聊Vue中的计算属性和属性侦听
2021/10/05 Vue.js
交互式可视化js库gojs使用介绍及技巧
2022/02/18 Javascript
十大最强格斗系宝可梦,超梦X仅排第十,第二最重格斗礼仪
2022/03/18 日漫
Hive日期格式转换方法总结
2022/06/25 数据库