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作的文本留言本的例子(五)
Oct 09 PHP
php htmlspecialchars加强版
Feb 16 PHP
PHP版国家代码、缩写查询函数代码
Aug 14 PHP
PHP函数addslashes和mysql_real_escape_string的区别
Apr 22 PHP
PHP实现把MySQL数据库导出为.sql文件实例(仿PHPMyadmin导出功能)
May 10 PHP
检测codeigniter脚本消耗内存情况的方法
Mar 21 PHP
php计算一个文件大小的方法
Mar 30 PHP
php生成固定长度纯数字编码的方法
Jul 09 PHP
ThinkPHP 整合Bootstrap Ajax分页样式
Dec 23 PHP
PHP无限极分类函数的实现方法详解
Apr 15 PHP
php swoole多进程/多线程用法示例【基于php7nts版】
Aug 12 PHP
Laravel5.1 框架控制器基础用法实例分析
Jan 04 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
利用Ffmpeg获得flv视频缩略图和视频时间的代码
2011/09/15 PHP
php从数组中随机抽取一些元素的代码
2012/11/05 PHP
深入解析PHP的引用计数机制
2013/06/14 PHP
PHP小技巧之JS和CSS优化工具Minify的使用方法
2014/05/19 PHP
PHP读取PPT文件的方法
2015/12/10 PHP
Javascript技术技巧大全(五)
2007/01/22 Javascript
javascript 获取表单file全路径
2009/12/31 Javascript
jquery获取子节点和父节点的示例代码
2013/09/10 Javascript
JS操作CSS随机改变网页背景实现思路
2014/03/10 Javascript
Nodejs中读取中文文件编码问题、发送邮件和定时任务实例
2015/01/01 NodeJs
JavaScript模拟可展开、拖动与关闭的聊天窗口实例
2015/05/12 Javascript
深入讲解AngularJS中的自定义指令的使用
2015/06/18 Javascript
AngularJs Managing Service Dependencies详解
2016/09/02 Javascript
AngularJS 单元测试(一)详解
2016/09/21 Javascript
简单好用的nodejs 爬虫框架分享
2017/03/26 NodeJs
Nodejs搭建wss服务器教程
2017/05/24 NodeJs
Vue渲染函数详解
2017/09/15 Javascript
Vue递归实现树形菜单方法实例
2018/11/06 Javascript
Python写的一个简单DNS服务器实例
2014/06/04 Python
Python中列表(list)操作方法汇总
2014/08/18 Python
Python中运行并行任务技巧
2015/02/26 Python
python实现解数独程序代码
2017/04/12 Python
Scrapy抓取京东商品、豆瓣电影及代码分享
2017/11/23 Python
Python读csv文件去掉一列后再写入新的文件实例
2017/12/28 Python
Ubuntu下Anaconda和Pycharm配置方法详解
2019/06/14 Python
python中使用you-get库批量在线下载bilibili视频的教程
2020/03/10 Python
Python列表切片常用操作实例解析
2020/03/10 Python
python网络编程socket实现服务端、客户端操作详解
2020/03/24 Python
Html5自定义字体解决方法
2019/10/09 HTML / CSS
Hertz荷兰:荷兰和全球租车
2018/01/07 全球购物
下面关于"联合"的题目的输出是什么
2013/08/06 面试题
最美孝心少年事迹材料
2014/08/15 职场文书
党委领导班子整改方案
2014/09/30 职场文书
会计求职信怎么写
2015/03/20 职场文书
千手观音观后感
2015/06/03 职场文书
大学生军训心得体会5篇
2019/08/15 职场文书