I'm using this (php) upload code I found online for the image upload form.
I realize there are already a lot of questions/answers on the site about "renaming files" when uploading, and I've done quite a bit of research on them.
So far...none of them seem to specifically address what I want to do.
Hopefully this can be achieved by adjusting the code I'm using.
Ultimately...I would like to be able to upload a single file (not multiple) and have the files automatically named with a simple number, eg; 1, 2, 3, 4 or 5 etc...
No prefix and no extension. Just the numerical value of the name.
However, I would like the code to first check the target directory to scan which files "name" already exist.
So if the existing files in the directory are 1, 2, 3, 4 and 5..., the new files will automatically be named 6 in sequence, and so on.
However, if the existing files in the directory are 1, 2, 4 and 5 (3 does not exist), the new file will be uploaded as 3 to preserve the order.
Or, for my particular needs, I don't even mind if all images in the directory are renamed with a new upload. Essentially changing the order so that the sequence of numbers is preserved.
This is the upload code I'm currently using:
<?php $target_dir = "userImages/userID/"; $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."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>
You can try this function, it will check if the files in the directory are named consecutively, and then rename them so that they are always numbered, the function returns the next number of the newly uploaded file
How to achieve?