php基础三(文件系统)

<!-- PHP文件系统 -->
    <?php
    readfile("/home/paul/text.txt");
    $filename = 'NoAlike.txt';
    $filestring = file_get_contents($filename);
    $filearray = explode("\n", $filestring);
    while (list($key, $val) = each($filearray)) {
        ++$key;
        $val = trim($val);
        print 'Line' .$key.':'.$val.'<br />';
    }
    $filename = 'NoAlike.txt';
    $filestring = file_get_contents($filename);
    echo $filestring;
    //     fopen\fread\fclose操作读取文件
    $fp = fopen('NoAlike.txt', "r");//r、r+、w、w+
    $contents = fread($fp, 1024);
    fclose($fp);
    var_dump($fp);
    
    $date = "在PHP中文网学好PHP,妹子票子不在话下!";
    $numbyte = file_put_contents('binggege.txt', $data);
    if ($numbyte) {
        echo '写入成功,我们读取看看结果试试:';
        echo file_get_contents('binggege.txt');
    }else{
        echo '写入失败或者没有权限,注意检查';
    }
    
    //     fwrite配合fopen进行写入操作
    $filename = 'test.txt';
    $fp = fopen($filename, "r+");//x、a
    $len = fwrite($fp, '我是一只来自南方的狼,一直在');
    
    //创建临时文件
    $handle = tmpfile();
    $numbytes = fwrite($handle, '写入临时文件');
    fclose($handle);
    echo '向临时文件中写入了'.$numbytes.'个字节';
    
    //移动、拷贝和删除文件
    rename($oldname, $newname);
    $filename = 'test.txt';
    $filename2 = $filename.'old';
    rename($oldname, $oldname2);
    copy($oldname, $oldname2);
    if (unlink($filename)) {
        echo  "删除文件成功$filename!\n";
    }else {
        echo "sc $filename失败!\n";
    }
    
    //检测文件属性函数
    file_exists($filename);//文件是否存在
    is_readable($filename);//文件是否可读
    is_writable($filename);//文件是否可写
    is_executable($filename);//文件是否可执行
    is_file($filename);//是否是文件
    is_dir($filename);//是否是目录
    clearstatcache();//清楚文件的状态缓存
    if (file_exists('install.lock')) {
        echo '已安装,请不要再次安装';
        exit;
    }
    
    //文件常用函数和常量
    $_current_file = str_replace(
        array('/','\\'), DIRECTORY_SEPARATOR, __FILE___);
    define('_CUR_FILE_', $_current_file);
    echo _CUR_FILE_;
    rewind($handle);//指针回到开始处
    fseek($handle, $offset);//文件指针向后移动指定字符
    $fp = fopen('demo2.txt', 'r+');
    echo fread($fp, 10);
    rewind($fp);
    echo '<br>';
    echo fread($fp, 10);
    echo '<br>';
    echo fseek($fp, 10);
    echo '<br>';
    echo fread($fp, 10);
    echo '<br>';
    fclose($fp);
    $filename = 'demo.txt';
    echo $filename . '文件大小为:'.
        filesize($filename).'bytes';
    filectime($filename);//文件创建时间
    filemtime($filename);//文件修改时间
    fileatime($filename);//文件上次访问时间
    $filename = 'demo.txt';
    if (file_exists($filename)) {
        echo '$filename文件的上次访问时间是:'.date("Y-m-d H:i:s"
            ,filectime($filename));
        echo '$filename文件的上创建时间是:'.date("Y-m-d H:i:s"
            ,filectime($filename));
        echo '$filename文件的上次修改时间是:'.date("Y-m-d H:i:s"
            ,filemtime($filename));
    }
    
    //文件锁处理机制
    $fp = fopen("demo.txt", "r+");
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, "文件这个时候被我占用了哟\n");
        flock($fp, LOCK_UN);
    }else {
        echo "锁失败,可能有人在操作,这个时候不能将文件上锁";
    }
    fclose($fp);
    
    //目录处理函数
    $dir = "d:/";
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            echo readdir($dh).'<br />';
            echo readdir($dh).'<br />';
            echo readdir($dh).'<br />';
            echo readdir($dh).'<br />';
            closedir($dh);
        };
    }
    $dir = "d:/";
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false){
                echo "文件名为:$file :
                文件的类型是:".filetype($dir.$file).'<br />';
            }
            closedir($dh);
        }
    }
    
    //文件权限设置
    chmod("/var/wwwroot/index.html", 755);
    chmod("/var/wwwroot/index.html", "u+rwx,go+rx");
    chmod("/somedir/somefile", 0755);
    
    //文件路径函数
    pathinfo($path);//返回文件的各个组成部分
    basename($path);//返回文件名
    dirname($path);//文件目录部分
    parse_url($url);//网址拆解成各部分
    http_build_query($query_data);//生成url中的query字符串
    http_build_url();//生成一个url
    $date = [
        'username'=>'php',
        'area'=>'hubei'
    ];
    echo http_build_query($date);
    $path_parts = pathinfo('d:/www/index.inc.php');
    echo '文件目录名:'.$path_parts['dirname']."<br />";
    echo '文件全名:'.$path_parts['basename']."<br />";
    echo '文件扩展名:'.$path_parts['extension']."<br />";
    echo '不包含扩展的文件名:'.$path_parts['filename']."<br />";
    echo "1: ".basename("d:/www/index.d",".d").PHP_EOL;
    echo "2: ".basename("d:/www/index.php").PHP_EOL;
    echo "3: ".basename("d:/www/passwd").PHP_EOL;
    $url = 'http://username:password@hostname:9090/path?arg=value#anchor';
    var_dump(parse_url($url));
    
    //文件留言本
    //     date_default_timezone_set('PRC');
    @$string = file_get_contents('message.txt');
    if (!empty($string)) {
        $string = rtrim($string, '&^');
        $arr = explode('&^', $string);
        foreach ($arr as $value){
            list($username, $content, $time) = explode('$#', $value);
            echo '用户名为<font color="gree">'.$username.'</font>';
            echo '<hr />';
        }
    }
    
    $fp=fopen('message.txt', 'a');
    $time=time();
    $username=trim(@$_POST['username']);
    $content=trim(@$_POST['content']);
    if ($username & $content) {
        $string=$username.'$#'.$content.'$#'.$time.'&^';
        fwrite($fp, $string);
        fclose($fp);
    }
    
    ?>
    
    <h1>基于文本的留言本演示</h1>
    <form action="write.php" method="post">
        用户名:<input type="text" name="username" /><br />
        留言内容:<textarea name="content"></textarea><br />
      <input type="submit" value="提交" />
    </form>
    
    
    
    
    <!-- 实现修改配置文件的实例 -->
    <?php
        include 'config.php';
    ?>
    <form action="edit.php" method="post">
        <input type="text" name="DB_HOST" value="<?php echo DB_HOST;?>" /><br />
        <input type="text" name="DB_USER" value="<?php echo DB_USER;?>" /><br />
        <input type="text" name="DB_PWD" value="<?php echo DB_PWD;?>" /><br />
        <input type="text" name="DB_NAME" value="<?php echo DB_NAME;?>" /><br />
        <input type="submit" value="修改" />
    </form>
    
    <!-- edit.php -->
    <?php
        $string=file_get_contents('config.php');
        foreach ($_POST as $key=>$val){
            $yx="/define\('$key','.*?'\);/";
            $re="define('$key','$val');";
            $string=preg_replace($yx, $re, $string);
        }
        
        file_put_contents('config.php', $string);
        echo '修改成功';
    ?>
    <!-- config.php -->
    <?php
        define('DB_HOST', 'localhost1');
        define('DB_USER', 'root1');
        define('DB_PWD', 'root1');
        define('DB_NAME', 'neirong1');
    ?>
