How can I check if an uploaded file already exists in the destination folder in PHP?
To check if an uploaded file already exists in the destination folder in PHP, you can use the `file_exists()` function along with the `basename()` function to get the filename from the uploaded file path. This way, you can compare the filename with the list of files in the destination folder to see if a file with the same name already exists.
$uploadDir = 'uploads/';
$uploadedFile = $uploadDir . basename($_FILES['file']['name']);
if (file_exists($uploadDir . $_FILES['file']['name'])) {
echo "File already exists in the destination folder.";
} else {
move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile);
echo "File uploaded successfully.";
}
Related Questions
- How can PHP developers ensure that the content they output is correctly formatted for consumption by external applications like RSS readers?
- What are some potential pitfalls when creating and accessing files in PHP, as seen in the provided code snippet?
- How can PHP be used to dynamically generate email addresses for contact forms based on database entries, reducing the need for manual entry?