I've this PHP page:
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars($line);
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
It generates this HTML results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I'm happy');"><div>
This code seems to be correct, however, clicking on second "div" element an error occurs.
The ' char is equivalent to ' and javascript generates an error:
alert('I'm happy');"
I solved this problem adding to code addslashes() PHP function:
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars(addslashes($line));
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
Correct results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I\'m happy');"><div>
My question:
Is this the right/best solution? Which is the best practice to manage this kind of problems?