php is_writable函数介绍

is_writable — 判断给定的文件名是否可写,该函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

语法:

bool is_writable  ( string $filename  )

如果文件存在并且可写则返回 TRUE 。filename 参数可以是一个允许进行是否可写检查的目录名。 

记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。 

参数:

  1. filename 要检查的文件名称。 

返回值:

如果文件 filename 存在并且可写则返回 TRUE 。 

 

php is_writable实例

使用is_writable函数判断给定的文件是否可读:

<?php
$filename = \"test.text\";
if (is_readable($filename)) {
    echo \"文件 $filename 可读\";
} else {
    echo \"文件 $filename 不可读\";
}
?>

其实我们也可以自己写一个函数来判断文件是否可读,而不需要使用php内置函数is_writable,以下函数可用于替换php内置的is_writable函数,大家可以参考一下:

//可用于替换php内置的is_writable函数
function isWritable($filename){
    if(preg_match(\'/\\/$/\',$filename)){
        $tmp_file=sprintf(\'%s%s.tmp\',$filename,uniqid(mt_rand()));
        return isWritable($tmp_file);
    }
    if(file_exists($filename)){
        //文件已经存在的话,使用读写方式打开
        /* http://www.manongjc.com/article/1369.html */
        $fp=@fopen($filename,\'r+\');
        if($fp){
            fclose($fp);
            return true;
        }
        else{
            return false;
        }
    }
    else{
        $fp=@fopen($filename,\'w\');
        if($fp){
            fclose($fp);
            un ($filename);
            return true;
        }
        else{
            return false;
        }
    }
}
收藏 打印