Jinsi ya Kufahamu CSRF Tokens kwa Form Security
CSRF tokens hutoa unique key kwa kila form submission.
Server inachunguza token ili kuthibitisha request ni halali.
βοΈ 2. Generating CSRF Token
<?php
session_start();
// Generate CSRF token if not exists
if(empty($_SESSION['csrf_token'])){
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
?>
π‘ Maelezo:
bin2hex(random_bytes(32)) inazalisha token isiyo predictable.
Token inahifadhiwa kwenye session server-side.
π 3. Adding CSRF Token to Form
<form method="POST" action="process_form.php">
<input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
<input type="text" name="name" placeholder="Enter your name" required>
<button type="submit">Submit</button>
</form>
Token lazima iende pamoja na form submission.
π 4. Validating CSRF Token
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']){
die("β Invalid CSRF token. Request denied.");
}
// Proceed with form processing
$name = $_POST['name'];
echo "β Form submitted successfully. Name: " . htmlspecialchars($name);
}
?>
π‘ Maelezo:
Compare token from POST with token in session.
Invalid token = reject request immediately.
π§ 5. Vidokezo vya Usalama
Use unique token per session β avoid using predictable token.
Regenerate token periodically β optionally after successful submission.
Combine with other security measures β password hashing, prepared statements, input validation.
Escape output β use htmlspecialchars() ili kuzuia XSS.
β 6. Hitimisho
CSRF tokens ni must-have kwa web forms.
Zinahakikisha requests ni legitimate na zinatoka kwa user halali.
Best practice: unique session token, validate on server, combine with other security practices.
π Tembelea:
π https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, form security, na web application best practices.