1. Go to this page and download the library: Download bgeneto/ci4-sanitize library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
bgeneto / ci4-sanitize example snippets
namespace App\Models;
use CodeIgniter\Model;
use Bgeneto\Sanitize\Traits\SanitizableTrait;
class Customer extends Model
{
use SanitizableTrait;
protected $table = 'customers';
protected $allowedFields = ['name', 'email', 'phone'];
protected function initialize(): void
{
parent::initialize();
$this->setSanitizationRules(['name' => ['uppercase'], 'email' => ['trim']]);
$this->setSanitizationCallbacks(['beforeInsert', 'beforeUpdate']);
}
}
namespace Bgeneto\Sanitize\Config;
use CodeIgniter\Config\BaseConfig;
class Sanitization extends BaseConfig
{
public array $rules = [
'UserModel' => [
'name' => ['trim', 'norm_spaces', 'uppercase'],
'phone' => ['trim', 'numbers_only'],
],
// Other models sanitization rules can be added here:
'TestModel' => [
'phrase' => ['trim', 'norm_spaces', 'capitalize'],
],
];
}
class Sanitization extends BaseConfig
{
public array $rules = [
'UserModel' => [
'name' => ['trim', 'alpha_only'], // see new rule below
'phone' => ['trim', 'numbers_only'],
],
];
// new custom rule:
public static function alpha_only(string $value): string
{
return preg_replace('/[^\p{L}]/u', '', $value);
}
}
namespace App\Models;
use CodeIgniter\Model;
use Bgeneto\Sanitize\Traits\SanitizableTrait;
class UserModel extends Model
{
use SanitizableTrait;
protected $table = 'users';
protected $allowedFields = ['name', 'email', 'phone'];
protected function initialize(): void
{
parent::initialize();
// We just need to configure the desired sanitization callbacks
$this->setSanitizationCallbacks(['beforeInsert', 'beforeUpdate']);
}
}