php is_writeable函数实例讲解及出错的解决方法

时间:2016-09-27
php is_writeable()函数判断指定的文件是否可写。本文章向大家介绍s_writeable使用方法和实例以及在使用该函数时出现BUG的解决思路和方法,需要的朋友可以参考一下。

php is_writeable定义和用法

is_writeable() 函数判断指定的文件是否可写。

语法

is_writeable(file)

参数 

参数 描述
file 必需。规定要检查的文件。

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

注释:本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

 

php is_writeable例子

<?php
$file = "test.txt";
if(is_writeable($file))
  {
  echo ("$file is writeable");
  }
else
  {
  echo ("$file is not writeable");
  }
?>

输出:

test.txt is writeable

PHP is_writeable函数bug问题

1、在windowns中,当文件只有只读属性时,is_writeable()函数才返回false,当返回true时,该文件不一定是可写的。

如果是目录,在目录中新建文件并通过打开文件来判断;

如果是文件,可以通过打开文件(fopen),来测试文件是否可写。

2、在Unix中,当php配置文件中开启safe_mode时(safe_mode=on),is_writeable()同样不可用。

读取配置文件是否safe_mode是否开启。

/**
     * Tests for file writability
     *
     * is_writable() returns TRUE on Windows servers when you really can't write to
     * the file, based on the read-only attribute.  is_writable() is also unreliable
     * on Unix servers if safe_mode is on.
     *
     * @access    private
     * @return    void
     */
    if ( ! function_exists('is_really_writable'))
    {
        function is_really_writable($file)
        {
            // If we're on a Unix server with safe_mode off we call is_writable
            if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
            {
                return is_writable($file);
            }
     
            // For windows servers and safe_mode "on" installations we'll actually
            // write a file then read it.  Bah...
            if (is_dir($file))
            {
                $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100));
     
                if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
                {
                    return FALSE;
                }
     
                fclose($fp);
                @chmod($file, DIR_WRITE_MODE);
                @unlink($file);
                return TRUE;
            }
            elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
            {
                return FALSE;
            }
     
            fclose($fp);
            return TRUE;
        }
    }

Directory "xxx" is writeable by group错误的解决办法

今天朋友在linux服务器上安装wordpress主题,发现一个奇怪的错误,有个文件总是显示错误。并且出现Directory "路径" is writeable by group这样的错误。查了一下,发现不少朋友遇到这种问题,解决的方法也很简单,就是讲目录或者文件权限调低,设置成755或者更低。

chmod 755 设置用户的权限为:

  • 1.文件所有者可读可写可执行
  • 2.与文件所有者同属一个用户组的其他用户可读可执行
  • 3.其它用户组可读可执行