This exact code will work fine when uploading files on my local XAMPP server but uploading it to my web server this stops working. Other functions of the same project still work fine though.
//Image Uploading
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png', 'jpg', 'jpeg');
if(in_array($file_ext, $allowed)) {
$file_name_new = $username.'.png';
$file_dest = '../images/'.$file_name_new;
if($file_error > 0){
echo "There was an error uploading this image! Try another.";
} else {
if(move_uploaded_file($file_tmp, $file_dest)) {
header("Location: ../user/editprofile.php?user=".$username);
}
}
}
}
HTML bit
<h2>Profile Image</h2>
<form action="editprofile.php?user=<?php echo $user; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
Firstly, I'd pathinfo to get the filename and file extension of the uploaded file. Secondly you should validate mimetype rather than extension by comparing what is in $_FILES['userfile']['type']
against a list of mimetypes, for this situation you'll want to check for ['image/png', 'image/jpeg']
to prevent someone uploading something like a PHP script with a jpg extension. You also probably want to preserve the extension of the uploaded file rather than making them all png as this could cause unexpected errors.
With that out of the way the information will be inside $file_error
to let you know exactly why the file isn't uploading. You will get back a file error code that will tell you what has gone wrong.
It will be one of these:
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.UPLOAD_ERR_CANT_WRITE
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.UPLOAD_ERR_EXTENSION
Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.The most common on shared hosting is incorrect permissions on the file you're uploading to (value 7).