How can errors be avoided when using the move_uploaded_file function in PHP?

When using the move_uploaded_file function in PHP, errors can be avoided by checking if the file was successfully uploaded before attempting to move it. This can be done by verifying the $_FILES array and checking for any errors during the upload process.

if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo "File uploaded successfully!";
    } else {
        echo "Error moving file.";
    }
} else {
    echo "Error uploading file.";
}