Protecting webpage text from being selected I've got a text I don't want to be copied by users.
To avoid that, I'm using this code:
index.php

&lt;?php
session_start();
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i &lt; 100; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
$_SESSION['token'] = $randomString;
?&gt;
&lt;!DOCTYPE html&gt;
&lt;head&gt;
  &lt;meta charset="utf-8"&gt;
  &lt;title&gt;Test&lt;/title&gt;
  &lt;script src="../jquery.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;script&gt;
$(document).ready(function(){
$("#content").load("page.php?token=&lt;?php echo $_SESSION['token']; ?&gt;", function (responseText, textStatus, req) {if (textStatus == "error") {
$("#content").html('An error occurred :(');
}
});
});
&lt;/script&gt;
&lt;div id="content"&gt;Please wait...&lt;/div&gt;
&lt;/body&gt;


page.php

&lt;?php
session_start();
if(!empty($_SESSION['token']) AND $_GET['token']==$_SESSION['token']){echo '
&lt;script&gt;
function error(){
alert("This text is protected");
}
$(document).ready(function(){ 
$(document).mousedown(function(e){ 
    if( e.button == 2 ) { 
    error();
    return false;
    } 
  }); 
  $(document).keydown(function(){
  error();
  return false;
  });
});
&lt;/script&gt;
Text...';
unset($_SESSION['token']);
}
else{echo 'Error.';
}
?&gt;


Is this method reliable?
That is an old skool question, the common wisdom is that you cannot prevent a user from getting to the text. There are a number of ways to get around your protection.

For example, in Chrome, open Developers Tools, open your site, check the web request, and then all the text will be perfectly copy pastable.

Other than that:


alert() has been a bad practice for 20 years now, please use something else
Indent your code, use jsbeautifier if you have trouble
In the keydown, I would check whether the control key is pressed before throwing an error, unless the user never needs to press PageUp or PageDown
I am not entire surely, but I think you will need event.preventDefault(); to really prevent right clicking etc.