I want to store images using PHP, so I am using the following code:
$encodedCard = isset($_POST["card"])? $_POST["card"] : null;
$name = isset($_POST["fn"]) ? $_POST["fn"] : null;
$card = base64_decode($encodedCard,true);
$completePath = '/home/user/cards/' . $name . '.png';
if (file_put_contents($completePath, $card)!== false) {
echo "success";
} else {
$lastError = error_get_last();
echo "Error writing to file: " . $lastError['message'];
}
I have checked that the code is working properly until the if
statement.
I am getting the following error:
Error writing to file: file_put_contents(/home/user/cards/image_name.png): Failed to open stream: Permission denied
Upon opening my Aapche2 error.log, I have the following:
PHP Warning: file_put_contents(/home/user/cards/image_name.png): Failed to open stream: Permission denied in /path/to/the/php/file.php on line 5
I tried changing the permissions for the directory, but nothing worked. The changes I tried are:
## did not work
chmod -R 755 /home/user/cards/
## did not work
chown -R www-data:www-data /home/user/cards/
## did not work
chmod -R 777 /home/user/cards/
If it helps, I am using Apache2 on an Ubuntu 22.04.03 LTS machine for the server.
Any help is appreciated; thanks in advance.
Edit: After Dorg's answer, I am adding some information related to my Apache 2 configuration files.
I have my PHP files saved as /var/www/domain_name/api/add/image.php
.
My virtual host is as follows:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName domain_name
ServerAlias domain_name
DocumentRoot /var/www/domain_name
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Although I don't have <Directory>
in my virtual host, I have it in my apache.conf
file as:
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
<Directory /home/user/cards/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>