CodeIgniter Forums
How to Sanitize data in FilterInterface CI4 - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to Sanitize data in FilterInterface CI4 (/showthread.php?tid=77796)



How to Sanitize data in FilterInterface CI4 - what2see - 10-19-2020

Hi,

Can somebody tell me how to use FilterInterface in modifying request before using it in the Controller? I want to sanitize or to remove unwanted characters in the data before using it in my Controller.

Here is the sample of my code: 

Filter:

PHP Code:
namespace App\Filters;

use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;

class 
SanitizeFields implements FilterInterface
{

    protected $session;

    public function before(RequestInterface $request$arguments null)
    {
        $request->getVar('number_only'FILTER_SANITIZE_NUMBER_INT);
    }

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        // Do something here
    }



Controller: 
PHP Code:
//controller
public function getData()
{
    echo $this->request->getVar('number_only');


Is it possible to sanitize the value of number_only variable from "123abc456" to "123456"? 

Thank you!


RE: How to Sanitize data in FilterInterface CI4 - InsiteFX - 10-20-2020

PHP Code:
// Check to see if the variable is an integer
if (filter_var($this->request->getVar('number_only'), FILTER_VALIDATE_INT) === false)
{
    // ERROR!  
}
else
{
    echo $this->request->getVar('number_only');