What are common pitfalls when renaming files during image uploads in PHP?

Common pitfalls when renaming files during image uploads in PHP include not checking for file extensions, not handling file name collisions, and not sanitizing file names to prevent security vulnerabilities. To solve these issues, always validate file extensions, generate unique file names to avoid collisions, and sanitize file names to remove any potentially harmful characters.

// Get the file extension
$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

// Generate a unique file name
$filename = uniqid() . "." . $extension;

// Sanitize the file name
$filename = preg_replace("/[^a-zA-Z0-9.]/", "", $filename);

// Move the uploaded file to the desired directory with the new name
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $filename);