博客列表 >php之文件操作

php之文件操作

Serendipity-Ling
Serendipity-Ling原创
2018年01月11日 00:54:49776浏览
<?php
/**
 *文件操作
 */
header('content:text/html;charset=utf-8');
//文件变量名
$fileName = 'demo.txt';
//先检测文件是否存在,如果存在则进行下一步,没有则输出提示
if (file_exists($fileName))
{
    $file_c = @date('Y/m/d H:i:s',filectime($fileName));
    $file_m = @date('Y/m/d H:i:s',filemtime($fileName));
    $file_a = @date('Y/m/d H:i:s',fileatime($fileName));
    echo <<< FILE
文件创建时间:$file_c<br>
文件修改时间:$file_m<br>
文件访问时间:$file_a<br>
FILE;
}
else
{
    echo '文件不存在';
}
<?php
/**
 * 目录操作
 * 绝对路径:从根目录开始,相对路径:从当前文件所在目录开始
 * 目录分隔符:unix采用:正斜线/,Windows采用反斜线:\
 * 每个目录下面有二个特殊目录: .表示当前目录,..表示上一级目录
 * 常用函数:
 * 1.basename($url)返回文件名部分
 * 2.dirname($url)返回去掉文件名的完整目录
 * 3.pathinfo($url)以关联数组方式返回目录的各个部分
 */
header('content-type:text/html,charset=utf-8');
$path = 'http://localhost/ling/file/filename.php';
$fileName = basename($path);
$fileRoad = dirname($path);
$pathArray = pathinfo($path);
echo <<< PATH
文件名:$fileName<br>
文件路径:$fileRoad<br>
PATH;
echo '<pre>';
print_r($pathArray);

//递归遍历一个指定目录
$dir = 'E:\myphp_www\PHPTutorial\WWW\ling';
//scandir()扫描指定目录下的所有文件与目录,返回一个索引数组
//echo '<pre>';
//print_r(scandir($dir.'/ling'));
//function list_dir ($dir)
//{
//    foreach (scandir($dir) as $temp) {
//        if ($temp == '.' || $temp == '..') {
//            continue;
//        }
//        if (is_dir($dir. '/' . $temp)) {
//            list_dir($dir . '/' . $temp);
//        } else
//        {
//            echo $dir.'/'.$temp.'<br/>';
//        }
//    };
//};
//list_dir($dir);
//可以用glob()过滤掉'.'和'..'
function list_dir($dir){
    foreach (glob($dir) as $temp)
    {
        if (is_dir($temp))
        {
            list_dir($temp.'/*');
        }else
        {
            echo $dir.'/'.$temp.'<br/>';
        }
    }
}
list_dir($dir);
<?php
/**
 *文件打开,读取与关闭
 * fopen(),fread(),fclose()
 */
header('content:text/html;charset=utf-8');
$fileName = 'demo.txt';
//fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
//打开文件,以r+的模式打开,读写模式,从文件头开始读写
$handle = fopen($fileName,'r+') or die('文件打开失败');
$fileSize = filesize($fileName);
//读取文件
$content = fread($handle,$fileSize);
//关闭文件
fclose($handle);

//输出文件内容
echo $content.'<br>';
//可直接读取文件内容输出到屏幕上
readfile($fileName);
//输出文件长度
echo '<br>'.$fileSize;
//省略打开和关闭的操作,直接将一个文件内容读取到变量中
$str = file_get_contents($fileName);
echo '<br>'.$str;
<?php
/**
 * 文件绝对路径
 */

header('content-type;text/html;charset=utf-8');
//$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
//$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
//echo 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
function redirect($page='index.php'){
    $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
    $url = rtrim($url,'/\\');
    $url .= '/'.$page;
    header('location:'.$url);
    exit();
}
redirect('filename.php');


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议