Add php user data to a java alert

4 posts by 3 authors in: Forums > CMS Builder
Last Post: July 31   (RSS)

I have the following java script which upon right click of mouse displays a message alert.

I'm having an issue adding PHP user data such as the users name and address to the "alert section" shown in red below. Can anyone help?

Thanks - Ray

------------------------- code script ----------------------------

<!-- web page warning box upon mouse right click -->
<script language="javascript">
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
alert("The RIGHT CLICK and web page print functions have been deactivated. Printing and redistribution of this product is strictly prohibited"); //here you draw your own menu
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
alert("The RIGHT CLICK and web page print functions have been deactivated. Printing and redistribution of this product is strictly prohibited");
window.event.returnValue = false;
});
}
</script>

nmsinc

Hi Ray,

What Robin suggested is the right approach, but I suggest that instead of just looking at quotes, you do a bit more to make sure things are secure. If you don't escape the values, you could open yourself up a security attack known as cross-site scripting attack (XSS). This allows someone to put some random code into the values for the user's name or address and when you echo it out to the user it will then run the attackers JavaScript as coming from you and can be used to hijack user's sessions etc. with other sites.

One way you can mitigate this issue is using the PHP function json_encode() to escape the code and make it safe for JS display. Below is an example...

<script>

  const jsUsernameSafe = <?php echo json_encode($username); ?>;

  alert(`Your username is ${jsUsernameSafe}`); //<-- Notice the use of backticks here for a template string literal (interpolation)

</script>


You may also want to just make sure that the user's name and address are not empty either an account for that. Not the greatest experience to say "Hello <blank>!" 

I hope this helps! :)

Tim Hurd
Senior Application Developer
TimHurd.com

Thanks everyone. I will give these a try!

nmsinc