> For the complete documentation index, see [llms.txt](https://docs.cmsfullform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cmsfullform.com/documents/helpers/security_helper.md).

# 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
