2

我在 ubuntu 上使用 php。当我在网页上使用任何拒绝访问的图像时,页面上会出现警告。我想在显示之前检查它,如果它没有打开权限,那么就给它打开权限。正如我们在终端命令中所做的那样。

chmod 777 myimage.jpg

如何检查这一点并授予对 php.ini 文件的完全访问权限。

谢谢

4

5 回答 5

8

检查函数is_readable()is_writable()

例子:

$filename = '/home/myuser/example.txt';

if (is_readable($filename) && is_writable($filename))
{
    echo "File has read and write permissions.";
}
于 2010-01-05T11:09:58.343 回答
2

您可以做的一件事是使用fileowner函数 (and posix_getpwuid) 并与您的 PHP 用户(通常www-data)进行比较。

如果用户相同,您可以根据需要更改权限。但首先检查文件是否仍可写。

更新:chmodandchown函数在成功时返回 TRUE,在失败时返回 FALSE,因此最好将它们放在 if 子句中。error_reporting(0);您可以通过在脚本开头设置或使用如下@符号来抑制错误输出:

if ( @chmod($filename, 0666) ) {
    // do whatever with file
}
else if ( @chown($filename, 1000) ) {
    chmod($filename, 0666);
    // do whatever with file
}
else {
    // can't change permissions
}
于 2010-01-05T14:46:25.250 回答
2

使用is_readable()检查文件是否可以被 PHP 进程读取。

使用chmod()更改文件的权限。

此外,您可以使用is_writable()来测试是否可以写入文件,并使用file_exists()来检查文件是否存在。

于 2010-01-05T11:14:40.757 回答
1

每次引用文件时从 PHP 即时执行此操作是管理文件的一种非常低效的方法。它还要求所有文件访问都通过 PHP 脚本进行调解。此外,从安全的角度来看,允许内容是世界可写的也是相当混乱的。

我会运行一次管理脚本来整理现有文件的权限,然后在新文件进入系统时解决问题。

当然,如果您没有作为 webserver uid 以外的其他人的 shell 访问/shell 访问,那么您将不得不使用 PHP(因此 readdir/is_readable/is_writeable)来实现它。

在不知道文件如何出现在您的网络服务器上的情况下,很难推荐特定的解决方案。

C。

于 2010-01-05T14:10:14.423 回答
0

One thing you can do to make the file readable / writable is to call this function upon file / folder creation without the second argument:

function AutoChmod($path, $chmod = null)
{
    if (file_exists($path) === true)
    {
        if (is_null($chmod) === true)
        {
            $chmod = (is_file($path) === true) ? 644 : 755;

            if (in_array(get_current_user(), array('apache', 'httpd', 'nobody', 'system', 'webdaemon', 'www', 'www-data')) === true)
            {
                $chmod += 22;
            }
        }

        return chmod($path, octdec(intval($chmod)));
    }

    return false;
}

Example:

AutoChmod('/path/to/file/you/just/created.txt');

This function will give appropriate permission whether you are working with SuPHP / SuExecPHP or not.


To check permissions you just need to use the functions is_readable() and is_writable().

于 2010-01-05T16:38:06.283 回答