What role does CSRF protection play in safeguarding PHP applications from unauthorized requests and potential data manipulation attacks?
CSRF protection helps prevent attackers from tricking users into unknowingly submitting malicious requests on behalf of the user. This safeguard is crucial in preventing unauthorized requests that could lead to data manipulation attacks in PHP applications.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token validation failed.');
}
// Process the form data
}
$csrf_token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;
?>
<form method="post">
<input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>