Atadj
Atadj

Reputation: 7180

How to prepare PHP variable for Javascript array() use?

Let's say that we have input field or textarea where user can put anything. This means that user can put there:

My current code does this: <?php $data = addslashes($content_of_input); ?>

and soon after that...

<?php
    $php_generate_javascriptArray .='
        javascriptArray[0] ="'.$data.'";
    ';
?>
<script>
    javascriptArray = [];
    <?php echo $php_generate_javascriptArray; ?>
</script>

Adding slashes unfortunately isn't enough - Javascript breaks when user puts for instance multiple lines or HTML links into that. Is there any way to prevent that and still ALLOW Javascript array to contain LINK, MULTIPLE LINES, HTML TAGS? I'm looking for some universal filters.

Upvotes: 1

Views: 270

Answers (2)

Quentin
Quentin

Reputation: 943569

json_encode will convert a PHP data structure (or string, or number) to the appropriate JavaScript data structure while making it safe for injecting into a script element in an HTML document (by escaping slashes).

<script>
    var data = <?php echo json_encode($data); ?> ;
</script>

Upvotes: 6

FIG-GHD742
FIG-GHD742

Reputation: 2486

Use PHP function urlencode(...) or base64_encode(...) of need of more advanced protection.

I normal use urlencode and on Javascript side use unescape for decode the URL format data.

Upvotes: 1

Related Questions