Tune .htaccess file for higher speed of a PHP application

Performance / application speed is a big factor for small portfolio websites to large, feature heavy web applications. Everyone wants a small portfolio website to load up in milliseconds, and no one wants to wait for the dashboard of a large SaaS application to takes minutes and minutes to load.

There are a lot of ways to tune a web application for faster speed. In this article, I will be focussing on two aspects that come up very frequently, setting content expiry header on static resources, and enabling gzip compression.

Content Expiry headers

Content expiry header is usually set on JS / CSS files and images on a web application, that is, files that are likely to change very little or not at all. For such files, if you set the content expiry header to, say, 1 month, then this instructs the browser to first check in its cache whether the file exists and is 1 month old or newer. If such file exists, the browser loads it from the cache.

Gzip compression

When Gzip compression is set on a server, then the server can send a compressed version of a requested web page. For example, a browser requests index.html file from the server. If Gzip compression is on, then the server can send the compressed gzip file to the browser, and then the browser uncompresses it at client side and displays the file. Have you thought about how much bandwidth can be saved this way?

Modifying htaccess file

To set content expiry and gzip compression on any PHP application, you have to modify the .htaccess file in the application root. I am providing a snippet below.

In this snippet I have set content expiry time frame to 1 month … feel free to modify this to day / year as you want.

######################################################################
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault “access plus 1 month”
# My favicon
ExpiresByType image/x-icon “access plus 1 year”
# Images
ExpiresByType image/gif “access plus 1 month”
ExpiresByType image/png “access plus 1 month”
ExpiresByType image/jpg “access plus 1 month”
ExpiresByType image/jpeg “access plus 1 month”
# CSS
ExpiresByType text/css “access plus 1 month”
# Javascript
ExpiresByType application/javascript “access plus 1 year”
</IfModule>
<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>
######################################################################
To test whether gzip compression is enabled on your live website or not, you can use this tool: http://www.gidnetwork.com/tools/gzip-test.php
References

Hack Proofing and Optimizing a WordPress powered website

Part 1: Prevent Spams and Hacking attacks

 

  1. Never use the username admin
  2. Use a strong password
  3. Use login-lockdown plugin to limit the number of failed logins to an administrator account.
  4. Download the plugin WP Security Scan
    1. After installation, view the WordPress firewall dashboard to see the list of scanned vulnerabilities. Each vulnerability shows the suggested mitigation policy underneath.
  1. Disable execution of any PHP script that might be injected into the server during a file upload or a theme installation / update.
    1. To do this create an .htaccess file in wp-content and wp-includes folder. Put the following lines there

<Files *.php>
deny from all
</Files>

  1. Protect wp-config.php from malicious use by adding this line to the .htaccess file in the root directory of wordpress.

<files wp-config.php>
order allow,deny
deny from all
</files>

 

  1. Download the plugin WordPress Firewall. Among other features, this plugin has options to mitigate SQL injection and stop directory browsing.

 

Part 2: Optimize WordPress … speed things up

  1. Download the plugins Super Cache and delete Super Cache – Clear all cache. The second plugin just provides a button on the dashboard for one click delete of all cache files.
  2. Use a third party image compressor (there are image compressors available online via cloud services) to compress your site images.
  3. Download Lazy Load plugin to lazy load images.
  4. Download Revisions Control plugin and configure the total number of revisions stored for a post or page. The number should be around 2/3.
  5. Download WP-Optimize and run the plugin to optimize and clean database tables.

 

References:

Using Javascript prototypal inheritance to add an Array search method

Javascript has no classes. Everything is an object in Javascript. Even functions. And objects can inherit other objects.

In this post, I will show how to use this unique inheritance feature of Javascript, aka prototypal inheritance, to customize built in Javascript objects like arrays. Particularly, I will show how to add a custom method to the Javascript Array object so that any array you use in your javascript app can use that method.

 

Whenever you create a new array in Javascript, it is an object inheriting from the Array object. Our target is to add a search method to the Array object. Wouldn’t it be convenient to be able to search arrays like

var result = myArray.find("Mango");

 

Well, wouldn’t it?

 

You bet it will be. But Javascript arrays do not come with a find method. Let us put it into the Array object so that all arrays can use it.

 

Array.prototype.find = function(key, value)
{
   var i;

   if(!key && !value)
   {
      return this;   //return the whole array since no parameters are passed
   }

   for(i = 0; i < this.length; i++)
   {
      if(!value)
      {
         //if only one parameter is passed, it will be found as key, value will be null

         value = key;

         if(this[i] == value) return this[i];
      }
      else
      {
         if(this[i][key] == value) return this[i];
      }
   }

   return null;
}

