PHP实现的文件操作类及文件下载功能示例

本文实例讲述了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)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php面向对象程序设计入门教程》、《PHP网络编程技巧总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

(0)

相关推荐

  • PHP实现的下载远程文件类定义与用法示例

    本文实例讲述了PHP实现的下载远程文件类定义与用法.分享给大家供大家参考,具体如下: <?php /** * 下载远程文件类支持断点续传 */ class HttpDownload { private $m_url = ""; private $m_urlpath = ""; private $m_scheme = "http"; private $m_host = ""; private $m_port = "

  • php下载远程文件类(支持断点续传)

    简易使用方法:  复制代码 代码如下: $object = new httpdownload(); $object->set_byfile($file)%N#H#%;//服务器文件名,包括路径 $object->filename = $filename;//下载另存为的文件名 $object->download(); 3.源文件: 复制代码 代码如下: <? class httpdownload { var $data = null; var $data_len = 0; var

  • 从性能方面考虑PHP下载远程文件的3种方法

    今天在做导出Excel的时候,总是要测试导出的Excel文件,频繁的下载和打开,很麻烦就想着写段代码一气呵成  服务端导出Excel==>下载Excel文件到本地==>并打开的操作. 这里摘出PHP下载远端文件的方案,以备忘.其中第3种方法考虑到文件过大时的性能问题. 3种方案: -rw-rw-r-- 1 liuyuan liuyuan 470 Feb 20 18:12 test1_fopen.php -rw-rw-r-- 1 liuyuan liuyuan 541 Feb 20 18:06

  • php带密码功能并下载远程文件保存本地指定目录 修改加强版

    原作者BlueStyle 提示 改进地方有 以前的算法是等文件下载完才计算, 现在这个直接在在获取文件时候就计算大小 加了容错语句 增加了判断目录,没有目录自动创建 把计算文件大小的算法换了个 以前的那个光计算文件大小就7行代码, 现在这个只要两行 转载请保留原作者版权信息,由于作者是政府人员,为不惹麻烦,请保留此段文字完整性 html代码: 复制代码 代码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN&qu

  • PHP文件下载类

    复制代码 代码如下: <?    //====================================================    //   使用范例:    // $download=new download('php,exe,html',false);    //  if(!$download->downloadfile($filename))    //  {    //    echo $download->geterrormsg();    //  }    

  • php下载远程大文件(获取远程文件大小)的实例

    废话不多说,直接上代码 <?php // 暂不支持断点续传 // $url = 'http://www.mytest.com/debian.iso'; 不知道为何获取本地文件大小为0 $url = 'http://192.168.8.93/download/vm-672/18/0.vmdk'; $file = basename($url); $header = get_headers($url, 1); $size = $header['Content-Length']; $fp = fopen

  • PHP下载远程文件到本地存储的方法

    本文实例讲述了PHP下载远程文件到本地存储的方法.分享给大家供大家参考.具体实现方法如下: <?php function GrabImage($url,$filename="") { if($url=="") return false; if($filename=="") { $ext=strrchr($url,"."); if($ext!=".gif" && $ext!="

  • php实现的支持断点续传的文件下载类

    本文实例讲述了php实现的支持断点续传的文件下载类及其用法,是非常实用的技巧.分享给大家供大家参考.具体方法如下: 通常来说,php支持断点续传,主要依靠HTTP协议中 header HTTP_RANGE实现. HTTP断点续传原理: Http头 Range.Content-Range() HTTP头中一般断点下载时才用到Range和Content-Range实体头, Range用户请求头中,指定第一个字节的位置和最后一个字节的位置,如(Range:200-300) Content-Range用

  • 解决PHP超大文件下载,断点续传下载的方法详解

    最近导出的时候出现一个php内存溢出的问题,原因就是在于下载的时候读取生成的临时文件过大,PHP内存无法容纳,一开如是想到更改PHP内存限制,但是这个只是一个缓兵之计,于是想到了另外一个方法是把文件分次读取,并下载. 以下是源代码: 复制代码 代码如下: <?php $sourceFile = "1.tmp"; //要下载的临时文件名 $outFile = "用户订单.xls"; //下载保存到客户端的文件名 $file_extension = strtolo

  • 浅谈php fopen下载远程文件的函数

    如下所示: //下载附件 function get_file($url, $folder = "./") { set_time_limit (24 * 60 * 60); // 设置超时时间 $destination_folder = $folder . '/'; // 文件下载保存目录,默认为当前文件目录 if (!is_dir($destination_folder)) { // 判断目录是否存在 mkdirs($destination_folder); // 如果没有就建立目录

随机推荐