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.";
Related Questions
- What best practices should be followed when writing SQL queries in PHP?
- What are the advantages of using a pre-built Mailer class like PHPMailer over the built-in mail() function in PHP?
- When implementing a solution for transferring selected values between select fields in PHP, what factors should be considered in terms of file size and programming effort?