Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

SQL Injection on Models

I know that the best way to avoid SQL Injection is this way:

$model = Model::findFirst(
    array(
        'conditions' => 'name = ?1',
        'bind' => array(1 => $name)
    )
);

And that I should NOT use this:

$model = Model::findFirst('name = "' . $name . "'");

But I can't find much information on how safe this is:

$model = Model::findFirstByName($name);


60.9k
edited Jul '16

dont worry its safe enought. You can check your mysql logs to see the query but i am pretty sure you will see ? as a parameter.

No harm can be done by using intval here and there, also (int) $id but you will be ok.

source here; https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L4202

edit:

also about this

$model = Model::findFirst('id = ' . $id);

are you sure its not safe ? i am talking empty here but think all queries are prepared before that, ( cuz of the pdo ), so i dont think you can inject with that either.

you can try it yourself tho.. jsut

model::find("id = 1; DROP my_temp_table_i_created_for_this_case;")

but yea, someone can inject you with 5 or 1=1 to bypass the login ... meh... so yea dont use it :D

So it's safe even if I don't cast the id. I've changed id to name so it's a string and a better example.

If I use findBy... or findFirstBy... the value is binded for me?

dont worry its safe enought. You can check your mysql logs to see the query but i am pretty sure you will see ? as a parameter.

No harm can be done by using intval here and there, also (int) $id but you will be ok.

source here; https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L4202

edit:

also about this

``` $model = Model::findFirst('id = ' . $id); ```

are you sure its not safe ? i am talking empty here but think all queries are prepared before that, ( cuz of the pdo ), so i dont think you can inject with that either.

you can try it yourself tho.. jsut

```

model::find("id = 1; DROP mytemptableicreatedforthis_case;")

```

but yea, someone can inject you with 5 or 1=1 to bypass the login ... meh... so yea dont use it :D

Just if you pass one parameter phalcon will handle it :D