I am trying to upload image to server. The following code works when I use on local pc but when I try on server, image is not uploaded.
$img = $_FILES['file_uploaded']['name']; $image_temp = $_FILES['file_uploaded']['tmp_name']; if(move_uploaded_file($image_temp, "uploads/" . $img)){ $fullpath = dirname(__FILE__) . '\images\' . $img; } else echo 'Failed!';
Advertisement
Answer
Do you have the same file permissions on server? Does folder /var/www/html/uploaded
exist and is writable by web server user (usually www-data)?
Try running following command in server terminal:
sudo su mkdir /var/www/html/uploads chmod -R 775 /var/www/html/uploads chown -R www-data:www-data /var/www/html/uploads
Where www-data is used, change it with your own web server user.
“FIXED” SCRIPT:
$img = $_FILES['file_uploaded']['name']; $upload_dir = "/var/www/html/uploads/"; $image_temp = $_FILES['file_uploaded']['tmp_name']; if (file_exists($image_temp)) { echo "Temp file doesn't exist."; return false; } $move_file = move_uploaded_file($image_temp, $upload_dir . $img); if ($move_file) { $fullpath = $upload_dir . $img; } else { echo 'Failed!'; return false; }
You should write additional checks, so you know where your application fails.
Regarding security, you should never trust user. In this case we used filename ($_FILES['file_uploaded']['name']
)provided by user, using which he could write and maybe even read outside of designated directory