Monday, 8 December 2014

Monday, 1 December 2014

Monday, 24 November 2014

Check if an array is multi-dimensional

if (count($array) == count($array, COUNT_RECURSIVE)) 
  echo 'array is not multidimensional';
  echo 'array is multidimensional';

Filtering data with PHP (Sanitizing data) and Validation

To filter arrays:

Get url query string parameters using Javascript only

Difference between array merge and array + array

Responsive Design: Screen resolution reference

Using rems

CSS Clear Fix

Parallax websites

Single Page Website

Install both OpenJDK and Oracle Java on Fedora

Use the "alternatives" app to switch between the two.

Assign event to Escape keypress

$(document).keyup(function(e) {
  if (e.keyCode == 27) { some_code_here }   // esc

CSS 3 resize property

Doesn't work on iframes in Firefox  33

Prevent link from doing default action

$( "a" ).click(function( event ) {

Make link open in parent of iframe

window.parent.location.href= "";

Saturday, 8 November 2014

Restrict web site access to specific IP addresses in Apache

order deny,allow
deny from all
allow from 111.222.333.444

Put the above code in the .htaccess in the root. You can add more "allow from" lines for more ip addresses.

Friday, 7 November 2014

Word wraping by word breaking

.break-word {
  word-wrap: break-word;

Friday, 31 October 2014

Linux: Change permissions recursively of only directories or only files

For directories:

find /path/to/folder -type d -exec chmod 755 {} \;

For files:

find /path/to/folder -type f -exec chmod 644 {} \;

Another way:

find /path/to/base/dir -type d -exec chmod 755 {} +
find /path/to/base/dir -type f -exec chmod 644 {} +

However, this seems to be the best solution, when you do not need to unset execute permissions on files:

chmod -R u+rwX,go+rX,go-w /path
The important thing to note here is that X acts differently to x - the man page says The execute/search bits if the file is a directory or any of the execute/search bits are set in the original (unmodified) mode. In other words, chmod u+X on a file won't set the execute bit; and g+X will only set it if it's already set for the user.

Tuesday, 28 October 2014

Apache Keep Alive Setting

This setting determines if a connection is kept alive after a single file is transferred between the server and the browser.

Default is off

Can be turned on depending on available RAM and traffic patterns:

Content Negotiation for Languages

How to configure etags

"remove the iNode portion of Etags. To do this in Apache add the following lines to your configuration file.
<Directory /usr/local/httpd/htdocs>
    FileETag MTime Size

Or choose "MTime  Size" for the Etags setting in WHM's Apache configuration

Monday, 13 October 2014

Jquery multiple selectors

jQuery( "selector1, selector2, selectorN" )

Note that the commas are within the selector.

Jquery iterating over arrays, objects, and array-like objects

var sum = 0;
var arr = [ 1, 2, 3, 4, 5 ];

$.each( arr, function( index, value ){
sum += value;

Javascript associative array

Javascript does not feature associative arrays. However, you can create something similar using object arrays.


arr={'key1': 'value1','key2':'value2'};

This array can be accessed with:

the_value = array['key2']

Values can be added or changes:


More info here:

You can iterate over the object array using Jquery:

$.each( arr, function( index, value ){
sum += value;

Monday, 18 August 2014

How To Set Up HTTP Authentication With Nginx

Nginx configuration file error

When restarting nginx after a configuration file change, if you get an error message that the configuration file has an error, you can get more info about the error with:

sudo nginx -t

Tuesday, 5 August 2014

To get a mysql formatted datetime using javascript:

 * You first need to create a formatting function to pad numbers to two digits…
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();

 * …and then create the method to output the date string as desired.
 * Some people hate using prototypes this way, but if you are going
 * to apply this to more than one Date object, having it as a prototype
 * makes sense.
Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());

I couldn't find a simpler jQuery solution to this.
If you want the time according to the user's time zone, remove the "UTC" in the second last line of the code.

Monday, 28 July 2014

Set Timezone

This will set the timezone for all the php functions in a page. Put this at the top of a page:


Solve 5 annoying moodle problems

XMPP chat

Prosody is a good XMPP chat server. It can be installed from the distro repository.

A guide:

There are many desktop clients for XMPP. There are a few web clients too: and

However, for these web clients to connect to the XMPP server, they need to use HTTP, so the XMPP server needs a plugin to communicate using xmpp over http, called BOSH:

The BOSH plugin for Prosody is:

Once the bosh-bind plugin is installed, a redirect should be setup in the web server (Apache or Nginx). This is because, converse.js must connect to the XMPP server (through bosh) at port 5280. However, browsers prevent authentication to this port because of same-origin policies (to prevent XSS). Therefore, the javascript can be made to authenticate to a particular directory which redirects the request to the correct url and port.

For integrating prosody with Wordpress, there is a plugin:

However, this plugin requires wordpress to store passwords as md5 hashes (using a plugin) instead of phpass. Md5 hashes are very insecure so wordpress-authenticator cannot be used.

There is another prosody plugin for wordpress authentication:
However, the code is alpha and development seems to have halted.

To integrate converse.js with a site that already uses authentication, one needs to use PHP prebinding:

Prosody: creating accounts:

Wednesday, 23 July 2014

Wednesday, 9 July 2014

Improving email delivery (preventing spam flagging)

Friday, 27 June 2014

Windows 7 Panning Desktop Applications

Friday, 20 June 2014

Page caching for Buddypress? Transients, memcached, vs others

Since Buddypress works on having users login, page caches software such W3 Total Cache, BP Super Cache, Nginx microcache, APC, Memcached, etc. won't work.

What would work is a partial page caching software. But there doesn't seem to be any such software now.

However, by using the wordpress transients API, one can manually code fragment or partial page caching.

Problems with transients:

Starting with Wordpress 3.7, transients are garbage collected, so the issues mentioned above may be fixed.

Enabling Opcache in PHP

Here are the commands that can be entered in php.ini for configuration of the opcache. There is also an explanation ofthe features.

Here are some Opcache GUI reporting tools:

Some configuration tips:

More detailed configuration tips:

Tuesday, 17 June 2014

Wordpress: Disable heartbeat

If wordpress is taking too much server resources, you can disable wordpress heartbeat. If you are using buddypress, disable "Activity auto-refresh" in Buddypress settings.

In the above page, you will find the code to disable heartbeat on all pages except post.php and post-new.php (here it is required for autosave while creating new posts and commenting).

To be added in functions.php

add_action( 'init', 'stop_heartbeat', 1 );

function stop_heartbeat() {
        global $pagenow;

        if ( $pagenow != 'post.php' && $pagenow != 'post-new.php' )

Nginx with CPanel

Cpxstack is a plugin to cPanel that completely replaces Apache with nginx (other plugins keeps apache and configure nginx as a reverse proxy).

To install cpxstack, you need Incron. For this you need to enable the EPEL repository (see previous article for this).

You also need to install php-devel. Cpanel prevents installing any php related packages through an "exclude" entry in yum.conf. Open yum.conf and remove "php*".

After upgrading to the latest stable PHP version, you should enable the Remi repository and the php55 remi repository. You can now install php-devel.

You can run the script as per instructions here:

For incron and php-devel you can alternatively directly run the script to see if it installs these packages automatically.

After the script has run, you should go to WHM, when you click on the cpxstack icon in the sidebar, it will ask you to change a setting in the Tweak Settings area.
You also need to go to cPanel and manually enable nginx for your site. Also in WHM change the default number of worker processes to a lower number (default is 15).

Nginx: Allow selected IP addresses only

  server {
    listen 80;

    location / {

      deny    all;
You can have multiple "allow" lines.

301 permanently moved redirect with PHP

The following php commands will do a 301 redirect when using PHP FPM 
header('Status: 301 Moved Permanently', true);
header('Location: ' . $url); // or header('Location: ' . $url, true, 301); 

Nginx configuration for Wordpress

For wordpress pretty permalinks to work, you need to add this to your nginx.conf file where the wordpress directory is /wordpress:

location /wordpress {
    index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$args;

Nginx configuration for Moodle

If the moodle directory is /moodle then put this in the configuration file nginx.conf or the appropriate file under the nginx.include.d folder:

server {
     rewrite ^/moodle/(.*\.php)(/)(.*)$ /moodle/$1?file=/$3 last;
In the same file, in the php section:
  location ~ \.php$ {
     fastcgi_split_path_info ^(.+\.php)(/.+)$;
Putting the same rewrite rule in the location /moodle section does not work.
If you are using the cpXstack plugin for cPanel, make sure you follow this:
For any domain that has nginX+PHP-FPM enabled, additional nginX configuration can be added by the root user at
/opt/pifpm/nginx.include.d/<DOMAINNAME>.autoinclude where DOMAINNAME is the domain .
Changes made any where else may not be preserved during server shut down. 

Monday, 16 June 2014

cPanel: Install php-devel

CPanel disables installation of php related packages using yum. To enable it:

nano /etc/yum.conf

Remove php* from the "exclude" line.

EPEL repositories for Fedora and Cent OS

Certain applications such as incron can't be found in the default repositories of Cent OS. To get this software, you need to enable the EPEL (Extra Packages for Enterprise Linux) repository:

Wednesday, 7 May 2014

Tuesday, 6 May 2014

Manually activating a user in Buddypress

To completely activate an imported user in Buddypress, you need to update two different tables:

In wp_usermeta add a date to the last_activity field.
In wp_bp_activity add a record for each user like so
INSERT INTO `wp_new`.`wp_bp_activity` (`id`, `user_id`, `component`, `type`, `action`, `content`, `primary_link`, `item_id`, `secondary_item_id`, `date_recorded`, `hide_sitewide`, `mptt_left`, `mptt_right`, `is_spam`) VALUES (NULL, '4', 'members', 'last_activity', '', '', '', '0', NULL, '2014-05-06 12:41:51', '0', '0', '0', '0');

Only after this will the person's name be available for private messaging.

Friday, 4 April 2014

Friday, 31 January 2014

How to make Wordpress root-relative

Add the following lines to your wp-config file (found in the root).

define('WP_HOME',"http://" . $_SERVER['HTTP_HOST']);
define('WP_SITEURL',"http://" . $_SERVER['HTTP_HOST']);

define( 'WP_CONTENT_DIR',  dirname( __FILE__ ) . '/wp-content' );
define( 'WP_CONTENT_URL',  'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' );
//  added by chetan Custom plugin directory
define( 'WP_PLUGIN_DIR',   dirname( __FILE__ ) . '/wp-content/plugins' );
define( 'WP_PLUGIN_URL',   'http://' . $_SERVER['HTTP_HOST'] . '/wp-content/plugins' );

Then prevent the functions get_site_url() and  get_home_url from accessing the wp_options database table to get the server domain or ip.

For this edit the link-template.php file:

Find the function get_home_url and comment every occurrence of this line like so:
//        $url = get_option( 'home' );

and add this:

    $url = "http://" . $_SERVER['HTTP_HOST'];

Do the same for get_site_url():

//        $url = get_option( 'siteurl' );

and add this:

    $url = "http://" . $_SERVER['HTTP_HOST'];

Now, to make sure any media files that are uploaded use root relative urls, install the following plugin:

Monday, 27 January 2014

VirtualBox Disable Time Sync

vboxmanage setextradata [VMname] "VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled" "1"

Turn it back on:
vboxmanage setextradata [VMname] "VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled" "0"