kirk
kirk

Reputation: 3

PHP apostrophe escaped breaking links

I was provided with a set of data that represents URL links. Such as: "doug'sfood.jpg".

.

I keep these strings in an array, and then select them randomly to display inserting them into an

<img src="doug'sfood.jpg"></img>

What Chrome is putting out is:

<img src="doug&#39;sfood.jpg"></img>

I tried replacing the quotes with a php escaped (\') apostrophe, but this just ended the quote prematurely.

Can someone help me? Thanks.

Upvotes: 0

Views: 4690

Answers (2)

Anne
Anne

Reputation: 27073

I think Chrome automatically escapes characters that are not correctly escaped.

Always use:

<img src="quote&#39;quote.jpg" alt="" />

Instead of:

<img src="quote'quote.jpg" alt="" />

Certain characters should always be escaped in HTML, for example:

' -> &#39;
& -> &#38; or &amp;

Check the htmlspecialchars() and urlencode() functions, example:

$string = "quote'quote.jpg";

echo htmlspecialchars($string, ENT_QUOTES);
// quote&#039;quote.jpg

echo urlencode($string);
// quote%27quote.jpg

Upvotes: 2

mario
mario

Reputation: 145482

Anyway, when printing out the filename tags, use urlencode() rather than relying on HTML escapes or browser behaviour:

foreach ($img as $href) {
    print '<img src="' . urlencode($href) . '" />';        
}

This will become doug%27sfood.jpg in your example (AKA the correct way to do it). Which hopefully can be located by your webserver.

Upvotes: 0

Related Questions