What is the best practice for handling file uploads in PHP to ensure that only one image file is stored per user?

To ensure that only one image file is stored per user, you can generate a unique filename based on the user's ID and replace any existing file with the same name. This way, each user will only have one image file associated with their account.

// Get the user's ID from the session or database
$user_id = $_SESSION['user_id'];

// Check if a file was uploaded
if(isset($_FILES['image'])){
    $file_name = $user_id . '_' . $_FILES['image']['name'];
    
    // Check if a file with the same name already exists
    if(file_exists('uploads/' . $file_name)){
        unlink('uploads/' . $file_name); // Delete the existing file
    }
    
    // Move the uploaded file to the uploads directory
    move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $file_name);
}