Security_helper

This Helper defines several security functions to sanitize user input and prevent security vulnerabilities such as XSS (Cross-Site Scripting), SQL Injection, and Directory Traversal attacks.

Prevent XSS

  • Converts special characters into HTML entities (e.g., < becomes &lt;, > becomes &gt;).

  • Prevents malicious JavaScript from being injected into web pages.

function xss_clean($data) {
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

Example:

$user_input = "<script>alert('Hacked!');</script>";
$clean_input = xss_clean($user_input);
echo $clean_input; 
// Output: &lt;script&gt;alert('Hacked!');&lt;/script&gt;

Clean Input Data to Prevent Attacks

  • Removes unnecessary spaces and backslashes.

  • Strips out single (') and double (") quotes to prevent SQL Injection.

  • Removes any special characters except letters, numbers, spaces, and punctuation.

Example:

$user_input = " DROP TABLE users; ";
$cleaned_input = clean_input($user_input);
echo $cleaned_input; 
// Output: DROP TABLE users

Security Benefit: Protects against SQL Injection and XSS attacks.

Secure

These functions sanitize user input from URL parameters ($_GET) and form data ($_POST).

// Get data from URL parameters
function S_GET($key, $default = null) {
    if (isset($_GET[$key])) {
        return clean_input($_GET[$key]);
    }
    return $default;
}

// Get data from form
function S_POST($key, $default = null) {
    if (isset($_POST[$key])) {
        return clean_input($_POST[$key]);
    }
    return $default;
}

// Get data from $_GET and $_POST
function S_REQUEST($key, $default = null) {
    if (isset($_REQUEST[$key])) {
        return clean_input($_REQUEST[$key]);
    }
    return $default;
}

// Check data from $_GET is exist
function HAS_GET($key) {
    return isset($_GET[$key]);
}

// Check data from $_POST is exist
function HAS_POST($key) {
    return isset($_POST[$key]);
}

// Check data from both $_GET and $_POST
function HAS_REQUEST($key) {
    if (isset($_REQUEST[$key])) {
        return true;
    }
    return false;
}

Example:

$btn    = S_POST('submit', 'default_value');
$id     = S_GET('id', 'default_value');

if (HAS_GET('id')) {
    echo "ID exists in the URL";
}

if (HAS_POST('submit')) {
    echo "Form submitted";
}

Secure URIs to Prevent Attacks

  • Removes dangerous characters from URLs.

  • Prevents directory traversal attacks by stripping out .. and ....

  • Allows only alphanumeric characters, underscores (_), hyphens (-), and dots (.) in URL segments.

Example using uri_security():

$unsafe_uri = "/admin/../../config.php";
$safe_uri = uri_security($unsafe_uri);
echo $safe_uri; 
// Output: admin/config.php

Security Benefit: Prevents unauthorized file access and path traversal attacks.

Secure All $_GET Parameters

  • Sanitizes all $_GET keys and values.

  • Removes dangerous characters while keeping alphanumeric characters, underscores (_), and dashes (-).

  • Prevents GET parameter manipulation attacks.

Example using sget_security():

$_GET['<script>alert(1)</script>'] = '123';
sget_security();
print_r($_GET);

// Output: Array([scriptalert1script] => 123)

Security Benefit: Prevents parameter-based attacks.

Security_helper in Controller

<?php
namespace App\Controllers;

use System\Core\BaseController;
use App\Models\UsersModel;

class UsersController extends BaseController {
    protected $usersModel;

    public function __construct() {
        $this->usersModel = new UsersModel();
    }
    
    public function profile(){
        $id = S_GET('id') ?? ''; 
        if(empty($id)) {
            $userInfo = $this->usersModel->getUserById($id);
        }
    }
    
    public function login() {
        if (HAS_POST('username')){
            $csrf_token = S_POST('csrf_token') ?? '';
            
            $input = [
                'username'  =>  S_POST('username') ?? '',
                'password'  =>  S_POST('password') ?? ''
            ];
            
            // Validate data $input
            
            $this->render('auth', 'Backend/Auth/login');
    }
}

Last updated

Was this helpful?