{"id":25253244,"url":"https://github.com/bgeneto/ci4-sanitize","last_synced_at":"2026-02-23T12:50:29.673Z","repository":{"id":276980796,"uuid":"930934434","full_name":"bgeneto/ci4-sanitize","owner":"bgeneto","description":"A CodeIgniter 4 (CI4) library that provides a flexible, rule-based data sanitization solution.","archived":false,"fork":false,"pushed_at":"2025-02-22T13:43:05.000Z","size":50,"stargazers_count":0,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-03T16:43:41.469Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bgeneto.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-02-11T13:04:06.000Z","updated_at":"2025-02-22T13:43:08.000Z","dependencies_parsed_at":"2025-02-11T14:23:58.392Z","dependency_job_id":"04d98085-c393-4a85-bdec-b08e7ec06c75","html_url":"https://github.com/bgeneto/ci4-sanitize","commit_stats":null,"previous_names":["bgeneto/ci4-sanitize"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/bgeneto/ci4-sanitize","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bgeneto%2Fci4-sanitize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bgeneto%2Fci4-sanitize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bgeneto%2Fci4-sanitize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bgeneto%2Fci4-sanitize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bgeneto","download_url":"https://codeload.github.com/bgeneto/ci4-sanitize/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bgeneto%2Fci4-sanitize/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29743322,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-23T07:44:07.782Z","status":"ssl_error","status_checked_at":"2026-02-23T07:44:07.432Z","response_time":90,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-02-12T04:58:47.785Z","updated_at":"2026-02-23T12:50:29.655Z","avatar_url":"https://github.com/bgeneto.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ci4-sanitize\n\n[![Latest Stable Version](https://poser.pugx.org/bgeneto/ci4-sanitize/v/stable)](https://packagist.org/packages/bgeneto/ci4-sanitize)\n[![Total Downloads](https://poser.pugx.org/bgeneto/ci4-sanitize/downloads)](https://packagist.org/packages/bgeneto/ci4-sanitize)\n[![License](https://poser.pugx.org/bgeneto/ci4-sanitize/license)](https://packagist.org/packages/bgeneto/ci4-sanitize)\n\n`ci4-sanitize` is a PHP library for CodeIgniter 4 that provides data sanitization functionality. It allows you to easily sanitize user input and other data using a set of predefined rules or custom rules. This helps prevent security vulnerabilities like cross-site scripting (XSS) and SQL injection.\n\n\n\n## Quick Start\n\n1. Install with Composer: `composer require bgeneto/ci4-sanitize`\n\n2. Publish the config file: `php spark sanitize:publish`\n\n3. Set up your model: \n\n   ```php\n   \u003c?php\n   \n   namespace App\\Models;\n   \n   use CodeIgniter\\Model;\n   use Bgeneto\\Sanitize\\Traits\\SanitizableTrait;\n   \n   class Customer extends Model\n   {\n       use SanitizableTrait;\n   \n       protected $table         = 'customers';\n       protected $allowedFields = ['name', 'email', 'phone'];\n   \n       protected function initialize(): void\n       {\n           parent::initialize();\n           $this-\u003esetSanitizationRules(['name' =\u003e ['uppercase'], 'email' =\u003e ['trim']]);\n           $this-\u003esetSanitizationCallbacks(['beforeInsert', 'beforeUpdate']);\n       }\n   }\n   ```\n\n\n\n## Installation\n\n#### Composer + Packagist\n\n```bash\ncomposer require bgeneto/ci4-sanitize\n```\n\n#### Composer + GitHub repo:\n\nJust setup a repository like this in your project's `composer.json` file:\n\n```json\n{\n    \"require\": {\n        \"your-project/other-dependencies\": \"...\",\n        \"bgeneto/ci4-sanitize\": \"dev-main\"\n    },\n\n    \"repositories\": {\n        \"sanitize\": {\n            \"type\": \"vcs\",\n            \"url\": \"https://github.com/bgeneto/ci4-sanitize.git\"\n        }\n    }\n}\n```\n\n#### Composer + Local repo:\n\n```bash\ngit clone https://github.com/bgeneto/ci4-sanitize.git /path/to/your/local/ci4-sanitize\n```\n\nNow edit your `composer.json` file and add a new `path` repository:\n\n```json\n{\n    \"require\": {\n        \"your-project/other-dependencies\": \"...\",\n        \"bgeneto/ci4-secrets\": \"dev-main\"\n    },\n\n    \"repositories\": {\n        \"sanitize\": {\n            \"type\": \"path\",\n            \"url\": \"/path/to/your/local/ci4-sanitize\"\n        }\n    }\n}\n```\n\nPublish the configuration file after installing:\n\n```bash\nphp spark sanitize:publish\n```\n\n\n\n## Configuration\n\nThe package comes with a configuration file (`app/Config/Sanitization.php`) where you can define default sanitization rules for your models.\n\n```php\n\u003c?php\n\nnamespace Bgeneto\\Sanitize\\Config;\n\nuse CodeIgniter\\Config\\BaseConfig;\n\nclass Sanitization extends BaseConfig\n{\n    public array $rules = [\n        'UserModel' =\u003e [\n            'name'  =\u003e ['trim', 'norm_spaces', 'uppercase'],\n            'phone' =\u003e ['trim', 'numbers_only'],\n        ],\n        // Other models sanitization rules can be added here:\n        'TestModel' =\u003e [\n            'phrase' =\u003e ['trim', 'norm_spaces', 'capitalize'],\n        ],\n    ];\n}\n```\n\nYou can also add custom (new) rules to this config file:\n\n```php\nclass Sanitization extends BaseConfig\n{\n    public array $rules = [\n        'UserModel' =\u003e [\n            'name'  =\u003e ['trim', 'alpha_only'],  // see new rule below\n            'phone' =\u003e ['trim', 'numbers_only'],\n        ],\n    ];\n\n    // new custom rule:\n    public static function alpha_only(string $value): string\n    {\n        return preg_replace('/[^\\p{L}]/u', '', $value);\n    }\n}\n```\n\n\n\n## Usage\n\n### Sanitizer Class\n\nYou can use the `Sanitizer` class directly to sanitize\n\n```php\nuse Bgeneto\\Sanitize\\Sanitizer;\n\n$rules = [\n    'username' =\u003e ['trim', 'lowercase'],\n    'email'    =\u003e ['trim', 'email'],\n];\n\n$sanitizer = new Sanitizer($rules);\n\n$data = [\n    'username' =\u003e '  MyUser  ',\n    'email'    =\u003e '  test@example.com  ',\n    'age'      =\u003e '30',\n];\n\n$sanitizedData = $sanitizer-\u003esanitize($data);\n\n// Output:\n// [\n//     'username' =\u003e 'myuser',\n//     'email'    =\u003e 'test@example.com',\n//     'age'      =\u003e '30', // No rule for 'age', so it remains unchanged\n// ]\n```\n\nYou can also add rules dynamically:\n\n```php\n$sanitizer-\u003eaddRules(['username' =\u003e ['alphanumeric']]);\n$sanitizedData = $sanitizer-\u003esanitize($data);\n```\nYou can also apply rules at the time of sanitization, which will override any previously defined rules:\n```php\n$sanitizer = new Sanitizer(['name' =\u003e ['trim']]);\n$data = ['name' =\u003e '  John Doe  ', 'email' =\u003e ' test@example.com '];\n$lateRules = ['email' =\u003e ['trim', 'email']];\n$sanitizedData = $sanitizer-\u003esanitize($data, $lateRules);\n// Result: ['name' =\u003e 'John Doe', 'email' =\u003e 'test@example.com']\n```\n\n### Sanitizer Class Static Usage\n\nThe `Sanitizer` class provides several static methods for convenient sanitization:\n\n*   **`Sanitizer::registerRule(string $rule, callable $callback)`:** Registers a custom sanitization rule.\n*   **`Sanitizer::applyRule(mixed $value, string $rule)`:** Applies a sanitization rule (built-in or custom) to a value.\n*   **`Sanitizer::resetRules()`:** Resets all custom rules.\n\n**Registering and Using Custom Rules:**\n\n```php\nuse Bgeneto\\Sanitize\\Sanitizer;\n\n// Define a custom rule to append text to a string\nSanitizer::registerRule('append_text', function ($value, $params = []) {\n    $suffix = $params[0] ?? '_appended';\n    return $value . $suffix;\n});\n\n// Apply the custom rule\n$sanitized = Sanitizer::applyRule('My String', 'append_text:!!!'); // $sanitized = \"My String!!!\"\n\n// Another custom rule example: convert a string to a slug\nSanitizer::registerRule('my_slug', function ($value) {\n    $value = \\transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $value);\n    $value = \\preg_replace('/[^a-z0-9]+/u', '-', $value);\n    return \\trim($value, '-');\n});\n\n$slug = Sanitizer::applyRule('My Awesome Title', 'my_slug'); // $slug = \"my-awesome-title\"\n\nSanitizer::resetRules(); // Removes all custom rules\n```\n\n**Applying Built-in Rules:**\n\n```php\nuse Bgeneto\\Sanitize\\Sanitizer;\n\n$trimmed = Sanitizer::applyRule('  Hello World  ', 'trim'); // $trimmed = \"Hello World\"\n$lowercase = Sanitizer::applyRule('Hello World', 'lowercase'); // $lowercase = \"hello world\"\n$numbers = Sanitizer::applyRule('Phone: 123-456-7890', 'numbers_only'); // $numbers = \"1234567890\"\n$stripped = Sanitizer::applyRule('\u003cp\u003eHello\u003c/p\u003e\u003ca\u003eWorld\u003c/a\u003e', 'strip_tags_allowed:\u003cp\u003e'); // $stripped = \"\u003cp\u003eHello\u003c/p\u003eWorld\"\n\n```\n\n### Sanitizable Trait\n\nThe `SanitizableTrait` is designed for use with CodeIgniter 4 models. It automatically applies sanitization rules before inserting or updating data.\n\n```php\n\u003c?php\n\nnamespace App\\Models;\n\nuse CodeIgniter\\Model;\nuse Bgeneto\\Sanitize\\Traits\\SanitizableTrait;\n\nclass UserModel extends Model\n{\n    use SanitizableTrait;\n\n    protected $table         = 'users';\n    protected $allowedFields = ['name', 'email', 'phone'];\n    protected function initialize(): void\n    {\n        parent::initialize();\n        // We just need to configure the desired sanitization callbacks \n        $this-\u003esetSanitizationCallbacks(['beforeInsert', 'beforeUpdate']);\n    }\n}\n\n```\n\nThe trait will use the rules defined in the `Sanitization` config file for the `UserModel`.  You can also add rules dynamically:\n\n```php\n$model-\u003esetSanitizationRules(['name' =\u003e ['capitalize']]);\n```\n\nYou can retrieve the currently applied sanitization rules using `getSanitizationRules()`:\n\n```php\n$rules = $userModel-\u003egetSanitizationRules(); // Get all rules\n$nameRules = $userModel-\u003egetSanitizationRules('name'); // Get rules for the 'name' field\n```\n\nYou can also sanitize arbitrary data directly using the trait:\n\n```php\n$data = [\n    'name' =\u003e '  john doe  ',\n    'email' =\u003e '  test@example.com  ',\n];\n\n$sanitizedData = $userModel-\u003esanitizeData($data);\n```\n\n**Allowed Callbacks:**\n\nThe `SanitizableTrait` allows you to specify which model events should trigger sanitization. You can set these using the `setSanitizationCallbacks()` method. The allowed callbacks are:\n\n*   `beforeInsert`\n*   `beforeUpdate`\n*   `beforeFind`\n*   `beforeDelete`\n*   `beforeInsertBatch`\n*   `beforeUpdateBatch`\n\n### Built-in Rules\n\nThe following built-in rules are available:\n\n*   `trim`: Removes whitespace from the beginning and end of a string.\n*   `lowercase`: Converts a string to lowercase.\n*   `uppercase`: Converts a string to uppercase.\n*   `capitalize`: Capitalizes the first character of each word in a string.\n*   `numbers_only`: Removes all non-numeric characters from a string.\n*   `email`: Sanitizes an email address.\n*   `float`: Sanitizes a floating-point number.\n*   `int`: Sanitizes an integer.\n*   `htmlspecialchars`: Converts special characters to HTML entities.\n*   `norm_spaces`: Normalizes whitespace in a string (removes multiple spaces).\n*   `slug`: Generates a URL-friendly slug.\n*   `url`: Sanitizes a URL.\n*   `strip_tags`: Strips HTML and PHP tags from a string.\n*   `strip_tags_allowed`: Strips HTML and PHP tags, allowing specified tags (e.g., `strip_tags_allowed:\u003cp\u003e,\u003ca\u003e`).\n*   `alphanumeric`: Removes all non-alphanumeric characters from a string.\n\n### Custom Rules\nCustom rules can be used both globally (with `Sanitizer::registerRule()`) and within models that use the `SanitizableTrait`. The examples shown in the \"Sanitizer Class Static Usage\" section demonstrate how to define and use custom rules.\n\n## License\n\nThis package is open-sourced software licensed under the [MIT license](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbgeneto%2Fci4-sanitize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbgeneto%2Fci4-sanitize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbgeneto%2Fci4-sanitize/lists"}