1

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

  • text
  • white spaces
  • multilines
  • HTML tags
  • single and double quotes
  • slashes
  • and whatnot...

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.

2 Answers 2

5

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>
Sign up to request clarification or add additional context in comments.

5 Comments

For some reason - in the above example - adding json_encode() instead of addslashes() breaks Javascript altogether even when using plain text. Perhaps because I'm using double quotes?
@Paul — Yes, json_encode will output a literal (string, array, object, etc). You need to output it directly and not wrap it in quotes (which it might contain) to make it a string.
I need to use PHP for() to generate very, very long multi-dimensional Javascript array(). The above example is my only choice. In my question I simplified it. Is there any way to do it using my above example?
Use for() to generate a very long multi-dimensional PHP array. Then json_encode it.
EDIT: Okay, I tested and it so far it is okay.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.