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 相关文章推荐
动态网站web开发 PHP、ASP还是ASP.NET
Oct 09 PHP
全文搜索和替换
Oct 09 PHP
php mysql数据库操作类
Jun 04 PHP
php 静态化实现代码
Mar 20 PHP
PHP中如何调用webservice的实例参考
Apr 25 PHP
浅析PHP绘图技术
Jul 03 PHP
PHP按行读取、处理较大CSV文件的代码实例
Apr 09 PHP
PHP 魔术变量和魔术函数详解
Feb 25 PHP
php安装swoole扩展的方法
Mar 19 PHP
PHP判断数组是否为空的常用方法(五种方法)
Feb 08 PHP
php获取ip及网址的简单方法(必看)
Apr 01 PHP
PHP实现双链表删除与插入节点的方法示例
Nov 11 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操作xml入门之cdata区段
2015/01/23 PHP
php简单中奖算法(实例)
2017/08/15 PHP
php实现微信公众号企业转账功能
2018/10/01 PHP
JQuery 初体验(建议学习jquery)
2009/04/25 Javascript
jquery 模拟类搜索框自动完成搜索提示功能(改进)
2010/05/24 Javascript
初窥JQuery(二) 事件机制(1)
2010/11/25 Javascript
Javascript执行效率全面总结
2013/11/04 Javascript
同域jQuery(跨)iframe操作DOM(实例讲解)
2013/12/19 Javascript
使用简洁的jQuery方法实现隔行换色功能
2014/01/02 Javascript
Jquery实现侧边栏跟随滚动条固定(兼容IE6)
2014/04/02 Javascript
JavaScript实现单击下拉框选择直接跳转页面的方法
2015/07/02 Javascript
AngularJS全局scope与Isolate scope通信用法示例
2016/11/22 Javascript
Bootstrap基本组件学习笔记之下拉菜单(7)
2016/12/07 Javascript
jQuery实现贪吃蛇小游戏(附源码下载)
2017/03/04 Javascript
浅谈Vue组件及组件的注册方法
2018/08/24 Javascript
详解easyui 切换主题皮肤
2019/04/04 Javascript
vue 父组件通过v-model接收子组件的值的代码
2019/10/27 Javascript
js瀑布流布局的实现
2020/06/28 Javascript
使用IPython下的Net-SNMP来管理类UNIX系统的教程
2015/04/15 Python
浅谈scrapy 的基本命令介绍
2017/06/13 Python
Python内存管理方式和垃圾回收算法解析
2017/11/11 Python
Python使用装饰器进行django开发实例代码
2018/02/06 Python
Python之lambda匿名函数及map和filter的用法
2019/03/05 Python
详解将Python程序(.py)转换为Windows可执行文件(.exe)
2019/07/19 Python
使用Python获取当前工作目录和执行命令的位置
2020/03/09 Python
Pytorch使用PIL和Numpy将单张图片转为Pytorch张量方式
2020/05/25 Python
html5 视频播放解决方案
2016/11/06 HTML / CSS
PHP面试题集
2016/12/18 面试题
职业技术学校毕业生推荐信
2013/12/03 职场文书
小学教师师德演讲稿
2014/05/06 职场文书
出纳试用期自我鉴定范文
2014/09/16 职场文书
学习党的群众路线教育实践活动剖析材料
2014/10/13 职场文书
百家讲坛观后感
2015/06/12 职场文书
教师节座谈会主持词
2015/07/03 职场文书
游戏开发中如何使用CocosCreator进行音效处理
2021/04/14 Javascript
docker 制作mysql镜像并自动安装
2022/05/20 Servers