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 相关文章推荐
一个高ai的分页函数和一个url函数
Oct 09 PHP
PHP操作XML作为数据库的类
Dec 19 PHP
七款最流行的PHP本地服务器分享
Feb 19 PHP
php实现利用phpexcel导出数据
Aug 24 PHP
PHP面向对象之旅:深入理解static变量与方法
Jan 06 PHP
php递归删除目录与文件的方法
Jan 30 PHP
php使用指定编码导出mysql数据到csv文件的方法
Mar 31 PHP
php 类自动载入的方法
Jun 03 PHP
thinkphp3.x中display方法及show方法的用法实例
May 19 PHP
什么是PHP7中的孤儿进程与僵尸进程
Apr 14 PHP
PHP-FPM 设置多pool及配置文件重写操作示例
Oct 02 PHP
PHP Swoole异步Redis客户端实现方法示例
Oct 24 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/02 无线电
PHP语法速查表
2007/01/02 PHP
跨浏览器PHP下载文件名中的中文乱码问题解决方法
2015/03/05 PHP
Laravel源码解析之路由的使用和示例详解
2018/09/27 PHP
Tab页界面 用jQuery及Ajax技术实现(php后台)
2011/10/12 Javascript
jQuery 图片切换插件(代码比较少)
2012/05/07 Javascript
JS/jQuery实现默认显示部分文字点击按钮显示全部内容
2013/05/13 Javascript
引入JS文件IE6报语法错误或缺少对象问题的解决方法
2014/01/09 Javascript
JavaScript的作用域和块级作用域概念理解
2014/09/21 Javascript
Js+php实现异步拖拽上传文件
2015/06/23 Javascript
js实现具有高亮显示效果的多级菜单代码
2015/09/01 Javascript
Bootstrap表单布局样式代码
2016/05/31 Javascript
基于jQuery实现中英文切换导航条效果
2016/09/18 Javascript
利用js编写网页进度条效果
2017/10/08 Javascript
原生JS写Ajax的请求函数功能
2017/12/22 Javascript
vue实现的双向数据绑定操作示例
2018/12/04 Javascript
vue router总结 $router和$route及router与 router与route区别
2019/07/05 Javascript
python命令行参数sys.argv使用示例
2014/01/28 Python
浅谈pandas中DataFrame关于显示值省略的解决方法
2018/04/08 Python
python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序
2020/07/20 Python
Python读取Pickle文件信息并计算与当前时间间隔的方法分析
2019/01/30 Python
python实现小球弹跳效果
2019/05/10 Python
python ChainMap的使用和说明详解
2019/06/11 Python
对python 中re.sub,replace(),strip()的区别详解
2019/07/22 Python
用python实现英文字母和相应序数转换的方法
2019/09/18 Python
Python解释器及PyCharm工具安装过程
2020/02/26 Python
python GUI库图形界面开发之PyQt5访问系统剪切板QClipboard类详细使用方法与实例
2020/02/27 Python
django API 中接口的互相调用实例
2020/04/01 Python
HTML5组件Canvas实现图像灰度化(步骤+实例效果)
2013/04/22 HTML / CSS
美国在线眼镜商城:Eyeglasses.com
2017/06/26 全球购物
大学生求职简历的自我评价
2013/10/14 职场文书
大四学生毕业自荐信
2013/11/07 职场文书
2015会计试用期工作总结
2014/12/12 职场文书
教师个人年终总结
2015/02/11 职场文书
spring项目中切面及AOP的使用方法
2021/06/26 Java/Android
《艾尔登法环》1.03.3补丁上线 碎星伤害调整
2022/04/07 其他游戏