PHP实现文件操作类及文件下载功能的教程

 更新时间:2016年12月31日 09:44  点击:2149
这篇文章讲述了php中如何实现文件操作类及文件下载功能的教程,非常有用,感兴趣的同学可以参考一下

本文实例讲述了PHP实现的文件操作类及文件下载功能。分享给大家供大家参考,具体如下:

文件操作类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?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
 classcfile {
  //The path to the file we wish to work with.
  protected$thepath;
  //Error messages in the form of constants for ease of use.
  constFOUNDERROR ="Sorry, the file in question does not exist.";
  constPERMERROR ="Sorry, you do not have the proper permissions on this file";
  constOPENERROR ="Sorry, the file in question could not be opened.";
  constCLOSEERROR ="Sorry, the file could not be closed.";
  //The constructor function.
  publicfunction__construct (){
   $num_args= func_num_args();
   if($num_args> 0){
    $args= func_get_args();
    $this->thepath =$args[0];
   }
  }
  //A function to open the file.
  privatefunctionopenfile ($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{
                thrownewexception (self::OPENERROR);
                returnfalse;
              }
            }catch(exception$e) {
              echo$e->getmessage();
            }
          }else{
            thrownewexception (self::PERMERROR);
          }
        }catch(exception$e) {
          echo$e->getmessage();
        }
      }else{
        thrownewexception (self::FOUNDERROR);
      }
    }catch(exception$e) {
      echo$e->getmessage();
    }
  }
  //A function to close a file.
  functionclosefile () {
    try{
      if(!fclose ($this->thepath)){
        thrownewexception (self::CLOSEERROR);
      }
    }catch(exception$e) {
      echo$e->getmessage();
    }
  }
  //A function to read a file, then return the results of the read in a string.
  publicfunctionread () {
    //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.
      returnfgets($filepointer);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to write to a file.
  publicfunctionwrite ($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.
      returnfwrite ($filepointer,$towrite);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to append to a file.
  publicfunctionappend ($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.
      returnfwrite ($filepointer,$toappend);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to set the path to a new file.
  publicfunctionsetpath ($newpath) {
    $this->thepath =$newpath;
  }
 }
?>
1
2
3
4
5
6
7
8
9
<?php
  $myfile=newcfile ("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!");
?>

文件下载:

1
2
3
4
5
6
7
8
9
10
11
12
<?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文件与目录操作。分享给大家供大家参考,具体如下:

文件目录相关函数

<?php
// 输出目录中的文件
functionoutputcurfiles ($allowedtypes,$thedir){
//首先,我们确保目录存在。
if(is_dir($thedir)){
 //现在,我们使用scandir扫描目录中的文件。
 $scanarray= scandir ($thedir);
 //接着我们开始解析数组。
 //scandir()用“.”和“..”统计文件导航列表
 //因此作为文件,我们不应该列出他们。
 for($i= 0;$i<count($scanarray);$i++){
  if($scanarray[$i] !="."&&$scanarray[$i] !=".."){
   //现在,进行检查,以确保这是一个文件,而不是一个目录。
   if(is_file($thedir."/".$scanarray[$i])){
    //现在,因为我们将允许客户端编辑这个文件,
    //我们必须检查它是否是可读和可写。
    if(is_writable($thedir."/".$scanarray[$i]) && is_readable($thedir."/".$scanarray[$i])){
     //现在,我们检查文件类型是否存在于允许的类型数组中.
     $thepath=pathinfo($thedir."/".$scanarray[$i]);
     if(in_array ($thepath['extension'],$allowedtypes)){
      //如果文件符合规定,我们可以继续输出.
      echo$scanarray[$i] ."<br />";
     }
    }
   }
  }
 }
}else{
 echo"对不起,这个目录不存在.";
}
}
$allowedtypes=array("txt","html");
outputcurfiles ($allowedtypes,"testfolder");
///////////////////////////////////////////////////
functionrecurdir ($thedir) {
  //First attempt to open the directory.
  try{
    if($adir= opendir ($thedir)){
      //扫描目录。
      while(false !== ($anitem= readdir ($adir))){
        //不统计目录中包含“.”或“..”的情况
        if($anitem!="."&&$anitem!=".."){
          //此时如果是一个目录,则缩进一点
          //再去递归
          if(is_dir($thedir."/".$anitem)){
            ?><span style="font-weight: bold;"mce_style="font-weight: bold;"><?phpecho$anitem; ?></span><?php
            ?><div style="margin-left: 10px;"mce_style="margin-left:10px;"><?php
            recurdir ($thedir."/".$anitem);
            ?></div><?php
          }elseif(is_file($thedir."/".$anitem)){
            //此时输出文件.
            echo$anitem."<br />";
          }
        }
      }
    }else{
      thrownewexception ("Sorry, directory could not be openend.");
    }
  }catch(exception$e) {
    echo$e->getmessage();
  }
}
echo"<br />/////////////////////////////////////<br /><br />";
recurdir("testfolder");
//////////////////////////////////////////////////////////////////
echo"<br />/////////////////////////////////////<br /><br />";
functionsortfilesbydate ($thedir){
  //首先,需要确保目录存在。
  if(is_dir($thedir)){
    //接着,我们使用scandir扫描此目录中的文件.
    $scanarray= scandir ($thedir);
    $finalarray=array();
    //然后开始解析数组
    //scandir()用“.”和“..”统计文件导航列表
    //因此作为文件,我们不应该列出他们.
    for($i= 0;$i<count($scanarray);$i++){
      if($scanarray[$i] !="."&&$scanarray[$i] !=".."){
        //现在,我们检查,以确保这是一个文件,而不是一个目录.
        if(is_file($thedir."/".$scanarray[$i])){
          //现在需要做的是循环数据到一个关联数组.
          $finalarray[$thedir."/".$scanarray[$i]] =filemtime($thedir."/".$scanarray[$i]);
        }
      }
    }
    //至此,我们已经遍历了整个数组,现在需要做的只是asort()它。
    asort ($finalarray);
    return($finalarray);
  }else{
    echo"对不起,这个目录不存在.";
  }
}
//然后,我们将函数指向我们需要查看的目录.
$sortedarray= sortfilesbydate ("testfolder");
//至此,就可以按照如下形式输出:
while($element= each ($sortedarray)){
  echo"File: ".$element['key'] ." was last modified: ".date("F j, Y h:i:s",$element['value']) ."<br />";
}
?>
这篇文章介绍了php中的数组操作,有添加,删除,计算,反转,排序,查找等等。有需要的同学可以参考一下

本文实例分析了PHP数组操作。分享给大家供大家参考,具体如下:

PHP的数组是很重要的一部分。操作示例如下:

<?php
functionbr() {
  echo'<br />===============================================<br />';
}
$arr1=array();
$arr1[] ='x';
$arr1[] ='a';
$arr1[] ='e';
$arr1[] ='c';
$arr1[] ='h';
// 添加数组
array_push($arr1, 3, 23, 55);
// 数组长度
echo'the size of array is :'.count($arr1).'<br />';
// 反转
var_dump(array_reverse($arr1));
// 排序 - 直接作用于数组
sort($arr1);
var_dump($arr1);
// 排序 - 按字符串排序
sort($arr1, SORT_STRING);
var_dump($arr1);
// 范围
$arr2= range('a','h');
// 连接
$arrTemp1= implode('-',$arr2);
echo$arrTemp1;
echo'<br />';
// 切割
echo'['.implode('][',array_reverse(explode('-',$arrTemp1) )).']';
// 数组合并,会重排索引
$arr3=array_merge($arr1,$arr2);
var_dump($arr3);
// 删除数组元素
array_shift($arr3);
array_pop($arr3);
unset($arr3[4]);
array_splice($arr3, 6, 2);
var_dump($arr3);
// 抽取数组,原数组不变
$arr4=array_slice($arr3, 2,3);
var_dump($arr4);
// 关联数组
$fruits=array('red'=>'apple','yellow'=>'banana','green'=>'lime');
// 数组键
$colors=array_keys($fruits);
// 数组值
$fla=array_values($fruits);
var_dump($colors);
var_dump($fla);
// 查找
echoin_array('green',$colors);
echo'<br />';
echoin_array('black',$colors)?'in':'not in';
echo'<br />';
echoarray_key_exists('yellow',$fruits);
echo'<br />';
// 按键排序
ksort($fruits);
var_dump($fruits);
// 按值排序
asort($fruits);
var_dump($fruits);
// 循环
foreach($fruitsas$key=>$value) {
  echo$key.' => '.$value.'<br />';
}
echo'<br />';
$f=$fruits;
while($elem= each($f)) {
  echo$elem['key'].' -- '.$elem['value'].'<br />';
}
echo'<br />';
$arr5=array(2, 8, 100, 33, -18);
// 查找最大最小值
echomax($arr5);
echo'<br />';
echomin($arr5);
echo'<br />';
echoarray_sum($arr5);
echo'<br />';
functiondouble($x) {
  echo($x* 2).' ';
}
// 数组元素应用函数
array_walk($arr5,'double');
functioncheck($x) {
  return$x> 20;
}
// 筛选
var_dump(array_filter($arr5,'check'));
$arr6= range(1,10);
echo'random number: '.array_rand($arr6);
//统计
//count(); sizeof(); array_count_values();
$arr7=array(4,5,1,2,3,1,2,1);
$ac=array_count_values($arr7);
// 统计每个value出现的次数
var_dump($ac);
$arr8=array('key1'=>'v1','key2'=>'v2','key3'=>'v3');
extract($arr8);
echo"$key1 $key2 $key3";
//填补
$input=array(12,10,9);
var_dump(array_pad($input, 5, 0));
var_dump(array_pad($input, -5, 0));
?>
这篇文章写了php反斜杠处理函数addslashes()和stripslashes()的使用教程,学习过程中遇到问题的同学快来看看吧!

php 反斜杠处理函数

addslashes():对输入字符串中的某些预定义字符前添加反斜杠,这样处理是为了数据库查询语句等的需要。这些预定义字符是:单引号 (') ,双引号 (") ,反斜杠 (\) ,NULL。

stripslashes():删除由 addslashes() 函数添加的反斜杠。该函数用于清理从数据库或 HTML 表单中取回的数据。(若是连续二个反斜杠,则去掉一个,保留一个;若只有一个反斜杠,就直接去掉。)

默认情况下,PHP 指令 magic_quotes_gpc 为 on,对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。例:

if(get_magic_quotes_gpc()){
   code....
}

addslashes() 例子:

<?php
$str="Who's John Adams?";
echo$str." This is not safe in a database query.<br />";
echoaddslashes($str) ." This is safe in a database query.";
?>

输出结果:

Who's John Adams? This is not safe in a database query.
Who\'s John Adams? This is safe in a database query.

 stripslashes() 例子:

<?php
echostripslashes("Who\'s John Adams?");
?>

输出结果:

Who's John Adams?
[!--infotagslink--]

相关文章

  • php svn操作类

    以前我们开发大型项目时都会用到svn来同步,因为开发产品的人过多,所以我们会利用软件来管理,今天发有一居然可以利用php来管理svn哦,好了看看吧。 代码如下 ...2016-11-25
  • PHP 数据库缓存Memcache操作类

    操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
  • php实现文件下载实例分享

    举一个案例:复制代码 代码如下:<?phpclass Downfile { function downserver($file_name){$file_path = "./img/".$file_name;//转码,文件名转为gb2312解决中文乱码$file_name = iconv("utf-8","gb2312",$file_name...2014-06-07
  • nodejs文件操作模块FS(File System)常用函数简明总结

    件系统操作相关的函数挺多的。首先可以分为两大类。一类是异步+回调的。 一类是同步的。在这里只对异步的进行整理,同步的只需要在函数名称后面加上Sync即可1. 首先是一类最常规的读写函数,函数名称和形式,应该是起源于C...2014-06-07
  • 在PHP中使用X-SendFile头让文件下载更快

    一般来说, 我们可以通过直接让URL指向一个位于Document Root下面的文件, 来引导用户下载文件.但是, 这样做, 就没办法做一些统计, 权限检查, 等等的工作. 于是, 很多时候, 我们采用让PHP来做转发, 为用户提供文件下载...2014-06-07
  • C# 对文件与文件夹的操作包括删除、移动与复制

    在.Net中,对文件(File)和文件夹(Folder)的操作可以使用File类和Directory类,也可以使用FileInfo类和DirectoryInfo类,本文将详细介绍,需要的朋友可以参考...2020-06-25
  • php fopen 函数 读写文件操作

    php fopen 函数 读写文件操作 function getFile($url) { if($f=fopen("$url","r")) { while(!feof($f)) { $s.=fgets($f...2016-11-25
  • php 超大文件下载程序[http 缓存协商,Etag标记,断点续传]

    <?php教程 002 $file_path = './download/download_cn.rar'; 003 004 //使用方法 005 downFile($file_path); 006 007 // 服务器文件路径,下载文件名字(默认...2016-11-25
  • perl 文件操作总结

    perl 文件操作总结,需要的朋友可以参考下...2020-06-29
  • C#文件操作的简单实例

    这篇文章主要介绍了C#文件操作的简单实例,需要的朋友可以参考下...2020-06-25
  • Perl学习笔记之文件操作

    这篇文章主要介绍了Perl学习笔记之文件操作,本文分别给出了打开文件、读取文件、写入文件代码实例,需要的朋友可以参考下...2020-06-29
  • C语言 文件操作解析详解及实例代码

    这篇文章主要介绍了C语言 文件操作解析详解及实例代码的相关资料,需要的朋友可以参考下...2020-04-25
  • php入门教程之文件操作基础

    在有些场合中需要以文件的形式来对内容进行存储,通常这时候需要对文件进行一系列的操作,PHP中对于文件的操作跟其他计算机程序设计语言对文件的操作类似,对于文件的操作...2016-11-25
  • C语言基础文件操作方式超全详解建议收藏

    这篇文章主要为大家介绍了关于C语言文件操作方式的详细总结,建议收藏随用随看,有需要的朋友可以借鉴参考下,希望能够有所帮助...2021-10-14
  • php 文件操作函数(文件 创建,删除,修改 复制 属性)(1/3)

    本文章要讲关于php 文件操作函数他们包括对文件 创建,删除,修改 复制 获取文件属性,判断文件是否存在,写文件,改变文件属性,给写内容,复制文件 写文件的时候有时候需要锁定,...2016-11-25
  • PHP数据库操作Helper类完整实例

    这篇文章主要介绍了PHP数据库操作Helper类,详细分析了php操作mysql的连接、增删改查及关闭连接等步骤,并给出了完整的mysql操作类Helper供大家参考,需要的朋友可以参考下...2016-05-13
  • perl文件操作的一些例子分享

    有关perl文件操作的一些例子,供大家学习参考...2020-06-29
  • php 文件下载实例代码

    function xiazai($file_dir,$file_name) //参数说明: //file_dir:文件所在目录 //file_name:文件名 { $file_dir = chop($file_dir);//去掉路径中多余的空格...2016-11-25
  • java 文件下载支持中文名称的实例

    下面小编就为大家分享一篇java 文件下载支持中文名称的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-06-25
  • php文件下载(可限制下载速度)实现代码

    在php中文件下载会利用到header fopen fread三个主要函数,同时还有一些辅助函数如判断文件存在file_exists is_file等函数,下面我们来看一款文件下载可以限制下载速度实...2016-11-25