简体   繁体   中英

PHP MySQL how to properly store / escape string

I am having an issue with string sting that contains <br/> or & , < and so on.

I am escaping it like this before I store them into DB

nl2br(htmlentities($string, ENT_QUOTES, 'UTF-8'));

However some times when I display stored results I get stuff like this

&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;&lt;br /&gt;&lt;br /&gt;<br /><br />

can someone help / show me the best way to escape strings but preserve the break points and so on when I want to display it back on the screen.

thanks you

Ensure you set the double_encode to false , otherwise already encoded strings will be encoded again, turning &amp; into &amp;amp; . Then when you go to display it after using html_entity_decode , it will appear as if it was still encoded.

Undesirable Result: http://ideone.com/uQxuAM


Using htmlentities($string, ENT_QUOTES, 'UTF-8', false); will ensure this will not happen.

Then use html_entity_decode($string, ENT_QUOTES, 'UTF-8'); to display the value.

Demo: http://ideone.com/8Jo7YA


However, MySQL is fully capable of storing the decoded values in the database.

You never want to have htmlentities-encoded strings stored in your database. What happens when you want to generate a CSV or PDF, send an email, or anything which isn't HTML?

Aside from the fact you have to perform double the programming of encoding the data, increasing the amount of data in the database, then still need to decode the output, there are tons of articles online answering why you shouldn't.

So you should only ever need to encode the values for displaying the resulting data output in html.

Instead you should escape the input using mysqli_real_escape_string

$string = '<a href="/path/to/file?a=b&foo=bar#baz">My Link</a>';
$sql = "INSERT INTO links (link)"
     . "VALUES(" . mysqli_real_escape_string($string) . "')";

or better yet use prepared statements

$stmt = $mysqli->prepare("INSERT INTO links (link) VALUES(?)");
$stmt->bind_param("s", $string);
$stmt->execute();

Then to format the output as a success message to display what was actually added to the database.

$html = "<div>Added Link: " . htmlentities($string, ENT_QUOTES, 'UTF-8', false) . "</div>";

Now there is no need to use html_entity_decode to have the html rendered in the browser.

html_entity_decode() might do this.

$string = '<a href="http://test.com>test</a><br/>test';
$encode = nl2br(htmlentities($string, ENT_QUOTES, 'UTF-8'));

echo html_entity_decode($encode, ENT_QUOTES, 'UTF-8');

outputs original $string

<a href="http://test.com>test</a><br/>test

https://3v4l.org/qS5au

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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