0

What is the best way to decode the following URL to use with JavaScript?

URL:

https://www.example.com/post.php?v=1&text=it's-me&20hello%0Aworld%0A

Currently if a ' is present in the URL, it's causing an error and newlines (blank lines) are also not interpreted.

Code:

<?php
$postText = $_GET["text"]; 
?>  

<!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <script type="text/javascript">
      var options = {
        prefilltext: '<?php echo $postText;?>',
      };
    </script>
    </body>
    </html>
Matt
  • 2,981
  • 5
  • 23
  • 33
  • possible duplicate of [How to escape only single quotes?](http://stackoverflow.com/questions/6269188/how-to-escape-only-single-quotes) – Oriol Mar 22 '14 at 20:20

3 Answers3

0

The problem isn't that you must decode the url, it's that it must have single quotes escaped to avoid a javascript syntax error.

prefilltext: 'a'b'  // error
prefilltext: 'a\'b' // ok

To escape, you can use

echo str_replace('\'', '\\\'', $myString);
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

Because a double quote is not a legal URL character, but single quote is, you can delineate your javascript string with double quotes and you should be safe. There shouldn't be any double quotes in the string because it isn't a legal URL character whereas single quote is a legal URL character.

var options = {
    prefilltext: "<?php echo $postText;?>",
  };

The string can be properly prepared for being in a URL with PHP's urlencode(), though it looks like it may have already been encoded because of the %20 that's already in it.

You may also be interested in PHP's addslashes() function.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • What if `$postText` contains double quotes? There must be some escaping, either of single or double ones. – Oriol Mar 22 '14 at 20:31
  • Double quotes aren't legal characters in a URL. PHP's `urlencode()` would take care of the double quotes if the string hasn't already been made safe for a URL, though it looks like it has because of the `%20` that's already in it. – jfriend00 Mar 22 '14 at 20:33
  • @Oriol - Added a few more notes to my answer about PHP's `urlencode()` and `addslashes()`. – jfriend00 Mar 22 '14 at 20:38
0

Although addslashes would work in this case, I prefer to take a stronger action and run everything through JSON.

<?php
var $mystring = "A really complex string\r\nWith line breaks";
?>

<script>
  var jsstring = <php echo json_encode($mystring); ?>;
</script>
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74