What are the best practices for handling user input and data deletion in PHP to ensure data integrity and security?

To handle user input securely in PHP, always validate and sanitize input data to prevent SQL injection and cross-site scripting attacks. When deleting data, ensure that proper authorization checks are in place to prevent unauthorized deletion of records. Additionally, consider implementing soft deletes instead of hard deletes to maintain data integrity.

// Validate and sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Delete data with proper authorization check
if($user->isAdmin()) {
    $id = $_GET['id'];
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    echo "User deleted successfully.";
} else {
    echo "Unauthorized to delete user.";
}

// Implement soft delete
$id = $_GET['id'];
$stmt = $pdo->prepare("UPDATE users SET deleted_at = NOW() WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
echo "User soft deleted successfully.";