trueinViso
trueinViso

Reputation: 1394

htmlspecialchars won't convert quotes

htmlspecialchars won't work in my page to remove the back slashes before escaped apostrophes placed there by pdo objects. I am assuming this is because I am using UTF-8 on my page to display Chinese characters. I am trying to display a paragraph in English and a paragraph in Chinese. This is the code I am using:

$english=htmlspecialchars($row["english"], ENT_QUOTES, 'UTF-8');

For some reason it always displays like this:

Don\'t

There is no removal of the escape character...

Upvotes: 0

Views: 828

Answers (3)

Iłya Bursov
Iłya Bursov

Reputation: 24146

  1. PDO objects do not place slashes for '.
  2. htmlspecialchars() do not strip slashes
  3. It is actually incorrect to escape single quotes during display in HTML, only double quotes are special symbols.

So, here is usual example of XY problem (can I show this question to students?)

To understand what is going wrong you need to know next things:

  1. PHP can add \ to input arguments if magic_quotes are enabled - you need to turn them off (via php.ini or during runtime for php < 5.3. Also turn off magic_quotes_sybase.
  2. During insertion of data into database you (sometimes) need to escape single-quotes. This is usually done by PDO functions if you're using them right. If you're using bindParam, you do not need to use any other escaping.
  3. During fetching of data from database you may have problems with magic_quotes_runtime, so turn them off.
  4. Finally, you're outputting your data to HTML -- here you need to use htmlspecialchars() but without any attributes, as the default ones are okay.

If you have 1 or 2 problem - data in your database may already be corrupt, so you need to re-save them without the incorrectly added \ - for this you can use stripslashes(), but only one time to re-save data. During ordinary work of your system, you need to use proper approach.

Upvotes: 4

Pekka
Pekka

Reputation: 449415

Don\'t

This shouldn't be happening in the first place. There is likely a bug further up the stream (like, when the data gets inserted into the database) that should be fixed, instead of treating the symptom.

Upvotes: 2

iam-decoder
iam-decoder

Reputation: 2564

replace your variable with this:

$english = stripslashes(htmlspecialchars($row["english"], ENT_QUOTES, 'UTF-8'));

the stripslashes part will get rid of the slashes, but it might un-sanitize your string.

Upvotes: 0

Related Questions