JohnMichael JohnMichael - 1 month ago 9
PHP Question

Escaping this javascript code in php

I'm failing at escaping this code snippet that I only want to make visible on the page if a username is logged in. Then it just echoes that code, but as you can see, it's a large chunk that I need to escape. How do I go about that with this? Normally I don't have too much trouble with it myself but this code won't simply work otherwise.

//if user is logged in echo the code

if (isset($_SESSION['username'])){

echo '
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-PZWSZ2"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-PZWSZ2');</script>
';
}
?>

Answer

The issue is that you have single quotes to encapsulate the HTML and more inside the HTML that haven't been escaped \'. See PHP Strings.

But to present an alternative since there is no PHP in the HTML, just break out of PHP:

<?php
if (isset($_SESSION['username'])){
?>
   <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-PZWSZ2"
   height="0" width="0"   style="display:none;visibility:hidden"></iframe></noscript>
   <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
   new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
   j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
   '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
   })(window,document,'script','dataLayer','GTM-PZWSZ2');</script>
<?php
  }
?>

Also see Alternative syntax for control structures that may be easier or more readable.