What is the recommended method for uploading and storing avatars in PHP?

When uploading and storing avatars in PHP, it is recommended to use a secure method to prevent security vulnerabilities such as file injection attacks. One common approach is to upload the avatar to a designated folder on the server and store the file path in a database. This way, the avatar can be retrieved and displayed on the website without directly exposing the file path.

<?php
// Check if the form was submitted
if(isset($_POST['submit'])){
    // Define the target directory to store avatars
    $targetDir = "avatars/";
    
    // Generate a unique filename for the avatar
    $avatarName = uniqid() . '_' . $_FILES['avatar']['name'];
    
    // Specify the target file path
    $targetFilePath = $targetDir . $avatarName;
    
    // Move the uploaded file to the target directory
    if(move_uploaded_file($_FILES['avatar']['tmp_name'], $targetFilePath)){
        // Store the file path in the database
        $avatarPath = $targetFilePath;
        // Perform database query to store $avatarPath
        // Display success message
        echo "Avatar uploaded successfully!";
    } else{
        // Display error message if file upload fails
        echo "Error uploading avatar.";
    }
}
?>