开发者

php safe output

I'm trying to make a "remember fields" thingy, so if there is one error you won't have to fill in the whole form again. But how can I make the output safe?

Example:

<input type="text" name="email" value="<?php echo (isset($_POST['email'])) ? htmlspecialchars($_POST['email']) : ''; ?>" />

If someone types in " ' " (without the quotes) for example you get:

Warning: mysql_result() expects parameter 1 to be resource, boolean given in C:\wamp\www\pages\register.php on line 55

So then I tried:

<input type="text" name="email" value="<?php echo (isset($_POST['email'])) ? mysql_real_escape_string($_POST['email']) : ''; ?>" />

Then it just adds a lot of //////.

What should I do?

I'm a noob yes. But I thought htmlspecialchars made user in开发者_StackOverflow中文版put safe?


It depends on context.

htmlspecialchars() is your friend in HTML.

mysql_real_escape_string() is your friend in MySQL.

Update

You could run all your $_POST through htmlspecialchars() first with this...

$encodedHtmlPost = array_map('htmlspecialchars', $_POST);


You have to use mysql_real_escape_string() before you put data in database, not for the output! It will prevent SQL injections. Use htmlspecialchars when outputting data to user, it prevents XSS attacks.

When inserting in database:

$data = mysql_real_escape_string($data);

mysql_query("INSERT INTO table1(data) VALUES('$data')"); //Safe insertion

When outputting to user:

echo htmlspecialchars($data);


As for html escaping, you should use a wrapper function because htmlspecialchars needs some parameters to produce reliably safe output:

 htmlspecialchars($text, ENT_QUOTES, "UTF-8");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