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 相关文章推荐
动态生成gif格式的图像要注意?
Oct 09 PHP
PHP去除数组中重复的元素并按键名排序函数
Aug 18 PHP
Discuz 6.0+ 批量注册用户名
Sep 13 PHP
destoon安装出现Internal Server Error的解决方法
Jun 21 PHP
win7 64位系统 配置php最新版开发环境(php+Apache+mysql)
Aug 15 PHP
PHP连接SQLServer2005的方法
Jan 27 PHP
支持png透明图片的php生成缩略图类分享
Feb 08 PHP
Zend Framework教程之路由功能Zend_Controller_Router详解
Mar 07 PHP
orm获取关联表里的属性值
Apr 17 PHP
ajax调用返回php接口返回json数据的方法(必看篇)
May 05 PHP
Yii框架日志记录Logging操作示例
Jul 12 PHP
解决php extension 加载顺序问题
Aug 16 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调用Java对象的方法
2006/10/09 PHP
用IE远程创建Mysql数据库的简易程序
2006/10/09 PHP
PHP实现HTML生成PDF文件的方法
2014/11/07 PHP
php微信公众平台开发之获取用户基本信息
2015/08/17 PHP
php如何获取文件的扩展名
2015/10/28 PHP
微信公众号OAuth2.0网页授权问题浅析
2017/01/21 PHP
PHP函数积累总结
2019/03/19 PHP
PHP代码覆盖率统计详解
2020/07/22 PHP
JavaScript入门教程(8) Location地址对象
2009/01/31 Javascript
关于JAVASCRIPT urldecode URL解码的问题
2012/01/08 Javascript
动态显示可输入的字数提示还可以输入的字数
2014/04/01 Javascript
js 获取元素下面所有li的两种方法
2014/04/14 Javascript
jquery制作属于自己的select自定义样式
2015/11/23 Javascript
js匿名函数使用&amp;传参(实例)
2017/09/08 Javascript
nodejs实现简单的gulp打包
2017/12/21 NodeJs
vue实现搜索功能
2019/05/28 Javascript
JS实现页面侧边栏效果探究
2021/01/08 Javascript
[01:31:03]DOTA2完美盛典全回顾 见证十五项大奖花落谁家
2017/11/28 DOTA
python中的内置函数getattr()介绍及示例
2014/07/20 Python
Python实现的Excel文件读写类
2015/07/30 Python
python opencv实现任意角度的透视变换实例代码
2018/01/12 Python
妙用itchat! python实现久坐提醒功能
2019/11/25 Python
window环境pip切换国内源(pip安装异常缓慢的问题)
2019/12/31 Python
Opencv python 图片生成视频的方法示例
2020/11/18 Python
python3代码输出嵌套式对象实例详解
2020/12/03 Python
python3 使用ssh隧道连接mysql的操作
2020/12/05 Python
HTML5中5个简单实用的API
2014/04/28 HTML / CSS
基于html5 canvas做批改作业的小插件
2020/05/20 HTML / CSS
西班牙手机之家:Phone House
2018/10/18 全球购物
会话Bean的种类
2013/11/07 面试题
鸿星尔克广告词
2014/03/21 职场文书
个人四风对照检查材料
2014/09/26 职场文书
抄袭同学作业检讨书1000字
2014/11/20 职场文书
应届生求职自荐信范文
2015/03/04 职场文书
详解MindSpore自定义模型损失函数
2021/06/30 Python
logback如何自定义日志存储
2021/08/30 Java/Android