Cybersecurity ni hatua, mbinu, na teknolojia zinazotumika kulinda mifumo ya kompyuta, tovuti, na data dhidi ya wadukuzi, udukuzi wa taarifa, udanganyifu, na mashambulizi mengine ya mtandao. Lengo ni kuhifadhi usiri, integrity (uzima wa data), na availability (kupatikana kwa huduma).

2) Mifano ya code (PHP) — copy & paste, inafanya kazi

Kumbuka: badilisha DB_HOST, DB_USER, DB_PASS, DB_NAME kama inahitajika kabla ya kuendesha.

A. Connection ya DB (mysqli) — reusable
<?php
// db.php - Tumia kwa include/require
define('DB_HOST', 'localhost');
define('DB_USER', 'webuser');
define('DB_PASS', 'StrongPass123!');
define('DB_NAME', 'mydb');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
error_log("DB connect error: " . $conn->connect_error);
die("Database connection failed.");
}
$conn->set_charset('utf8mb4');
?>

B. Password hashing (signup) na verification (login)
<?php
// signup.php - hifadhi hashed password
require 'db.php';

$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

if ($username === '' || $password === '') {
die('Username na password vinahitajika.');
}

// Hash password kwa usalama
$hashed = password_hash($password, PASSWORD_DEFAULT);

$stmt = $conn->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
$stmt->bind_param('ss', $username, $hashed);
if ($stmt->execute()) {
echo "User created successfully.";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>

<?php
// login.php - verify password
require 'db.php';
session_start();

$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

if ($username === '' || $password === '') {
die('Username na password vinahitajika.');
}

$stmt = $conn->prepare("SELECT id, password_hash FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($id, $password_hash);
if ($stmt->fetch()) {
if (password_verify($password, $password_hash)) {
// Successful login - regenerate session id
session_regenerate_id(true);
$_SESSION['user_id'] = $id;
echo "Login successful.";
} else {
echo "Invalid credentials.";
}
} else {
echo "Invalid credentials.";
}
$stmt->close();
$conn->close();
?>

C. Prepared statement (misali wa select) — inalinda dhidi ya SQLi
<?php
// search_user.php
require 'db.php';

$term = $_GET['q'] ?? '';
$term = "%$term%";

$stmt = $conn->prepare("SELECT id, username FROM users WHERE username LIKE ? LIMIT 10");
$stmt->bind_param('s', $term);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);

header('Content-Type: application/json; charset=utf-8');
echo json_encode($rows);
$stmt->close();
$conn->close();
?>

D. CSRF token (form + validation)

A. Generate token na unaweza kuiweka kwenye form:

<?php
// csrf.php - include this at top of pages that render forms
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];
// >>> katika HTML form: <input type="hidden" name="csrf_token" value="<?php echo $csrf; ?>">
?>


B. Validate wakati wa ku-submit:

<?php
// process_form.php
session_start();

$posted = $_POST['csrf_token'] ?? '';
if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $posted)) {
http_response_code(400);
die('Invalid CSRF token.');
}
// end validate - endelea processing...
?>

E. Session security snippet (weka kwenye kila script ya protected)
<?php
// session_secure.php - include early in your app
ini_set('session.use_strict_mode', 1);
session_start([
'cookie_httponly' => 1,
'cookie_secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
'cookie_samesite' => 'Lax',
]);
if (empty($_SESSION['initiated'])) {
session_regenerate_id(true);
$_SESSION['initiated'] = time();
}
?>

F. File upload validation (basic, safe)
<?php
// upload.php
$allowed = ['jpg','jpeg','png','pdf'];
if (!isset($_FILES['file'])) {
die('No file uploaded.');
}
$filename = $_FILES['file']['name'];
$tmp = $_FILES['file']['tmp_name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$maxSize = 2 * 1024 * 1024; // 2 MB

if (!in_array($ext, $allowed)) {
die('File type not allowed.');
}
if ($_FILES['file']['size'] > $maxSize) {
die('File too large.');
}

// generate safe name and move to non-public folder if possible
$safeName = bin2hex(random_bytes(16)) . '.' . $ext;
$destination = __DIR__ . '/uploads/' . $safeName;

if (!move_uploaded_file($tmp, $destination)) {
die('Failed to move uploaded file.');
}

echo 'File uploaded successfully: ' . htmlspecialchars($safeName);
?>


Hakikisha uploads/ ina permissions sahihi na haifungulii kwa execution (weka .htaccess kuzuia .php execution au weka folder nje ya public_html).

3) Vidokezo vya haraka (quick checklist)

Tumia password_hash() na password_verify().

Tumia prepared statements (->prepare()) kwa queries zote zinazoingiza input ya mtumiaji.

Tumia HTTPS (SSL/TLS).

Tumia CSRF tokens kwa forms zinofanya state changes.

Sanitize output kwa browser (htmlspecialchars()) ili kuzuia XSS.

Weka sessions secure (httponly, secure cookie, regenerate id).

Back up data na uweke error logging badala ya kuonyesha errors kwenye browser.