Secure php output

I am trying to create “storage fields”, so if there is one mistake, you will no longer need to fill out the entire form. But how can I make a conclusion safe?

Example:

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

If someone types "'" (without 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 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 ///////

What should I do?

I'm no yes. But I thought htmlspecialchars made user input safe?

+6
php
source share
3 answers

It depends on the context.

htmlspecialchars() is your friend in HTML.

mysql_real_escape_string() is your friend in MySQL.

Update

First you can run all of your $_POST through htmlspecialchars() with this ...

 $encodedHtmlPost = array_map('htmlspecialchars', $_POST); 
+8
source share

You should use mysql_real_escape_string () before putting the data into the database, not for output! This will prevent SQL injection. Use htmlspecialchars when outputting data to the user, it prevents XSS attacks.

When pasted into a database:

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

When outputting to the user:

 echo htmlspecialchars($data); 
+1
source share

As for html escaping, you should use a wrapper function because htmlspecialchars needs some parameters to create reliable output:

  htmlspecialchars($text, ENT_QUOTES, "UTF-8"); 
+1
source share

All Articles