一.问答题
1.返回路径中的文件名部分的函数是什么?
2.改变文件模式的函数是什么?
3.拷贝文件的函数是什么?
4.返回路径中的目录部分的函数是什么?
5.将上传的文件移动到指定位置的函数是? 
6.返回规范化的绝对路径名的函数是什么?

二.编程题

1.请用三种方法写出函数,获取某个目录下所有文件和文件夹名的关联数组,
要求给函数传一个路径参数,返回一个数组,
格式为:array('dir'=>array('dir1','dir2'...),'file'=>array())

2.封装一个系统文件类,类中方法包括:判断文件是否存在,获取文件内容(包括锁和不锁文件),
输入内容到一个文件,追加内容到文件,删除文件,移动文件,拷贝文件,
文件的文件名部分,文件的目录部分,文件的后缀名部分,文件的mine类型,文件的大小,
获取文件上一次修改时间,判断是否为路径,判断文件是否可写,判断是否为文件,
创建文件夹,复制一个目录,删除一个目录。

一.问答题
1.string basename ( string $path [, string $suffix ] )
2.bool chmod ( string $filename , int $mode )
3.bool copy ( string $source , string $dest [, resource $context ] )
4.string dirname ( string $path )
5.bool move_uploaded_file ( string $filename , string $destination )
6.string realpath ( string $path ) 
//第一题
function scanDir1($dir = './'){
    $result['dir'] = $result['file'] = array();
    if(!is_dir($dir)) return $result;
    foreach (scandir($dir) as $df) {
        if($df==='.'||$df==='..') continue;
        if(is_dir($dir.'/'.$df)) $result['dir'][] = $df;
        if(is_file($dir.'/'.$df)) $result['file'][] = $df;
    }
    return $result;
}

