I am attempting to create a cronjob under the user apache, but I get permission denied errors for files that are accessed by the program. The specific file that my php script cannot access is /var/www/html/amazon/amazon_data.txt. Here is me checking the permissions, and testing to see if I can write to the file:
bash-3.2$ whoami
apache
bash-3.2$ ls -l /var/www/html/amazon/amazon_data.txt
-rwxrwxr-- 1 apache apache 1082 Apr 3 15:43 /var/www/html/amazon/amazon_data.txt
bash-3.2$ vi /var/www/html/amazon/amazon_data.txt
Now I try to run a script that tries to access the file I get this warning:
bash-3.2$ /usr/bin/php /var/www/html/amazon/amazon_inventory_sync.php
PHP Warning: Module 'json' already loaded in Unknown on line 0
PHP Warning: fopen(amazon_data.txt): failed to open stream: Permission denied in /var/www/html/amazon/amazon_inventory_sync.php on line 26
Warning: fopen(amazon_data.txt): failed to open stream: Permission denied in /var/www/html/amazon/amazon_inventory_sync.php on line 26
Unable to open amazon_data.txt!bash-3.2$
Why can I access and edit the file with the user just fine, but not in the php script when executing it via command line? There is no issue when I run the script from a browser.
Edit: I can run it fine under the user soh, who is in the group apache. apache is also in the group apache.
The issue was due to the file being requested not being a literal location. This is the code which did not work:
$filename = "amazon_data.txt";
$file = fopen($filename, "a+") or die("Unable to open $filename!
");
This may work fine when the script is run remotely via HTTP, but it may cause issues when running cron jobs or execution in the terminal. Changing the $filename
to be the full location fixed this issue.
$filename = dirname(__FILE__)."/"."amazon_data.txt";
$file = fopen($filename, "a+") or die("Unable to open $filename!
");
Why does this happen? I am guessing instead of the php file's folder being used, it was using a directory which the apache user did not have access to, such as the current working directory that the command in terminal was being executed from.