Tips, News and Comments on HTML Guard


Archive for the ‘Code Examples’ Category

February 24th, 2010, by Andreas

Using .htaccess to Mask watermark.php Calls

In a previous article, I demonstrated how one could use PHP to dynamically add watermarks to images. Implementing the solution I presented in that article required you to change your image links to something like this:

<img src="watermark.php?image=sample1.jpg&watermark=watermark.png" />

In this article, I will show you how you can easily watermark all images in a certain directory without changing your links to point to a .php file.

Solution Details

Let’s say the images you want to watermark are kept in a sub directory called “gallery” right below your domain folder. At this point, you will have to upload the watermarking script (watermark.php) and the watermark image (watermark.png) to that exact folder and create an .htaccess file containing the following two lines of code:

RewriteEngine on
RewriteRule ^(.*\.(gif|jp?g|png))$ /gallery/watermark.php?image=$1&watermark=watermark.png [NC]

By using the RewriteRule directory, you are telling the web server that image requests shall be processed by the “watermark.php” script file, as opposed to serving the images directly to the browser. The “watermark.php” script then places the “watermark.png” as a watermark on the requested image. After completing the .htaccess file, it must be uploaded (in ASCII mode) to the “gallery” directory.

Download Sample Files

If you wish to play around a bit with my sample code, I have created a zip file that contains all the necessary files for you to do so.


September 11th, 2009, by Andreas

About HTML Source Code Encryption

What Is HTML Encryption?

One major reason for the success of the World Wide Web is undeniably the openness of HTML. HTML files are basically plain text documents, meaning software applications and human users can easily create, read, and update web pages. The open nature of HTML not only allows users to edit websites with nothing more than a simple text editor, it also enables search engines to spider the web and forms the basis for a wide range of web-related applications for any platform you can imagine.

However, as a web designer or website owner you may encounter situations in which you feel a need for protecting your HTML, CSS or JavaScript code from being viewed and reused – for example, when you want to:

  • keep spam robots from harvesting email addresses from your pages.
  • safely email a website design preview to a customer before payment receipt.
  • stop competitors from studying and borrowing your fancy, hand-crafted JavaScript code.
  • prevent search engines from indexing and caching the phone number(s) listed on your contact page.
  • keep automated downloaders like WebZip or Teleport from copying your entire website.
  • bypass content filters imposed by companies, service providers, or governments.

In these situations HTML encryption is a viable option.

How It Works

HTML encryption/decryption techniques are based on JavaScript. The encrypted HTML code, which is saved inside the HTML document, is decrypted at runtime through JavaScript and written directly into the browser window using the document.write(…) function. This ensures that any JavaScript-enabled web browser can load and display the pages without additional components or plugins.

Any Drawbacks? How Secure Is This?

The following drawbacks should be considered before applying HTML encryption to your code:

  • Only users with JavaScript enabled in their browser will be able to view the pages.
  • Encrypted code cannot be analyzed by Google, which may hurt your search engine rankings.
  • The necessary decryption processing may slow down the page loading (although with modern high-speed computers, this is not really an issue).

In regard to security, you shouldn’t expect too much of HTML encryption. As the decryption algorithm is embedded into the pages, anyone with enough JavaScript knowledge and a bit of time can reverse engineer the code. Additionally, there are browser extensions available that can display the rendered (= decrypted) source code of the currently loaded web page. Nevertheless, the obfuscated code should be “Greek” to most users, therefore providing a certain degree of protection against illegal copying.

Encryption Methods

There are several different ways of encrypting/decrypting HTML pages via JavaScript, some of which I will describe here.

Escape Method

An easy way to obscure HTML code is to replace its characters with escape codes. Escape codes consist of a % sign followed by a hexadecimal representation of the character. For example, the letter A becomes code %41, where 41 is the hexadecimal form of the decimal number 65, which in turn is the ASCII representation of a capital A.

As the JavaScript language includes an unescape() function for decoding escape sequences, no special decryption algorithm is required. So, if you want the browser to output your escaped code, you could do something like:

