Welcome Guest, Not a member yet? Register   Sign In
CI4 filter before RequestInterface
#1

Hi,

I'm new in CodeIgniter 4. Is it possible to SANITIZE all request variables before using it in controller? 

number_only = '123abc456';
Code:
<?php 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 $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}
Code:
<?php
//controller
public function getData()
{
    echo $this->request->getVar('number_only');
}


I don't know if it is possible to output the data in controller with the sanitize number_only variable.
Output: 123456

Thanks!
Reply
#2

What I do is have some helper functions such as GetString($request, $variableName) and I use that to get all the variables coming from the client side that I am expecting to be a string. In that function, I put in all my sanitisers and any other cleanup code that I want to perform on all the String type inputs.

This makes my code clean and easy to read. it also help knowing that every instance of a variable that comes from a form or other source is cleaned correctly.

I have similar methods for each type that I am expecting from the client side and use them in all my controllers to get the inputs. it takes a little work to create the helper functions, but does make it quicker to write the code later.

I hope this helps, I don't see a way of doing what you are suggesting, unless you put the cleaned up inputs into some kind of global cache. You will have to know what they all are all the time, this seems a difficult way of maintaining the code and is prone to missing things and errors.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB