What potential issues can arise when renaming uploaded files in PHP, and how can they be avoided?
Issue: One potential issue when renaming uploaded files in PHP is that if the new filename already exists in the target directory, it can overwrite the existing file. To avoid this, you can check if the file already exists and generate a unique filename to prevent overwriting.
// Check if the file already exists in the target directory
if (file_exists($targetDirectory . $newFilename)) {
$extension = pathinfo($newFilename, PATHINFO_EXTENSION);
$newFilename = uniqid() . '.' . $extension; // Generate a unique filename
}
// Move the uploaded file to the target directory with the new filename
move_uploaded_file($_FILES['file']['tmp_name'], $targetDirectory . $newFilename);