首页 > 编程技术 > php

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

发布时间:2016-12-31 09:44

这篇文章讲述了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--]

您可能感兴趣的文章: