What is the best practice for checking if an uploaded file exists in PHP?
When uploading files in PHP, it's important to check if the file already exists in the destination directory to avoid overwriting existing files. One way to do this is by using the `file_exists()` function to check if a file with the same name already exists. If the file exists, you can handle the situation accordingly, such as renaming the file or displaying an error message.
$uploadDir = 'uploads/';
$uploadedFile = $uploadDir . $_FILES['file']['name'];
if (file_exists($uploadedFile)) {
// File already exists, handle accordingly
echo "File already exists.";
} else {
// File doesn't exist, proceed with uploading
move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile);
echo "File uploaded successfully.";
}
Related Questions
- What is the best approach to sum numbers associated with the same color in a multidimensional array in PHP?
- Where should additional validation code be added in a PHP script to check user input before database insertion?
- What are the potential pitfalls of using Microsoft Expression Web as an editor for PHP scripts?