Remy
Remy

Reputation: 81

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 input safe?

Upvotes: 8

Views: 4724

Answers (3)

mario
mario

Reputation: 145482

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");

Upvotes: 3

alex
alex

Reputation: 490233

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);

Upvotes: 8

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

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);

Upvotes: 2

Related Questions