# 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.

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

Example:

```php
$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:**

```php
$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&#x20;

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

```php
// 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:

```php
$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()`:

```php
$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()`**:**

<pre class="language-php"><code class="lang-php"><strong>$_GET['&#x3C;script>alert(1)&#x3C;/script>'] = '123';
</strong>sget_security();
print_r($_GET);

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

**Security Benefit:** Prevents **parameter-based attacks**.

## Security\_helper in Controller

```php
<?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');
    }
}
```

{% hint style="success" %}
Conclusion

These functions improve security by preventing **XSS**, **SQL Injection**, and **Path Traversal attacks**
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cmsfullform.com/documents/helpers/security_helper.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
