execv
execv

Reputation: 849

Handling Post Requests

I wrote this, and wanted to get everyones opinion. I use this when I'm expecting a variable from a FORM submission. Ie:

<form method="post" action="index.php">
Username: <input type="text" name="username">
</form>


$username = get_request('username');

function get_request($name) {
    if(isset($_REQUEST[$name])) {
        //return mysql_real_escape_string(htmlentities($_REQUEST[$name]));
        return mysql_real_escape_string($_REQUEST[$name]);
    } else {
        return "";
    }
}

Upvotes: 0

Views: 246

Answers (3)

kba
kba

Reputation: 19466

It looks OK, except it won't help you against certain SQL injections. You should add another argument to your function that sanitizes input according to types, for instance to make sure your return is an integer or a floating point number.

If for instance you have a pagination mechanism with a query SELECT * FROM tbl LIMIT 10, $page. If $page = like 1; DROP TABLE tbl -- and it gets send through your function get_request(), it won't help you any bit.

Another thing is you should just return null instead of an empty string ("") if it doesn't exist.

If you for instance have a variable $x = "", then isset($x) will return true, whereas it would return false with $x = null.

And as other people have pointed out, you should distinguish between GET and POST.

Upvotes: 1

Jamie Knight
Jamie Knight

Reputation: 26

While mysql_real_escape_string() does a good job, you may wish to be stricter on what you return. E.g. if you only need alphanumeric characters it would be safer (and possibly faster) to do:

return preg_replace('/[^a-z0-9]/', '', $_REQUEST[$name]);

Or even use filter_var if you are running PHP 5.2+.

Also as mentioned above, you if you can easily use $_POST instead of $_REQUEST if you are only handling POST data.

Other than than that, keep up the good work! :)

Upvotes: 1

Hjalmar
Hjalmar

Reputation: 1941

Nice, but shouldn't you want to return an error instead of an empty string if the $_REQUEST fails? Otherwise good!

Upvotes: 1

Related Questions