function scanDir2($dir = './'){
    $result['dir'] = $result['file'] = array();
    if(!is_dir($dir)) return $result;
    $handle = dir($dir);
    while (($df = $handle -> read()) !== false) {
        if($df==='.'||$df==='..') continue;
        if(is_dir($dir.'/'.$df)) $result['dir'][] = $df;
        if(is_file($dir.'/'.$df)) $result['file'][] = $df;
    }
    $handle -> close();
    return $result;
}

function scanDir3($dir = './'){
    $result['dir'] = $result['file'] = array();
    if(!is_dir($dir)) return $result;
    $handle = opendir($dir);
    while (($df = readdir($handle)) !== false) {
        if($df==='.'||$df==='..') continue;
        if(is_dir($dir.'/'.$df)) $result['dir'][] = $df;
        if(is_file($dir.'/'.$df)) $result['file'][] = $df;
    }
    return $result;
}   

//第二题
class FileSystem{
    public function exists($path)
    {
        return file_exists($path);
    }
    public function isFile($path)
    {
        return is_file($path);
    }
    public function isDir($path)
    {
        return is_dir($path);
    }
    public function get($path,$lock = false)
    {
        if(!$this->exists($path)) return '';
        if($lock){
            return $this -> lockGet($path);
        }else{
            return file_get_contents($path);
        }
    }
    private function lockGet($path)
    {
        $contents = '';
        $handle = fopen($path, 'r');
        if($handle){
            try {
                if(flock($handle, LOCK_SH)){
                    while (!feof($handle)) {
                        $contents .= fread($handle, 1048576);
                    }
                }
            } finally {
                fclose($handle);
            }
        }
        return $contents;
    }
    public function put($path,$contents,$lock = false)
    {
        return file_put_contents($path,$contents,$lock?LOCK_SH:0);
    }
    public function append($path,$contents)
    {
        return file_put_contents($path,$contents,FILE_APPEND);
    }
    public function delete($path)
    {
        if($this->isFile($path)){
            return unlink($path);
        }else if($this->isDir($path)){
            foreach (scandir($path) as $df) {
                if($df!=='.'||$df!=='..'){
                    $this->delete($path.'/'.$df);
                }
            }
            rmdir($path);
        }
    }
    public function move($path,$target)
    {
        return rename($path,$target);
    }
    public function copy($path,$target)
    {
        return copy($path,$target);
    }
    public function name($path)
    {
        return pathinfo($path,PATHINFO_FILENAME);
    }
    public function dirname($path)
    {
        return pathinfo($path,PATHINFO_DIRNAME);
    }
    public function extension($path)
    {
        return pathinfo($path,PATHINFO_EXTENSION);
    }
    public function type($path)
    {
        return filetype($path);
    }
    public function size($path)
    {
        return filesize($path);
    }
    public function lastModified($path)
    {
        return filemtime($path);
    }
    public function isWritable($path)
    {
        return is_writable($path);
    }
    public function makeDir($path,$mode = 0755)
    {
        return @mkdir($path,$mode);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值