Salines
Salines

Reputation: 5767

CakePHP 3: search form with get method and find condition, how to prevent SQL injection?

I have an HTML form with the GET method, and five text input field, which should help to filter the data. When users fill one or more fields, these data are shown as url query.

My question is how to safely use the this query data without the possibility of SQL injection?

EDIT Of course, is a simple filtering of user data, by name, location, etc., not fulltext search.

'first_name LIKE' => '%'.$this->request->query('first_name').'%'

Where is in the documentation explained bind method, like ?

->bind(':name', $this->request->query('name'))

Upvotes: 1

Views: 1013

Answers (2)

Inigo Flores
Inigo Flores

Reputation: 4469

To avoid SQL injection vulnerabilities, you can use query placeholders.

Your code should look something similar to

$query = $this->Users->find()
    ->where([
        'first_name LIKE' => '%:name%'
    ])
    ->bind(':name', $this->request->query('first_name'));

More information in:

Upvotes: 2

Pradeep Singh
Pradeep Singh

Reputation: 1290

You should consider using Search Plugin

Its just very simple, write this in controller

public $components = array(
    'Search.Prg'
);

public function index() {
    $this->Prg->commonProcess();
    $this->set('users', $this->paginate($this->Users->find('searchable',
    $this->Prg->parsedParams())));
}

And this one in Model

public $filterArgs = array(
    'first_name' => array(
        'type' => 'like',
        'field' => 'first_name'
    )
);

public function initialize(array $config = []) {
    $this->addBehavior('Search.Searchable');
}

and you are done.

For more examples, visit here

Upvotes: 1

Related Questions