7. Security Best Practices

Input Validation:

Always validate user inputs to prevent SQL injection and other attacks.

// Good: Use filter_var for input validation.
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);  

// Bad: Avoid trusting user inputs without validation.
$email = $_POST['email']; 

Password Hashing:

Hash passwords before storing them in the database.

// Good: Use password_hash for hashing passwords.
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);  

// Bad: Avoid storing plain text passwords.
$hashedPassword = $password; 

Output Escaping

Always validate user inputs to prevent SQL injection and other attacks.

// Good
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');  

// Bad
$name = $_POST['name']; 

Prepared Statements:

Always use prepared statements to prevent SQL injection and other attacks.

// Good
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); 
$stmt->execute(['id' => $id]);  

// Bad
$result = $pdo->query("SELECT * FROM users WHERE id = $id"); 

Cross-Site Scripting (XSS):

Always escape user input to prevent XSS attacks.

// Good
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');  

// Bad
echo $userInput; 

Cross-Site Request Forgery (CSRF):

Always use CSRF tokens to prevent CSRF attacks.

// Good 
<form method="post" action="/submit">     
    <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>"> 
</form>  

// Bad 
<form method="post" action="/submit">     
<!-- No CSRF token --> 
</form> 

Secure File Uploads:

Validate file uploads to prevent malicious uploads.

// Good
if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {         
    $fileTmpPath      = $_FILES['file']['tmp_name'];
    $fileName         = $_FILES['file']['name'];
    $allowedFileTypes = ['image/jpeg', 'image/png'];
    $fileType         = mime_content_type($fileTmpPath);

    if (in_array($fileType, $allowedFileTypes)) {         
        move_uploaded_file($fileTmpPath, "/uploads/$fileName");     
    } 
}  

// Bad
if (isset($_FILES['file'])) {     
    move_uploaded_file($_FILES['file']['tmp_name'], "/uploads/{$_FILES['file']['name']}"); 
}