Web applications zinaweza kuwa vulnerable kwa attacks mbalimbali ikiwa best practices za security hazitazingatiwa.

Common vulnerabilities ni pamoja na:

SQL Injection

Cross-Site Scripting (XSS)

Cross-Site Request Forgery (CSRF)

File Upload Vulnerabilities

Insecure Password Storage

Session Hijacking / Session Fixation

⚙️ 2. Example 1: SQL Injection
<?php
// Vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);


Problem: Attacker anaweza kuingiza input kama:

' OR '1'='1


Hii inaweza kuruhusu unauthorized login.

Solution: Use Prepared Statements na parameterized queries.

🧩 3. Example 2: XSS (Cross-Site Scripting)
<?php
// Display user comment
echo "<p>" . $_POST['comment'] . "</p>";


Problem: User anaweza inject script:

<script>alert('XSS')</script>


Script it executed in browser ya other users.

Solution: Use htmlspecialchars():

echo "<p>" . htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8') . "</p>";

🛡️ 4. Example 3: CSRF
<form action="delete_account.php" method="POST">
<input type="hidden" name="user_id" value="123">
<button type="submit">Delete Account</button>
</form>


Problem: Attackers wanaweza force user ku-submit request isiyotarajiwa.

Solution: Use CSRF tokens kwa forms:

<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

⚙️ 5. Example 4: Insecure Password Storage
// Vulnerable code
$password = $_POST['password'];
$sql = "INSERT INTO users (username,password) VALUES ('$username','$password')";


Problem: Passwords zinahifadhiwa plain text.

Solution: Hash passwords using password_hash():

$hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);

🔑 6. Best Practices

Always sanitize & validate input – prevent SQLi, XSS.

Use prepared statements – secure database queries.

Escape output – htmlspecialchars() for HTML.

Protect forms with CSRF tokens.

Hash passwords – never store plain text.

Secure file uploads – validate type, size, and rename files.

Use HTTPS – protect data in transit.

✅ 7. Hitimisho

Awareness of vulnerabilities ni step ya kwanza kwenye secure PHP development.

Combine prepared statements, input sanitization, CSRF tokens, password hashing, na HTTPS kwa maximum protection.

Regularly review OWASP Top 10 vulnerabilities kwa updated practices.

🔗 Tembelea:

👉 https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, web security, na prevention ya vulnerabilities.