What steps can be taken to ensure the security and integrity of a PHP script that allows users to delete database records based on user input?
To ensure the security and integrity of a PHP script that allows users to delete database records based on user input, you should validate and sanitize the user input to prevent SQL injection attacks. Additionally, you should implement proper authentication and authorization checks to ensure that only authorized users can delete records.
<?php
// Validate and sanitize user input
$record_id = filter_input(INPUT_POST, 'record_id', FILTER_SANITIZE_NUMBER_INT);
// Check if user is authorized to delete record
if ($user_is_authorized) {
// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute SQL query to delete record
$sql = "DELETE FROM records WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $record_id);
$stmt->execute();
// Close connection
$stmt->close();
$conn->close();
echo "Record deleted successfully";
} else {
echo "You are not authorized to delete this record";
}
?>
Related Questions
- In the context of comparing XML files in PHP, what are the advantages of using DOMDocument over SimpleXML, and when should each be preferred?
- How can error handling and debugging be enhanced in PHP scripts to identify issues like incorrect passwords during login?
- How can the issue of Forbidden (Error 403) be resolved when it occurs only on a specific server while working fine on others?