0

I am trying to upload image as shown here w3schools But it always shows the error

Sorry, there was an error uploading your file.

PHP

<?php
if(!isset($_POST["submit"])){
    die('Error');
}
$target_dir = "/var/www/img/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
    } else {
    echo "File is not an image.";
    $uploadOk = 0;
    }
}
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=   "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been     uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
} 

?>

It had Worked in Windows 10. Now the error seems upload is done but moving file or something else of the error..

OS : Ubuntu 18.04

PHP ver : 7.3

Apache2

In php.ini, file_uploads = On is setted.

SJang
  • 15
  • 4

2 Answers2

0

The documentation page for the function you are using move_uploaded_file() describes the behavior in case of the failure.

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

The first thing you could do is to enable error and warning reporting so you could see whether a warning is raised.

That way you will know whether an issue is with the filename or with actual file movement - which would indicate permissions issue.

matiit
  • 7,969
  • 5
  • 41
  • 65
0

It may be due to permission to directory you created in /var/www/ folder.

You can check your apache user by using following command

ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}'

You will get the apache user.After that give permission to apache user to access the directory.In my case apache user is daemon so i give permission to this user to access the img directory.

chown -R daemon:daemon img
ShaanSetia
  • 336
  • 2
  • 5
  • 17