简体   繁体   English

PHP / mySQL-在插入数据库之前如何安全地编码/解码/转义/任何需要的字符串

[英]PHP/mySQL - how to encode/decode/escape/whatever needed strings safely before inserting on database

My problem is this: I have a database where all fields are VARCHAR. 我的问题是:我有一个所有字段均为VARCHAR的数据库。 Some represent html code. 有些代表html代码。 This code contains chars like ◉, ⬛︎, ◔, ➜, ★, ✦, etc. These characters are not encoded on the HTML. 此代码包含char,⬛︎,◔,➜,★,✦等字符。这些字符未在HTML上编码。 They are like you see them here. 他们就像你在这里看到他们一样。

Other fields on that database are URLs. 该数据库上的其他字段是URL。

I know I have to escape these chars to prevent sql-injection and also have to encode them to allow insertion on the database. 我知道我必须转义这些字符以防止sql注入,还必须对它们进行编码以允许在数据库中插入。

htmlspecialchars will not handle these symbols because they are not encoded on the source. htmlspecialchars将不处理这些符号,因为它们未在源上进行编码。 mysql_escape_string will only escape bars and double quotes, etc. mysql_escape_string将仅转义小节和双引号等。

How do I really encode this and escape in PHP so I can insert this data on the database and how do I read them back? 我该如何真正编码并在PHP转义,以便可以将这些数据插入数据库中以及如何读回它们?

thanks. 谢谢。

I have found same problem when i insert German string value into varchar type field, string are converted to unreadable characters. 当我将德国字符串值插入varchar类型字段时,我发现了同样的问题,字符串被转换为不可读的字符。

This is the problem of UTF-8, I solve this issue by following thing: 这是UTF-8的问题,我通过以下方法解决了这个问题:

$con = mysqli_connect("localhost","root","root");
mysqli_query($con,"SET NAMES 'utf8'");

I hope it will fix your problem in every fields of your DB. 我希望它能解决您数据库中每个字段的问题。

Use parameterized queries to prevent SQL injection. 使用parameterized queries来防止SQL注入。 And use htmlspecialchars() function when you display data in html. 在html中显示数据时,请使用htmlspecialchars()函数。 With PDO that I love: 使用我喜欢的PDO:

$db = new PDO($dsn, $db_user, $db_password);
$query = 'INSERT INTO table (data1, data2) VALUES (:data1, :data2)';
$statement = $db->prepare($query);                          
$statement->bindValue(':data1',$data1);
$statement->bindValue(':data2',$data2)
$statement->execute();

如果您要删除常规az字母和0-9数字旁边的所有字符,请使用preg_match:

preg_match("/^[a-zA-Z0-9]+$/", $value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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