document.write(unescape("%48%61%6C%6C%6F%20%57%65%6C%74%21"));

(Output: “Hello World!”)

To escape your own code you may use the this page.

Rot13 Method

Rot13 is a method of text obfuscation in which every character is replaced with the character that is 13 places away in the Latin alphabet. It is rumored that this method of encryption was invented by Julius Caesar to send coded messages to his generals.

The following script provides a very comprehensive JavaScript implementation of the Rot13 algorithm:

function rot13(input) {
  return input.replace(/[a-zA-Z]/g,
    function(ch) {
      return String.fromCharCode((ch <= "Z" ? 90 : 122) >=
        (ch = ch.charCodeAt(0) + 13) ? ch : ch - 26);
  });
}

Using the above rot13() function the following code outputs “Hello World!” to the browser window:

document.write(rot13("Uryyb Jbeyq!"));

To obfuscate your own code with Rot13 please visit this page.

Base64 Method

Base64 is a way of encoding arbitrary text into a sequence of printable ASCII characters. The 64 characters within the Base64 alphabet are A-Z, a-z, 0-9, + and /. More details on the functions and uses of Base64 can be found in the corresponding Wikipedia article.

A simple JavaScript function for Base64 decoding can be found below:

function decode64(input) {
  var base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef" +
    "ghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var ch1, ch2, ch3, enc1, enc2, enc3, enc4;
  var i = 0;
 
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  do {
    enc1 = base64.indexOf(input.charAt(i++));
    enc2 = base64.indexOf(input.charAt(i++));
    enc3 = base64.indexOf(input.charAt(i++));
    enc4 = base64.indexOf(input.charAt(i++));
 
    ch1 = (enc1 << 2) | (enc2 >> 4);
    ch2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    ch3 = ((enc3 & 3) << 6) | enc4;
 
    output = output + String.fromCharCode(ch1);
 
    if (enc3 != 64) output = output + String.fromCharCode(ch2);
    if (enc4 != 64) output = output + String.fromCharCode(ch3);
 
    ch1 = ch2 = ch3 = "";
    enc1 = enc2 = enc3 = enc4 = "";
 
  } while (i < input.length);
 
  return output;
}

The following line of code uses the decode64() function to write “Hello World!” to the browser:

document.write(decode64("SGVsbG8gV29ybGQh"));

A form for encoding your own code with Base64 can be found here.

Encrypting Web Pages with HTML Guard

A very easy and painless way to encrypt HTML documents is to use HTML Guard, our software solution for protecting web pages from code and content theft. HTML Guard allows you to choose the parts of your web pages you want to encrypt and lets you process hundreds or thousands of files at the touch of a button. Furthermore, the obfuscation and protection techniques used by HTML Guard are much more sophisticated than the ones presented here. For instance, each processed HTML page is encrypted with a different key and uses different variable names in the JavaScript code, which makes the encryption more difficult to break.


August 12th, 2009, by Andreas

Disabling the Context Menu in Firefox

Firefox offers an easy way to circumvent the anti-right click script that I presented to you in a previous article. All one has to do is go to the “Advanced JavaScript Settings” (Tools > Options > Content > Advanced) and deselect the “Disable or replace context menus” option.

Firefox - Disable or replace context menus

However, there is no need to panic. There is a simple solution to this problem. By stopping the propagation of the “oncontextmenu” event with the .stopPropagation() method, the context menu can be blocked even with “Disable or replace context menus” remaining unchecked:

