8

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?

2

3 Answers 3

8

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);
Sign up to request clarification or add additional context in comments.

1 Comment

or, Output = htmlspecialchars, DB Input = mysql_real_escape_string
3

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

Comments

2

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

1 Comment

There is no such thing like injection but improperly formatted query only. Prepared statements are the proper way to be 100% safe, read more at phpdelusions.net/sql_injection Data should be stored unmodified! htmlspecialchars() seems a good way to go for the html-output, see answer of mario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.