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 相关文章推荐
PHP4实际应用经验篇(7)
Oct 09 PHP
PHP4在Windows2000下的安装
Oct 09 PHP
如何使用脚本模仿登陆过程
Nov 22 PHP
php下批量挂马和批量清马代码
Feb 27 PHP
PHP内核介绍及扩展开发指南―基础知识
Sep 11 PHP
利用浏览器的Javascript控制台调试PHP程序
Jan 08 PHP
php将session放入memcached的设置方法
Feb 14 PHP
PHP+Mysql树型结构(无限分类)数据库设计的2种方式实例
Jul 15 PHP
学习php开源项目的源码指南
Dec 21 PHP
Zend Framework教程之Zend_Layout布局助手详解
Mar 04 PHP
Laravel 5.5基于内置的Auth模块实现前后台登陆详解
Dec 21 PHP
PHP的微信支付接口使用方法讲解
Mar 08 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
中国广播史趣谈 — 几个历史第一次
2021/03/01 无线电
详解PHP的Yii框架的运行机制及其路由功能
2016/03/17 PHP
PHP获取当前时间不准确问题解决方案
2020/08/14 PHP
CSS常用网站布局实例
2008/04/03 Javascript
ExtJS 2.0实用简明教程 之获得ExtJS
2009/04/29 Javascript
javascript轻松实现当鼠标移开时已弹出子菜单自动消失
2013/12/29 Javascript
iframe的onreadystatechange事件在firefox下的使用
2014/04/16 Javascript
jQuery表格列宽可拖拽改变且兼容firfox
2014/09/03 Javascript
js实现横向百叶窗效果网页切换动画效果的方法
2015/03/02 Javascript
jQuery滚动条插件nanoscroller使用指南
2015/04/21 Javascript
jquery实现触发时更新下拉列表内容的方法
2015/12/02 Javascript
HTML Table 空白单元格补全的简单实现
2016/10/13 Javascript
微信小程序 icon组件详细及实例代码
2016/10/25 Javascript
基于JS快速实现导航下拉菜单动画效果附源码下载
2016/10/27 Javascript
JS监控关闭浏览器操作的实例详解
2017/09/12 Javascript
详解js获取video任意时间的画面截图
2019/04/17 Javascript
vue中格式化时间过滤器代码实例
2019/04/17 Javascript
详解微信UnionID作用
2019/05/15 Javascript
Ant Design的可编辑Tree的实现操作
2020/10/31 Javascript
浅谈在django中使用filter()(即对QuerySet操作)时踩的坑
2020/03/31 Python
Keras—embedding嵌入层的用法详解
2020/06/10 Python
Python configparser模块封装及构造配置文件
2020/08/07 Python
Python 列表反转显示的四种方法
2020/11/16 Python
孤独星球出版物:Lonely Planet Publications
2018/03/17 全球购物
Linux内核的同步机制是什么?主要有哪几种内核锁
2016/07/11 面试题
学生个人的自我评价分享
2013/11/05 职场文书
爱国口号
2014/06/19 职场文书
普通话演讲稿
2014/09/03 职场文书
节约每一滴水演讲稿
2014/09/09 职场文书
2014年最新个人对照检查材料范文
2014/09/25 职场文书
2014年政风行风评议工作总结
2014/10/21 职场文书
2014年法院个人工作总结
2014/12/17 职场文书
银行求职自荐信范文
2015/03/04 职场文书
2015年党员发展工作总结
2015/05/13 职场文书
六年级作文之预言作文
2019/10/25 职场文书
浅谈CSS不规则边框的生成方案
2021/05/25 HTML / CSS