function onContextMenu(e) {
  if (e && e.stopPropagation)
    e.stopPropagation();
 
document.oncontextmenu = onContextMenu;

When merging the above code into the original anti-right click script, we get the following:

<script language="JavaScript" type="text/javascript">
<!--
 
  // Setting "onlyOnImages" to "true" will disable right-clicking only for
  // images
  var onlyOnImages = false;
 
  // Detect the browser we have to handle with
  var isIE5 = document.all && document.getElementById;  // IE 5 or higher
  var isMoz = !isIE5 && document.getElementById;  // Mozilla/Firefox
 
  function cancelContextMenu(e) {
    // Here you can add additional code that is executed when the context menu
    // is blocked. For instance you can use the following code to display a
    // message to the user:
    //alert("Please respect our copyright. Thank you!");
 
    if (e && e.stopPropagation)
      e.stopPropagation();
 
    return false;
  }
 
  /* This function is fired every time a user clicks the right mouse button to
     open the browser's context menu. */
  function onContextMenu(e) {
    // Depending on the "onlyOnImages" variable the context menu is either
    // blocked for the complete page or only for <img> tags.
    if (!onlyOnImages
      || (isIE5 && event.srcElement.tagName == "IMG")
      || (IsMoz && e.target.tagName == "IMG")) {
      return cancelContextMenu(e);
    }
  }
 
  if (document.getElementById) {
    // Register event handler
    document.oncontextmenu = onContextMenu;
  }
 
-->
</script>

A sample page is available here.


July 17th, 2009, by Andreas

Ideas for Anti-Right Click Actions

Introduction

To follow up on my last article on how to use JavaScript to block right-clicks in the browser, I will now share some ideas on spicing up the script a bit. The goal is not to just silently disable the context menu, but also to give the user one of the following forms of feedback:

  • Display a message box window with a custom text
  • Display an inline message right under the cursor
  • Redirect the browser to another website
  • Bookmark a page
  • Send an email to a specified address

The presented solutions are more of a proof-of-concept than something I would actually recommend using. Please decide for yourself what to make of the code.

All code samples can be downloaded here as a ZIP file.

Display a message box window with a custom text

To show a message box every time a user right-clicks on your page, just add the following line of code to the original script’s “cancelContextMenu” function:

alert("Please respect our copyright. Thank you!");

A sample page is available here.

Display an inline message right under the cursor

A slicker and less intrusive way to present a message to a user is to display it as a div popup inside your page. Please click here to see what I mean.

Right Click Popup

The popup is displayed right under the mouse cursor’s current position and disappears after one second.

Redirect the browser to another website

Another possible reaction to a right click is to redirect the user’s browser to a different web page – for example, a page which explains what
‘copyright’ means. This can be accomplished with the following line of code:

location.href = "http://www.wipo.int/copyright/en/general/about_copyright.html";

Bookmark a page

When adding the following code to the original script, the user will be prompted to add your website to the Favorites list everytime he/she tries to open the context menu:

function bookmarkSite(url, title){
  if (isIE5)
    window.external.AddFavorite(url, title);
  else if (isMoz)
    window.sidebar.addPanel(title, url, "");
}
 
bookmarkSite("http://www.website.com/", "Website Title");

An example of the code can be found here.

Send an email to a specified address

Although not really advisable, you can also make the browser open the user’s email client every time a right-click is detected. To do so, just add this code to the original anti-right click script:

location.href = "mailto:test@test.com?subject=Subject goes here&body=Body goes here";

Please click here to see a sample page.


June 15th, 2009, by Andreas

Disable Right-Clicks on your Website

About Anti-Right-Click Protection

Disabling the browser’s context menu is a classic method to prevent the theft of web page content. With the help of JavaScript, it’s quite easy to block right-clicks by cancelling “oncontextmenu” events (see the code below). Although there are many ways to bypass this kind of protection, and although the solution doesn’t work in all browsers, implementing the solution is often better than doing nothing to prevent content theft.

The Script

To disable right-clicking on your web page, simply copy and paste the following code to the <head> (or <body>) section of your pages’ HTML code:

<script language="JavaScript" type="text/javascript">
<!--
 
  // Setting "onlyOnImages" to "true" will disable right-clicking only for
  // images
  var onlyOnImages = false;
 
  // Detect the browser
  var isIE5 = document.all && document.getElementById;  // IE 5 or higher
  var isMoz = !isIE5 && document.getElementById;  // Mozilla/Firefox
 
  function cancelContextMenu(e) {
    // Here you can add additional code that is executed when the context menu
    // is blocked. For instance, you can use the following code to display a
    // message to the user:
    // alert("Right-click disabled!");
 
    return false;
  }
 
  /* This function is fired every time a user clicks the right mouse button to
     open the browser's context menu. */
  function onContextMenu(e) {
    // Depending on the "onlyOnImages" variable the context menu is either
    // blocked for the complete page or only for <img> tags.
    if (!onlyOnImages
      || (isIE5 && event.srcElement.tagName == "IMG")
      || (IsMoz && e.target.tagName == "IMG")) {
      return cancelContextMenu(e);
    }
  }
 
  if (document.getElementById) {
    // Register event handler
    document.oncontextmenu = onContextMenu;
  }
 
-->
</script>

The script allows you to choose whether or not to disable right-clicks only on images (onlyOnImages = true) or for the complete page (onlyOnImages = true).

Script Demo

Click here to see a demo page that uses the “Anti-Right-Click” script listed above.

Right Click Protection with HTML Guard

By the way, a very easy way to add right-click protection to your web pages is to use HTML Guard, our software solution for preventing websites from being copied. HTML Guard not only allows you to disable the browser’s context menus but also provides protection features such as encrypting HTML source code, preventing text selection or blocking the print function. Please click here to download a fully functional demo version.


May 25th, 2009, by Andreas

Dynamic Image Watermarks with PHP

Introduction

An effective way to protect the images of a web page from being copied or linked from other websites is to visually mark them with a logo, a copyright notice, or any other identifying marker. In this article, I will explain how PHP can be used to quickly and dynamically watermark images on a web server without having to modify the original image files.

Watermark Sample

The following two images provide an example of what an image looks before and after watermarking it with the PHP script:

Original image:
Sample Image: Central Park

Watermarked image:
Watermarked Sample Image: Central Park

As you can see, the watermark is discreetly placed in the lower right corner without inhibiting the viewer from seeing the image.

Download and Installation

Please click here to download the watermarking script (including a sample page and the SVG sources for the watermark image).

To install the script, just upload the “watermark.php” file to your web server and change image tags in your HTML code from something like this:

<img src="sample1.jpg" />

to this:

<img src="watermark.php?image=sample1.jpg&watermark=watermark.png" />

Instead of linking an image directly, pass the image’s file name to the PHP script and additionally reference a watermark file. Supported image types are JPEG, PNG, and GIF. Image files can also be placed in subfolders relative to the folder of the script file:

<img src="watermark.php?image=folder/sample1.jpg&watermark=folder/watermark.png" />

The Code in Detail

First, the script opens both the original image and the watermark image using one of the imagecreatefrom(jpeg/gif/png) functions. Like many other functions used in the script, these functions are provided by the GD library that has been bundled with PHP since version 4.3.

function imagecreatefromfile($image_path) {
  // retrieve the type of the provided image file
  list($width, $height, $image_type) = getimagesize($image_path);
 
  // select the appropriate imagecreatefrom* function based on the determined
  // image type
  switch ($image_type)
  {
    case IMAGETYPE_GIF: return imagecreatefromgif($image_path); break;
    case IMAGETYPE_JPEG: return imagecreatefromjpeg($image_path); break;
    case IMAGETYPE_PNG: return imagecreatefrompng($image_path); break;
    default: return ''; break;
  }
}

Next, the intended position of the watermark in the output image is calculated (the watermark is placed in the lower right corner).

$watermark_pos_x = imagesx($image) - imagesx($watermark) - 8;
$watermark_pos_y = imagesy($image) - imagesy($watermark) - 10;

Now the source image and the watermark are being merged:

imagecopy($image, $watermark,  $watermark_pos_x, $watermark_pos_y, 0, 0,
  imagesx($watermark), imagesy($watermark));

The result is outputted to the browser as a JPEG image with the best quality (100):

header('Content-Type: image/jpeg');
imagejpeg($image, '', 100);

Finally, we free the memory allocated for the images:

imagedestroy($image);
imagedestroy($watermark);