删除文件时导致权限被拒绝的原因是什么?

时间:2015-01-05 15:48:05

标签: php linux file permissions permission-denied

我正在尝试使用PHP删除/var/www/main/user_resources/documents/NewFolder1/NewFolder1/noname3.php。如下所示,文件的所有者和组是phped,它是组可写的,而Michael属于phped组。我在使用Centos和Apache。

[Michael@devserver NewFolder1]$ pwd
/var/www/main/user_resources/documents/NewFolder1/NewFolder1
[Michael@devserver NewFolder1]$ ls -l
total 4
-rwxrwxr-x. 1 phped phped 15 Jan  5 07:02 noname3.php
[Michael@devserver NewFolder1]$ groups Michael
Michael : Michael www phped
[Michael@devserver NewFolder1]$

我的PHP脚本是:

echo 'Current script owner: ' . get_current_user().'<br>';
echo($dirname.'</br>');
unlink($dirname);

输出如下:

Current script owner: Michael
/var/www/main/user_resources/documents/NewFolder1/NewFolder1/noname3.php

An error occurred in script '/var/www/main/application/classes/library.php' on line 477: unlink(/var/www/main/user_resources/documents/NewFolder1/NewFolder1/noname3.php): Permission denied (error no: 2)

迈克尔为什么不能删除该文件?

2 个答案:

答案 0 :(得分:0)

被禁止删除此文件的Michael不是Apache,而是Apache。 您应该将apache设置为此文件的所有者,并且您的脚本将起作用:

chmod 755 -R NewFolder1/
chown -R apache:apache NewFolder1/

现在问题是用户Michael对此文件夹没有任何ftp权限。 如果您也想要ftp权限,请尝试:

chmod 775 -R /var/www/main/user_resources/documents/NewFolder1/NewFolder1/
chown -R Michael:apache /var/www/main/user_resources/documents/NewFolder1/NewFolder1/

-R代表&#34;递归&#34;意味着NewFolder1的所有文件和子文件夹将继承相同的权限。但是,这并不是真正推荐的 - 特别是如果您在共享托管服务器上。

要检查文件权限,请使用

ls -la /var/www/main/user_resources/documents/NewFolder1/NewFolder1/

解决方案#2:

首先以root身份登录!!! 如果您以其他用户身份登录,请键入:

su -

然后提供root密码。

然后,导航到本地目录(即:/ usr / local / sbin)并创建一个名为&#34; delete-file&#34;的脚本。并在其中加入以下行:

#!/bin/sh

[ $# -ne 1 ] && {
        echo "usage: $0 <filename>"
        exit 1
}

file=`echo $1`

rm -f $file

[ $? -eq 0 ] && echo "File has been deleted from system!" || echo "Failed to delete the file!"

然后将此文件设为可执行文件:

chmod 755 /usr/local/sbin/delete-file

然后编辑/ etc / sudoers以添加apache:

...
# Disable "ssh hostname sudo <cmd>", because it will show the password in clear.
#         You have to run "ssh -t hostname sudo <cmd>".
#
Defaults    requiretty
Defaults:apache     !requiretty ###ADD THIS LINE!

#
# Refuse to run if unable to disable echo on the tty. This setting should also be
# changed in order to be able to use sudo without a tty. See requiretty above.
#
...

在同一文件的末尾:

...
## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d

### ADD THIS NEXT LINE:
apache  ALL=(ALL) NOPASSWD: /usr/local/sbin/delete-file

将您的php脚本修改为:

<?php
...
$filename = "/var/www/main/user_resources/documents/NewFolder1/NewFolder1/file-to-delete.php";
shell_exec('sudo -S /usr/local/sbin/delete-file '.$filename);
...
?>

现在这应该可以删除文件,无论他们的主人是谁!

答案 1 :(得分:0)

根据您显示的信息,您应该能够删除该文件。如果你不能,你可能(肯定)没有记录用于PHP的Linux用户,然后将他重新登录。