Pit Digger Pit Digger - 1 year ago 85
Javascript Question

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']}';

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 ?

Answer Source

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

//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?>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download