We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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);


85.5k
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 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

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