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数组函数序列之array_pop() - 删除数组中的最后一个元素
Nov 07 PHP
深入apache host的配置详解
Jun 09 PHP
改写函数实现PHP二维/三维数组转字符串
Sep 13 PHP
PHP以mysqli方式连接类完整代码实例
Jul 15 PHP
10个超级有用值得收藏的PHP代码片段
Jan 22 PHP
php生成RSS订阅的方法
Feb 13 PHP
解决ThinkPHP关闭调试模式时报错的问题汇总
Apr 22 PHP
PHP中JSON的应用技巧
Oct 10 PHP
yii框架redis结合php实现秒杀效果(实例代码)
Oct 26 PHP
PHP观察者模式示例【Laravel框架中有用到】
Jun 15 PHP
PHP程序员学习使用Swoole的理由
Jun 24 PHP
Laravel框架路由和控制器的绑定操作方法
Jun 12 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的一个简单加密解密代码
2014/01/14 PHP
PHP常用编译参数中文说明
2014/09/27 PHP
laravel框架与其他框架的详细对比
2019/10/23 PHP
理解Javascript闭包
2013/11/01 Javascript
使用jquery清空、复位整个输入域
2015/04/02 Javascript
javascript使用avalon绑定实现checkbox全选
2015/05/06 Javascript
JavaScript实现带箭头标识的多级下拉菜单效果
2015/08/27 Javascript
BootStrap和jQuery相结合实现可编辑表格
2016/04/21 Javascript
Vue.js框架路由使用方法实例详解
2017/08/25 Javascript
在 Node.js 中使用 async 函数的方法
2017/11/17 Javascript
vue.js实现只弹一次弹框
2018/01/29 Javascript
微信小程序获取用户openid的实现
2018/12/24 Javascript
vue实现局部刷新的实现示例
2019/04/16 Javascript
20多个小事例带你重温ES10新特性(小结)
2019/09/29 Javascript
Vuex实现数据增加和删除功能
2019/11/11 Javascript
Quasar Input:type=&quot;number&quot; 去掉上下小箭头 实现加减按钮样式功能
2020/04/09 Javascript
解决vue项目打包上服务器显示404错误,本地没出错的问题
2020/11/03 Javascript
vue3.0 自适应不同分辨率电脑的操作
2021/02/06 Vue.js
Python中除法使用的注意事项
2014/08/21 Python
python开发之str.format()用法实例分析
2016/02/22 Python
Python+OpenCV目标跟踪实现基本的运动检测
2018/07/10 Python
Python re 模块findall() 函数返回值展现方式解析
2019/08/09 Python
python itsdangerous模块的具体使用方法
2020/02/17 Python
Python socket服务常用操作代码实例
2020/06/22 Python
利用CSS3伪元素实现逐渐发光的方格边框
2017/05/07 HTML / CSS
士力架广告词
2014/03/20 职场文书
竞选班委演讲稿
2014/04/28 职场文书
护士长2014年终工作总结
2014/11/11 职场文书
2014年教育教学工作总结
2014/11/13 职场文书
2015年清明节演讲稿范文
2015/03/17 职场文书
2015年大学辅导员工作总结
2015/05/12 职场文书
上学路上观后感
2015/06/16 职场文书
《所见》教学反思
2016/02/23 职场文书
教你怎么用Python生成九宫格照片
2021/05/20 Python
Mysql 设置boolean类型的操作
2021/06/04 MySQL
漫画「狩龙人拉格纳」公开TV动画预告图
2022/03/22 日漫