简体   繁体   中英

How to protect variable table names against SQL injection in PHP

I am building a web app which relies heavily on a database. Here is an example of the type of query I use a lot:

CREATE TABLE item$userenteredname$username

Basically each time a create a new item, there is a table which stores info for every time something is added. So I need the table names to remain the same.

I recently spent quite a while updating my code to use PDO. I understand how to prepare statements and bind values, but you can't do this with table names. Haven't been able to find a proper answer to my question, which to clarify is...

How can I sanitise user input against sql injection when I can't use prepare's or mysql_real_escape_string because the variable is in a table name?

My strategy for this use case would be to strip out non-alphanumeric characters.

    $usereneteredname = preg_replace('/[^0-9a-zA-Z_]/', '', $usereneteredname);
    $username = preg_replace('/[^0-9a-zA-Z_]/', '', $username);

    // then "CREATE TABLE item$userenteredname$username"

This strategy is called whitelisting. That preg_replace call will replace anything that isn't 0-9a-zA-Z_ .

Further considerations:

You may also wish to validate the string lengths after the output, and make sure you are operating on a string not an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM