I have redhat 8 and install LAMP; all things are working, but when I want to upload images through PHP script below:
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$target_dir = "/images"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"]))
{
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" &&
$imageFileType != "png" &&
$imageFileType != "jpeg" &&
$imageFileType != "gif"
) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else { // if everything is ok, try to upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I get this error:
File is an image – image/png.
Warning: move_uploaded_file(/imageslogo_white.png): failed to open stream: Permission denied in /var/www/html/apinew/upload.php on line 42Warning: move_uploaded_file(): Unable to move ‘/tmp/phpPVJeWk’ to ‘/imageslogo_white.png’ in /var/www/html/apinew/upload.php on line 42
Sorry, there was an error uploading your file.
This is the URL for test:
http://3.122.192.102/apinew/index.php
Folder permission:
drwxrwxrwx. 3 apache apache 55 Oct 24 08:52 apinew
drwxrwxrwx. 2 apache apache 6 Oct 24 11:05 images
-rwxrwxrwx. 1 apache apache 288 Oct 24 10:27 index.php
-rwxrwxrwx. 1 apache apache 1713 Oct 24 13:13 upload.php
2
Answers
I solved this error below the permission in se linux
chown -R apache:apache /var/www/html/directory_to_write chcon -R -t httpd_sys_content_t /var/www/html/directory_to_write chcon -R -t httpd_sys_rw_content_t /var/www/html/directory_to_write
You have a mistake in how you’re generating
$target_file
.Look closely at the error, and you’ll see it’s trying to create a file called
/imageslogo_white.png
. This likely needs to be/images/logo_white.png
, and you may have better results without the starting/
character as well – it’s not typically for your web host to put all your files at/
.