I want the code to automatically rename the file. So, if the file name is image.png, and another user uploads a file called image.png, the code will automatically rename the file to image1.png, and so on.
My current code doesnt upload the picture. The page goes blank and says: "File is an image - image/png.".
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;
}
// Checks if file already exists, and if it does, it should rename it.
while (!file_exists($target_file.".".$imageFileType)) {
$target_file = $target_file.$i++;
$uploadOk = 1;
}
// Checks file size
if ($_FILES["fileToUpload"]["size"] > 500000000) {
echo "Sorry, your file is too large. ";
$uploadOk = 0;
// Only allow specific file types
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed, your uploaded a $imageFileType file. ";
$uploadOk = 0;
}
// Checks if $uploadOk is set to 0 by mistake.
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. ";
// All is ok
} else {
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 was expecting the code would use $target_file and add $i++. I was expecting that it would keep incrementing the number until there is no file with the same name as it on the server.