Cron 作业和文件夹权限 - 权限被拒绝

2022-01-03 00:00:00 cron permissions php

我在 webroot 上方有一个文件夹,用于临时存储由 php web 应用程序生成的用户文件.例如,这些文件可能是要附加到电子邮件中的 PDF.

I have a folder above the webroot that is used to temporarily store user files generated by a php web application. The files may, for example, be PDF's that are going to be attached to emails.

文件夹权限设置为 rwxr-xr-x (0755).从 Web 应用程序执行过程时,文件会毫无问题地写入此文件夹.

The folder permissions are set to rwxr-xr-x (0755). When executing a procedure from the web application, the files get written to this folder without any issues.

我现在还设置了一个 cron 作业,它调用 php 脚本来执行与上面完全相同的过程.但是,由于权限失败,PDF 无法保存到上述文件夹中 - cron 作业报告返回 permission denied 错误.

I have now also set up a cron job that calls the php script to execute that exact same procedure as above. However, the PDF cannot be saved into the above folder due to failed permissions - the cron job reports back a permission denied error.

我已尝试将文件夹权限设置为 0775,但仍然被拒绝权限.但是,当权限为 0777 时,cron 作业就可以正常工作了.

I have tried setting the folder permissions to 0775 and still get a permission denied. However, when the permissions are 0777, then the cron job then works fine.

这对我来说似乎很奇怪 - 为什么 cron 在 0755 获得权限被拒绝,但它通过网络应用程序正常工作?

This seems very strange to me - why does the cron get a permission denied at 0755 but it works fine through the web app?

推荐答案

可能的答案是 cron 作业在您的用户下执行 - 并且该目录归 apache(或 www-data 或 nobody 或您的 Web 服务器的任何用户所有)运行为).

The probable answer is that the cron job executes under your user - and the directory is owned by apache (or www-data or nobody or whatever user your web server runs as).

要使其正常工作,您可以将 cron 作业设置为以 Web 服务器用户身份运行.像这样:

To get it to work, you could set up the cron job to run as the web server user. Something like this:

su -l www-data -c 'crontab -e'

或者,您可以将权限更改为 775(所有者和组的读写执行,其他人的读取执行)并将文件夹的组所有权设置为运行 cron 作业的用户.

Alternatively, you could change the permissions to 775 (read-write-execute for the owner and group, and read-execute for others) and set the group ownership of the folder to the user running the cron job.

但是,您必须确保如果您要删除某些内容或进入由 apache 创建的文件夹,您仍然可能会遇到问题(apache 会创建一个它自己拥有的文件,您的用户无法删除它然后,无论目录权限如何.

However, you have to make sure that if you're deleting something or descending into folder which is created by apache, you could still run into problems (apache would create a file which it itself owns, and your user cannot delete it then, regardless of the directory permissions.

您还可以查看诸如 suphp 之类的东西或任何最新的东西 - Web 服务器进程在您的用户名下运行,具体取决于您的系统架构.

You could also look at some stuff like suphp or whatever is up to date - where the web server processes are ran under your username, depending on your system architecture.

相关文章