PHP学习笔记(三)--文件操作

下面通过一些简单示例带你了解PHP的文件操作。

1、打开及关闭文件

resource fopen  ( string $filename  , string $mode  [, bool $use_include_path  = false  [, resource $context  ]] )

mode

说明

'r'

只读方式打开,将文件指针指向文件头。

'r+'

读写方式打开,将文件指针指向文件头。

'w'

写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。

'w+'

扫描二维码关注公众号,回复: 4232405 查看本文章

读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。

'a'

追加方式打开。写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。

'a+'

追加方式打开。读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。

'x'

创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE ,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。

'x+'

创建并以读写方式打开,其他的行为和 'x' 一样。

b

二进制模式,用于与其它模式进行连接,默认方式是二进制模式。

t

文本文件模式,用于与其它模式进行连接。

 

关闭打开的文件:bool fclose  ( resource $handle  )

 

<?php

    $fileName='D:\tmp.txt';

    $handle=fopen($fileName, "rb");

    while(!feof($handle)){

       echo fgets($handle);

    }

    fclose($handle);

?>

 

2、读写文件

  1. 读取整个文件内容

reaffile()、file()和file_get_contents()用于读取整个文件内容。使用这三个函数读取文件内容不需要打开关闭文件。

  • int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

readfile()读取整个文件的内容并写入到缓存中,出错则返回fase。

 

  • array file ( string $filename [, int $flags = 0 [, resource $context ]] )

file()函数读取整个文件的内容按行存储到数组中,包括换行符在内。

可选参数 flags 可以是以下一个或多个常量:

FILE_USE_INCLUDE_PATH

在 include_path 中查找文件。

FILE_IGNORE_NEW_LINES

在数组每个元素的末尾不要添加换行符

FILE_SKIP_EMPTY_LINES

跳过空行

 

  • string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

 

file_get_contents()将文件内容读入到一个字符串,如果有offset及maxlen参数,则从参数offset指定的位置开始读取长度为maxlen的一个字符串,如果读取失败则返回false。

 

【例1】使用readfile()函数

<?php

    $fileName='D:\tmp.txt';

    readfile($fileName);//显示所有内容

    $a=readfile($fileName);//返回总字数并且显示所有内容

    echo $a;

?>

 

【例2】使用file()函数

<?php

    $fileName='D:\tmp.txt';

    if (file_exists($fileName))//判断文件是否存在

    {

       $arr=file($fileName);

       foreach ($arr as $value){//每次输出一个文本文件的段落

           echo $value.'<p>';

       }

    }

   

?>

 

 

【例3】使用file_get_contents()函数

<?php

    $fileName='D:\tmp.txt';

    $strContent=file_get_contents($fileName);

    echo $strContent;

    $strContent=file_get_contents($fileName,null,null,11,20);//从第11个字符开始读取,读取长度为20(一个汉字占两个字符)

    echo $strContent;

?>

 

<?php
// <= PHP 5
$file  =  file_get_contents ( './people.txt' ,  true );
// > PHP 5
$file  =  file_get_contents ( './people.txt' ,  FILE_USE_INCLUDE_PATH );
?>

<?php

    $homePage='http://www.baidu.com/';

    $content=file_get_contents($homePage);

    echo $content;

?>

 

  1. 读取一行数据
  • string fgets ( resource $handle [, int $length ] )

一次读取一行数据,参数length为读取长度,遇到换行符、EOF或读取了length-1个字符后停止。

  • string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )

用于读取一行数据,会过滤掉读取内容中的html和php标记,参数allowable_tags可以设置哪些标记不被去掉。

 

【例1】使用fgets()函数

<?php

    $fileName='D:\tmp.txt';

    if(file_exists($fileName)){

       $handle=fopen($fileName, 'rb');

       while(!feof($handle)){

           echo fgets($handle).'<p>';

       }

       fclose($handle);

    }

?>

 

【例2】使用fegtss()函数

<?php

    $fileName='D:\tmp.txt';

    if(file_exists($fileName)){

       $handle=fopen($fileName, 'rb');

       while(!feof($handle)){

           echo fgetss($handle).'<p>';

       }

       fclose($handle);

    }

?>

 

  1. 读取一个字符

string fgetc ( resource $handle )

从文件中读取一个字符

<?php

    $fileName='D:\tmp.txt';

    if(file_exists($fileName)){

       $handle=fopen($fileName, 'rb');

       while(false!=($chr=fgetc($handle))){

           echo $chr;

       }

       fclose($handle);

    }

