What best practices should be followed when handling file uploads and renaming files in PHP to prevent errors and ensure data integrity?

When handling file uploads and renaming files in PHP, it is important to sanitize user input to prevent security vulnerabilities such as directory traversal attacks. Additionally, it is crucial to generate unique file names to prevent overwriting existing files and ensure data integrity. One common approach is to use a combination of a timestamp and a random string to create a unique file name.

// Handle file upload
if(isset($_FILES['file'])){
    $file_name = $_FILES['file']['name'];
    $file_tmp = $_FILES['file']['tmp_name'];
    
    // Generate a unique file name
    $new_file_name = time() . '_' . uniqid() . '_' . $file_name;
    
    // Move uploaded file to desired directory with the new file name
    move_uploaded_file($file_tmp, 'uploads/' . $new_file_name);
}