1

I have following script printed from PHP . If some one has a single quote in description it shows javascript error missing ; as it thinks string terminated .

print   "<script type=\"text/javascript\">\n
    var Obj = new Array();\n
     Obj.title        = '{$_REQUEST['title']}'; 
     Obj.description     = '{$_REQUEST['description']}';
     </script>";

Form does a post to this page and title and description comes from textbox.Also I am unable to put double quotes around {$_REQUEST['title']} as it shows syntax error . How can I handle this ?

Pit Digger
  • 9,618
  • 23
  • 78
  • 122

3 Answers3

3

a more clean (and secure) way to do it (imo):

<?php 
//code here

$title = addslashes(strip_tags($_REQUEST['title']));
$description = addslashes(strip_tags($_REQUEST['description']));
?>
<script type="text/javascript">
 var Obj = new Array();
 Obj.title = '<?php echo $title?>'; 
 Obj.description = '<?php echo $description?>';
</script>
Paris Liakos
  • 2,131
  • 3
  • 22
  • 23
  • Yeah. I think `strip_tags()` does not add security here. All it will do is add another possibility to break user input (as it might eat stuff like `< 200`) – Pekka Jul 13 '11 at 21:28
  • I *think* a pure `addslashes()` should be safe enough. I can't think of a way to break that (although @Mike shows a potential one above) – Pekka Jul 13 '11 at 21:29
  • 1
    actually, I think you're right: It is indeed worth adding `strip_tags()` to prevent breaking out from the script as @Mike shows underneath my answer. +1 – Pekka Jul 13 '11 at 21:32
0

You also need to be careful with things like line breaks. JavaScript strings can't span over multiple lines. json_encode is the way to go. (Adding this as new answer because of code example.)

<?php

$_REQUEST = array(
    'title'       => 'That\'s cool',
    'description' => 'That\'s "hot"
                      & not cool</script>'
);

?>

<script type="text/javascript">
 var Obj = new Array();
 Obj.title = <?php echo json_encode($_REQUEST['title'], JSON_HEX_TAG); ?>;
 Obj.description = <?php echo json_encode($_REQUEST['description'], JSON_HEX_TAG); ?>;

 alert(Obj.title + "\n" + Obj.description);
</script>

Edit (2016-Nov-15): Adds JSON_HEX_TAG parameter to json_encode calls. I hope this solves all issues when writing data into JavaScript within <script> elements. There are some rather annoying corner cases.

Community
  • 1
  • 1
mermshaus
  • 646
  • 1
  • 5
  • 18
-1

Use the string concatenation operator:

http://php.net/manual/en/language.operators.string.php

print   "<script type=\"text/javascript\">\n
    var Obj = new Array();\n
     Obj.title        = '".$_REQUEST['title']."'; 
     Obj.description     = '".$_REQUEST['description']."';
     </script>";
Aaron Ray
  • 838
  • 5
  • 8