How can PHP be used to generate unique file names for uploaded images to prevent naming conflicts and improve organization?

When uploading images, naming conflicts can occur if multiple users upload files with the same name. To prevent this, we can generate unique file names for each uploaded image using PHP. One way to achieve this is by combining a timestamp with a random string to create a unique identifier for each file. This approach helps improve organization and ensures that each uploaded image has a distinct file name.

// Generate a unique file name for uploaded images
$timestamp = time();
$random_string = bin2hex(random_bytes(5));
$unique_filename = $timestamp . '_' . $random_string;

// Use the unique file name when saving the uploaded image
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $unique_filename . ".jpg");