Using mysql_real_escape_string with PDO (no connection to localhost server)

∥☆過路亽.° 提交于 2019-12-04 01:56:31

问题


So I'm fairly paranoid and use mysql_real_escape_string() with PDO. I actually don't use prepared statements in PDO, so I do have to sanitize the inputs.

When hosting on my own server, I'd create an unprivileged user on the local machine so mysql_real_escape_string() wouldn't fail and empty my variable (heh, now that's sanitization!). I realize this is a pretty fail solution, since if the db's don't have matching charsets, then there's no point to the sanitizing at all, but it worked for the interim.

Now at my new host, I can't create an unpassworded, unprivileged user for the database... and mysql_real_escape_string() fails because there is no mysql server on the local machine. I can't edit php.ini to set the hostname/user/pass for the default database.

What can I do?

Brainstorming as I am writing this, I am wondering if php allows runtime changes to the config... maybe... hrm. Edit: Hm... ini_set()? :O


回答1:


Mixing two database libraries like this is a bad idea and potentially unsafe.

mysql_real_escape_string() needs an existing, classic mysql_connect() database connection (which it can get character set info from) to be totally safe. The PDO connection will be separate, possibly with different character set settings, ultimately resulting in less security:

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Use PDO all the way, there's no alternative.

If you don't want to use prepared statements, PDO::quote should be the correct function:

Returns a quoted string that is theoretically safe to pass into an SQL statement.

Note however that even the manual page for that function recommends using prepared statements instead.




回答2:


The usefulness of using PDO is to don't worry about escape stuff.

I suggest you to use prepare and let PDO do the dirty job.



来源:https://stackoverflow.com/questions/6191801/using-mysql-real-escape-string-with-pdo-no-connection-to-localhost-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!