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 相关文章推荐
E路文章系统PHP
Dec 11 PHP
精通php的十大要点(上)
Feb 04 PHP
php array_map array_multisort 高效处理多维数组排序
Jun 11 PHP
关于php fread()使用技巧
Jan 22 PHP
PHP和Mysqlweb应用开发核心技术 第1部分 Php基础-3 代码组织和重用2
Jul 03 PHP
PHP中的静态变量及static静态变量使用详解
Nov 05 PHP
php封装的mysqli类完整实例
Oct 18 PHP
利用php + Laravel如何实现部署自动化详解
Oct 11 PHP
PHP 多任务秒级定时器的实现方法
May 13 PHP
PHP如何通过表单直接提交大文件详解
Jan 08 PHP
PHP微信网页授权的配置文件操作分析
May 29 PHP
详解PHP中的8个魔术常量
Jul 06 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
ECshop 迁移到 PHP7版本时遇到的兼容性问题
2016/02/15 PHP
Laravel+jQuery实现AJAX分页效果
2016/09/14 PHP
php JWT在web端中的使用方法教程
2018/09/06 PHP
jQuery调用WebService的实现代码
2011/06/19 Javascript
JQuery设置获取下拉菜单某个选项的值(比较全)
2014/08/05 Javascript
js实现TAB切换对应不同颜色的代码
2015/08/31 Javascript
js判断当前页面在移动设备还是在PC端中打开
2016/01/06 Javascript
JS 对象(Object)和字符串(String)互转方法
2016/05/20 Javascript
js利用clipboardData实现截屏粘贴功能
2016/10/12 Javascript
浅谈js对象的创建和对6种继承模式的理解和遐想
2016/10/16 Javascript
connection reset by peer问题总结及解决方案
2016/10/21 Javascript
react-native使用react-navigation进行页面跳转导航的示例
2017/09/07 Javascript
Angular实现的进度条功能示例
2018/02/18 Javascript
JS秒杀倒计时功能完整实例【使用jQuery3.1.1】
2019/09/03 jQuery
微信小程序一周时间表功能实现
2019/10/17 Javascript
vue实现图片上传功能
2020/05/28 Javascript
JQuery使用数组遍历跳出each循环
2020/09/01 jQuery
python文件写入实例分析
2015/04/08 Python
Python基本语法经典教程
2016/03/11 Python
在python3环境下的Django中使用MySQL数据库的实例
2017/08/29 Python
基于python中staticmethod和classmethod的区别(详解)
2017/10/24 Python
Python基于property实现类的特性操作示例
2018/06/15 Python
python匹配两个短语之间的字符实例
2018/12/25 Python
浅谈Pycharm中的Python Console与Terminal
2019/01/17 Python
Tretorn美国官网:瑞典外套和鞋类品牌,抵御风雨
2018/07/19 全球购物
MYPROTEIN澳大利亚官方网站:欧洲运动营养品牌
2019/06/26 全球购物
幼教个人求职信范文
2013/12/02 职场文书
社区学习十八大感想
2014/01/22 职场文书
上海世博会口号
2014/06/19 职场文书
小学生植树节活动总结
2014/07/04 职场文书
最美护士演讲稿
2014/08/27 职场文书
邀请函的格式
2015/01/30 职场文书
2015年中职班主任工作总结
2015/05/25 职场文书
建国大业观后感600字
2015/06/01 职场文书
后天观后感
2015/06/08 职场文书
JAVA 线程池(池化技术)的实现原理
2022/04/28 Java/Android