?>

注意:使用此方法对于中文来说读取的是乱码

 

  1. 读取指定长度的字符

string fread ( resource $handle , int $length )

参数length为要读取的字节数。

<?php

    $fileName='D:\tmp.txt';

    if(file_exists($fileName)){

       $handle=fopen($fileName, 'rb');

       echo fread($handle, 32).'<p>';//读取32个字节

       echo fread($handle, filesize($fileName));//读取剩余内容

       fclose($handle);

    }

?>

 

3、数据写入文件

  • int fwrite ( resource $handle , string $string [, int $length ] )

fputs()与fwrite用法完全相同。

<?php

    $fileName='D:\tmp.txt';

    $content='要添加到文件的内容';

       if(is_writable($fileName)){//判断文件是否可写

              $handle=fopen($fileName, "a");

              if(!$handle)

              {

                  echo '打开文件失败';

                  exit;

              }

              if ( fwrite ( $handle ,  $content ) ===  FALSE ) {

                  echo  "不能写入到文件  $fileName " ;

              }

              echo '写入成功';

              fclose($handle);

       }

       else{

           echo '不能写入文件';

       }

?>

 

  • int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

flags 的值可以是 以下 flag 使用 OR (|) 运算符进行的组合。

Available flags

Flag

描述

FILE_USE_INCLUDE_PATH

在 include 目录里搜索 filename。 更多信息可参见 include_path。

FILE_APPEND

如果文件 filename 已经存在,追加数据而不是覆盖。

LOCK_EX

在写入时获得一个独占锁。

 

<?php

    $fileName='D:\tmp.txt';

    $content='要添加到文件的内容';

    file_put_contents($fileName, $content,FILE_APPEND|LOCK_EX);//向文件追加内容并且写入时加锁

?>

 

  • bool copy ( string $source , string $dest [, resource $context ] )

拷贝文件,如果目标文件存在,则会被覆盖

  • bool rename ( string $oldname , string $newname [, resource $context ] )

 

文件重命名,可以跨驱动器进行操作。

  • bool unlink ( string $filename [, resource $context ] )

删除文件

  • int fileatime ( string $filename )

获取文件上次访问时间,返回时间戳

  • int filemtime ( string $filename )

返回最后一次修改时间,返回时间戳

  • int filesize ( string $filename )

获取文件大小,单位为字节数

  • mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

返回一个数组包含文件name的路径信息。它们包括: PATHINFO_DIRNAME , PATHINFO_BASENAME  和 PATHINFO_EXTENSION  或 PATHINFO_FILENAME 。 如果没有指定 options 默认是返回全部的单元。

  • string realpath ( string $path )

返回文件的绝对路径

  • array stat ( string $filename )

返回一个数组,包括文件大小、最后修改时间等信息。

 

<?php

    $fileName='D:\tmp.txt';

    copy($fileName, 'D:\123.txt');

    rename($fileName, 'D:\12.txt');

    unlink('D:\123.txt');

    $lastTime=fileatime($fileName);//返回时间戳

    echo '上次访问时间:'.date('Y-m-d H:i:s',$lastTime).'<p>';

    echo '上次修改时间:'.date('Y-m-d H:i:s',filemtime($fileName)).'<p>';

    $size=filesize($fileName);

    echo '文件大小'.$size.'<p>';

    $arr=pathinfo($fileName);

    print_r($arr);

    echo '<p>';

    echo '文件路径:'.$arr['dirname'].'<p>';

    echo '文件全名:'.$arr['basename'].'<p>';//包括扩展名

    echo '文件扩展名:'.$arr['extension'].'<p>';

    echo '文件名:'.$arr['filename'].'<p>';//不包括扩展名

   

    echo realpath("index.php");

   

    $arrInfo=stat($fileName);

    foreach ($arrInfo as $key=>$value){

       echo $key.':'.$value.'<p>';

    }

?>

 

4、目录处理

  • resource opendir ( string $path [, resource $context ] )

打开一个目录

  • void closedir ( resource $dir_handle )

关闭打开的目录

  • array scandir ( string $directory [, int $sorting_order [, resource $context ]] )

返回一个数组,包括所有文件和目录。

  • bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

新建一个指定的目录

  • bool rmdir ( string $dirname [, resource $context ] )

删除指定的目录,目录必须是空的

  • string getcwd ( void )