The code has been generalized to work for both complex objects in the target array, as well as simple arrays like an array of strings. If your array has complex objects then obviously you have to pass an extra parameter to the search function telling which property of an object will be searched for a matching value.

 

The use of the keyword prototype in the function declaration makes this function available to all sub-objects of Array, i.e. all arrays in your Javascript app. In the same way, you could add a variable to Array. And you can put any object before the prototype keyword. That is the beauty of Javascript’s prototypal inheritance; the hierarchy can start from anywhere.

 

If you have ever worked with ArrayLists or Vectors in C# or Java (these are expandable arrays, for those who do not know), you will have noticed that ArrayList or Vector class comes in with lots and lots of helper methods like toString(), find() for manipulating the arrays. Javascript does not give you so many helper methods built-in. But using prototypal inheritance, you can very easilly add helper methods like these and make your arrays more fun to use.

Syntax highlighting for Drupal module files in Notepad++

Notepad++ does not recognize Drupal module code files (.module) as php source code files, so php syntax highlighting is absent for these files. In this post I will show you how to configure Notepad++ to recognize .module files as php source code files.

Open Notepad++ with root / administrator privileges. This is because the configuration changes will involve indirectly editing Notepad++’s core system files, which require root privileges to edit.

Go to Settings -> Style Configurator.

configuration

From the top portion, of the dialog box, select the theme for which you want to apply your style.

Select php from the language selection pane.

In the lower part of the dialog box is a list of the extensions that this theme recognizes as php source code files. Go ahead and add module as another extension. Save. If any module file is already open in Notepad++, close and reopen it.

Happy coding!

 

Remove recent content listings from Drupal front page

By default, Drupal lists recent contents on the front page. The list is a simple top down paginated list.

recent contents

Often this is not a desirable situation. Except blogs, I have never seen a single Drupal site that shows recent content listings like this. Now Drupal does not even expose a view for this, otherwise you could have just edited that view and changed the content listing style to a grid or table, something more suited to a front page. Some sites might not want the recent content lists in any form at all.

 

How to remove this thing?

blocks

The block ‘Main Page Content’ is the one responsible for rendering the central content for a particular page. For example, if you go to <site hostname>/node/23 the content of node 23 will be rendered in this block. If you go to user/5 the user profile for the user with ID 5 will be rendered here. By default, the URL of a Drupal site’s front page is <site hostname>/node, which renders this undesirable recent content listings.

Wait a minute. I could just configure the ‘Main Page Content’ block and show it on all pages except the front page!

configure block

So simple. So easy. Problem solved.

Apparantly. Just refresh your home page and you will still see the recent content listings.

Hmmm ….. Drupal is overriding this configuration.

 

So let us disable this listing at the much lower level, at a level where Drupal would not override it.

We are going to create a simple custom module and use hook_menu_alter to disable this listing.

For Drupal 6 and 7, custom modules are places in the sites/all/modules directory. We are going to call our module ‘Empty Front Page’. Create a directory called empty_front_page in sites/all/modules. Inside this directory, create two files, empty_front_page.info, empty_front_page.module.

 

In empty_front_page.info, put in the following code

 

name = Empty Front Page
description = Do not show anything on the front page.
package = Custom Modules
core = 7.x

 

In empty_front_page.module, put in the following code

 

 

function empty_front_page_menu_alter(&$items)
{
$items[‘node’][‘page callback’] = “new_callback”;
}

function new_callback()
{
return “”;
}

 

Include a starting php brace at the top of your code, but omit the closing php brace.

This is the way you write a hook. The name of our hook is menu_alter, and our module is empty_front_page. Therefore the function implementing the hook will be called empty_front_page_menu_alter.

Drupal’s menu items are stored as a list of paths in an associative array. The path names are the array keys and an array of properties acts as the value for a particular key. For our problem, we are interested in the path /node, or in other words, $items[‘node’]. The property ‘page callback’ defines the callback function for that path. We are setting a new callback in our code, and in our callback function, we are just returning an empty string. So when /node is now called, instead of recent content listings, just an empty string is returned.

Now go ahead and enable the module. Then clear the cache from <site hostname>/admin/config/development/performance. This is required because Drupal caches menu items in the database to avoid looking up the hook_menu implementations every time.

 

Refresh your home page.

Voila!

 

Another way of solving this problem is to use a different page as your home page from <site hostname>/admin/config/system. However, I am not a fan of this method, since you have to create another page and put all your front page blocks into it. Furthermore, using  a module for this is a great starting point for developers who expect to use a lot of custom code in their Drupal site, since you get the feel of creating a custom module straight away.