I'm sorry but I cannot reproduce the behaviour you describe. I've always used htmlspecialchars()
(which does essentially the same task as htmlentities()
) and it's never lead to any sort of double-encoding. The page source shows déjà vu
in both places (of course! that's the point!) but the rendered page shows the appropriate values and that's what sent back to the server.
Can you post a full self-contained code snippet that exhibits such behaviour?
Update: some testing code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
$default_value = 'déjà vu <script> ¿foo?';
if( !isset($_GET['foo']) ){
$_GET['foo'] = $default_value;
}
?>
<form action="" method="get">
<p><?php echo htmlentities($_GET['foo']); ?></p>
<input type="text" name="foo" value="<?php echo htmlentities($_GET['foo']); ?>">
<input type="submit" value="Submit">
</form>
</body>
</html>
Answer to updated question
The htmlentities()
function, as its name suggests, is used when generating HTML output. That's why it's of little use in your second example: JavaScript is not HTML. It's a language of its own with its own syntax.
Now, the problem you want to fix is how to generate output that follows these two rules:
- It's a valid string in JavaScript.
- It can be embedded safely in an HTML document.
The closest PHP function for #1 I'm aware of is json_encode(). Since JSON syntax is a subset of JavaScript, if you feed it with a PHP string it will output a JavaScript string.
As about #2, once the browser enters a JavaScript block it expects a </script>
tag to leave it. The json_encode() function takes care of this and escapes it properly (<\/script>
).
My revised test code:
<?php
$default_value = 'déjà vu </script> ¿foo?';
if( !isset($_GET['foo']) ){
$_GET['foo'] = $default_value;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function(){
$("input[type=text]").val(<?php echo json_encode(utf8_encode($_GET['foo'])); ?>);
});
//--></script>
</head>
<body>
<form action="" method="get">
<p><?php echo htmlentities($_GET['foo']); ?></p>
<input type="text" name="foo" value="(to be replaced)">
<input type="submit" value="Submit">
</form>
</body>
</html>
Nota: no utf8_encode() is required if your data is already in UTF-8.