What are the best practices for securing AJAX requests in PHP to prevent unauthorized database changes?
To secure AJAX requests in PHP and prevent unauthorized database changes, it is important to implement server-side validation and authentication checks. This can include verifying user permissions, using CSRF tokens, and sanitizing input data to prevent SQL injection attacks.
// Example PHP code snippet to secure AJAX requests
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_SESSION['user_id'])) {
// Redirect or return error message for unauthorized access
exit();
}
// Validate CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
// Handle CSRF token validation failure
exit();
}
// Sanitize input data
$data = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Perform database operations with validated and sanitized data
// Example: $stmt = $pdo->prepare("INSERT INTO table (column) VALUES (:value)");
// Example: $stmt->bindParam(':value', $data['value']);
}