What is the purpose of automatically renaming uploaded images in PHP?

When uploading images in PHP, it is important to automatically rename them to prevent naming conflicts and ensure the security of the uploaded files. This can be achieved by generating a unique filename based on a combination of factors such as the current timestamp and the original filename. By doing so, we can avoid overwriting existing files and mitigate the risk of malicious file uploads.

// Generate a unique filename for the uploaded image
$originalFilename = $_FILES['image']['name'];
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
$newFilename = uniqid() . '_' . time() . '.' . $extension;

// Move the uploaded file to a designated directory with the new filename
move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $newFilename);