Pit Digger
Pit Digger

Reputation: 9800

Javascript String with Single Quote printed from PHP code

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 ?

Upvotes: 1

Views: 1779

Answers (3)

mermshaus
mermshaus

Reputation: 646

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.

Upvotes: 0

Paris Liakos
Paris Liakos

Reputation: 2151

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>

Upvotes: 3

Aaron Ray
Aaron Ray

Reputation: 838

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>";

Upvotes: -1

Related Questions