返回当前目录

  • bool chdir ( string $directory )

将当前目录改为directory

  • float disk_free_space ( string $directory )

返回目录中的可用空间

  • float disk_total_space ( string $directory )

返回目录的总空间大小

  • string readdir ([ resource $dir_handle ] )

返回目录中的下一个文件的文件名,必须使用opendir()打开目录

  • void rewinddir ( resource $dir_handle )

将指定的目录重新指定到目录的开头

 

【例1】

<?php

    $pathInfo=pathinfo(realpath("index.php"),PATHINFO_DIRNAME);

    if (is_dir($pathInfo)){

       if($dire=opendir($pathInfo)){

           echo $dire;

       }

       closedir($dire);

    }

   

    $dir=scandir("E:\\临时文件");

    foreach ($dir as $value){

       echo $value.'<p>';

    }     

   

    mkdir('D:\tmp');

    rmdir('D:\tmp');

    echo getcwd().'<p>';

    echo '当前目录总空间:'.disk_total_space(getcwd()).'<p>';

    echo '空闲目录大小:'.disk_free_space(getcwd());

?>

 

【例2】两种方法遍历目录文件

<?php

    $handle=opendir(getcwd());

    while(true==($value=readdir($handle))){

       echo $value.'<p>';

    }

    $arr=scandir(getcwd());

    foreach ($arr as $value){

       echo $value.'<p>';

    }

?>

 

5、文件高级处理

  • bool rewind ( resource $handle )

将文件的指针设为文件流的开头。如果以追加方式打开,则无论文件指针在何处,总是会追加到文件末尾。

  • int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )

offset为指针位置或相对whence参数的偏移量,可以是负值。

whence参数可以取值如下:

1. SEEK_SET  - 设定位置等于 offset 字节。

2. SEEK_CUR  - 设定位置为当前位置加上 offset。

3. SEEK_END  - 设定位置为文件尾加上 offset。

如果忽略whence参数,则缺省为SEEK_SET.

  • bool feof ( resource $handle )

测试是否到了文件的结束的位置

  • int ftell ( resource $handle )

返回文件当前指针的位置

  • bool flock ( resource $handle , int $operation [, int &$wouldblock ] )

在向一个文件写入内容时,需要先锁定该文件,以防止其它用户同时修改此文件内容。

operation 可以是以下值之一:

1. LOCK_SH 取得共享锁定(读取的程序)。 

2. LOCK_EX  取得独占锁定(写入的程序。 

3. LOCK_UN  释放锁定(无论共享或独占)。 

如果不希望 flock()  在锁定时堵塞,则是 LOCK_NB (Windows 上还不支持)。

 

6、上传文件

使用文件上传需要配置php.ini中的一些属性:

  1. file_upload:设置为on才支持上传文件;
  2. upload_tmp_dir:上传文件临时目录;
  3. upload_max_filesize:服务器上传的文件的最大值,以MB为单位,默认为20MB;
  4. max_execution_time:PHP中一个指令执行的最长时间;
  5. memory_limit:PHP中一个指令所分配的内存空间,单位为MB。

如果需要上传超大文件需要修改最后三个属性。

 

$_FILES变量存储的上传文件的相关信息。

元素名

说明

$_FILES[filename][name]

存储了上传文件的文件名,如exam.txt、myDream.jpg等

$_FILES[filename][size]

存储了上传文件的大小,单位为字节

$_FILES[filename][type_name]

文件上传时,首先在临时目录中保存一个临时文件。该变量为临时文件。

$_FILES[filename][type]

上传文件的类型

$_FILES[filename][error]

存储了上传文件的结果。如果为0则说明上传成功

 

 

bool move_uploaded_file ( string $filename , string $destination )

上传文件到指定位置。在创建表单时,必须设置form表单的enctype=”multipart/form-data”.

<?php
$uploads_dir  =  '/uploads' ;
foreach ( $_FILES [ "pictures" ][ "error" ] as  $key  =>  $error ) {
    if ( $error  ==  UPLOAD_ERR_OK ) {
         $tmp_name  =  $_FILES [ "pictures" ][ "tmp_name" ][ $key ];
         $name  =  $_FILES [ "pictures" ][ "name" ][ $key ];
         move_uploaded_file ( $tmp_name ,  " $uploads_dir / $name " );
    }
}
?>

猜你喜欢

转载自blog.csdn.net/huzhizhewudi/article/details/84440298