Welcome to my BLOG!

I'm Iyngaran Iyathurai is a Project Manager cum Software engineer for MONARA PLC, PHP and Zend Framework expert based in Colombo, Sri Lanka. I studied Software Engineer at the University of Middlesex, graduated with a BSc in 2009. A couple of year ago I started my first software project; Multimedia Streaming Server. That was the starting point of a new era in my life as a software engineer. Currently I'm working in Monara PLC offering platform-independent software solutions via the PHP Zend-framework.

This is my personal blog. It is all about my activities, thoughts, inspiration, ideas, and everything that happened around me. Thank you so much for visiting my blog. I hope you guys will find something useful here for all your needs.

How to start a shell script with linux startup – ubuntu

Got a shell script that you want automatically run at bootup on Ubuntu Server Edition? Here’s how:

Create a script in the "/etc/init.d/" directory.

Make the script executable

    $ sudo chmod +x /etc/init.d/myscript.sh

Make the script start at bootup

    $ sudo update-rc.d myscript.sh defaults

Note: the option "defaults" puts a link to start your script in runlevels 2, 3, 4 and 5, and puts a link to stop in runlevels 0, 1 and 6.

Automatically or Manually Backup MySQL Databases

MySQL is one of the most popular open source database management system for the development of interactive Websites. Its is one of the basic components of established website development platforms such as LAMP (Linux-Apache-MySQL-PHP) due to its proven reliability and speed of performance.

If your site stores its sensitive data in a MySQL database, you will most definitely want to backup that information so that it can be restored in case of any disaster (we all have been there).

There are several ways to backup MySQL data. In this article we’ll learn how to achieve an automatic backup solution to make the process easier. Starting with the mysqldump utility that comes with MySQL, we will review several examples using mysqldump, including the backup of your database to a file, another server, and even a compressed gzip file and send confirmation email to your email address.

This is a simple backup solution for people who run their own web server and MySQL database server on a dedicated or VPS server. Since, I manage couple of boxes, here is my own automated solution.

Install lftp

lftp is a file transfer program that allows sophisticated ftp, http and other connections to other hosts. If site is specified then lftp will connect to that site otherwise a connection has to be established with the open command. To install lftp, enter:

#sudo apt-get install lftp

It is time to write a shell script that will automate entire procedure:

Shell script to backup MySQL database server

Following is the shell script. It will dump all database to /backup/mysql and later it will upload to FTP server and also it will send a confirmation email to the system admin. You need to setup correct server details, username,password and email address before using the script:

#!/bin/bash

# @author 		: Iyngaran Iyathurai

# 			  Software eng - BCAS R & D

# 			  E-Mail - Iyngaran55@yahoo.com, Iyngaran@bcas.lk

#                                    Skype - iyngaran55

#### Script Status File ##############

SCRIPT_STSTUS_FILE="/tmp/mysql_backup_on.txt"

SCRIPT_LOG_FILE="/tmp/mysql_backup_log.txt"

### MySQL Server Login Info ###

MUSER="your-mysql-server-username"

MPASS="your-mysql-server-password"

MHOST="your-mysql-server-hostname-or-ip-address"

MYSQL="$(which mysql)"

MYSQLDUMP="$(which mysqldump)"

# Make sure that, you have created the following folder - /backup/mysql
BAK="/backup/mysql"

GZIP="$(which gzip)"

### FTP SERVER Login info ###

FTPU="your-ftp-server-username"

FTPP="your-ftp-server-password"

FTPS="your-ftp-server-hostname-or-ip-address"

NOW=$(date +"%d-%m-%Y")

FILE=$SCRIPT_STSTUS_FILE

if [ -f $FILE ];

then

   echo "File $FILE exists"

else

echo "Script started" > /tmp/mysql_backup_on.txt

echo " $NOW Script started to backup the database " > $SCRIPT_LOG_FILE

[ ! -d $BAK ] && mkdir -p $BAK || /bin/rm -f $BAK/*

echo "# Logging to MYSQL Server..."

DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"

for db in $DBS

do

 FILE=$BAK/$db.$NOW-$(date +"%T").gz

 echo "# Starting to dump the database : " $db

 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE

 echo "# Backup completed " $db

done

echo "# All the databases are dumped successfully."

echo "# Logging to the FTP server...."

lftp -u $FTPU,$FTPP -e "mkdir /home/httpdocs/mysql/$NOW;cd /home/httpdocs/mysql/$NOW; mput /backup/mysql/*; quit" $FTPS

echo "# Backup files are transferred to the FTP server successfully."

rm -rf /tmp/mysql_backup_on.txt

#--------------- SENDING EMAIL ---------------------

SUBJECT="***** MIP: Database has been successfully backed up *****"

# Who to send the email to

EMAIL="iyngaran@bcas.lk"

# A file to hold the body of the message which

#is later redirected into mail

EMAILMESSAGE="mysql_backup.txt"

#Echo the body of the message into the file. The first line is

#added with > subsequent lines needs to be added with >>

echo "Sending email to the admin" > $EMAILMESSAGE

#Send an email using /bin/mail

mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE echo " $NOW Database backup has been succfully completed and confirmation email sent to the admin " > $SCRIPT_LOG_FILE

#--------------------------------------------------

fi

Save script as /home/your-name/mysql.backup.sh file. Setup executable permission:

$ chmod +x /home/your-name/mysql.backup.sh

Note : Make sure you have created this folder /backup/mysql (must have permission) in your local server, where the mysql server is running. And also make sure you have created this folder /home/httpdocs/mysql in your FTP server.

To run this script (backup MySQL) , enter:

sh /home/your-name/mysql.backup.sh

Run MySQL backup script as cron job

To automate procedure setup a cron job. For example run backup everyday at midnight (i.e once a day), enter:

$ crontab -e

Append following cron job:

00 00 * * * ssh /home/your-name/mysql.backup.sh

I hope you found these tips helpful. Be sure to drop a comment if you have any more ideas.

How to enable PHP error logging via .htaccess

Tracking PHP errors is a must when troubleshooting unexpected issues, related to plugins, themes. But you don’t want to have them visible on your site, especially not your customers. Here is a tutorial how to log all PHP errors behind the scenes to a private file.

Tracking your site’s PHP errors is an excellent way to manage and troubleshoot unexpected issues related to plugins and themes. Even better, monitoring PHP errors behind the scenes via private log is far better than trying to catch them as they appear at random visits.

Hide PHP errors from visitors

By default, the PHP display_errors setting is set on. You can read more about display_errors at PHP: Error Handling and Logging Functions. There are few important things that you should know about the error messages that is sent to the browser by display_errors.

Usually these error messages contains sensitive information about the web application environment that you are running and could lead to unwanted security threat. It is even stated in the manual that it is not recommended to enable this feature on a production site.

To disable or switch it off (assuming that you’re on a shared hosting which have limited super power), simply add the following lines to your .htaccess file.

;# hide php errors
;php_flag display_startup_errors off
;php_flag display_errors off
;php_flag html_errors off

With that in place, PHP errors will no longer be displayed publicly on your site. This eliminates a potential security risk, and keeps those ugly, unintelligible PHP errors from breaking your site layout and disorienting your visitors. No editing required for this code.

Enable private PHP error logging

Now that we have hidden PHP errors from public view, let's enable the logging of PHP errors so that we can privately keep track of them. This is done by including the following .htaccess directives to your domain's configuration file (httpd conf)  or to your site's root (or other target directory)  .htaccess file:

;# enable PHP error logging
;php_flag  log_errors on
;php_value error_log  /home/public_html/iyngaran.info/PHP_errors.log

For this to work, you will need to edit the path in the last line to reflect the actual location of your PHP_errors.log file. Of course, you will need to create this file and subsequently set the file permissions to 755 or, if necessary, 777. Finally, you need to secure the log file itself by adding this final line of code to your htaccess file:

;# prevent access to PHP error log
;
; Order allow,deny
; Deny from all
; Satisfy All
;

Then, after everything is in place, check that everything is working by triggering a few PHP errors. You may also want to verify protection of your error log by trying to access it via a browser.

Reference Links

http://www.vansteen.org/wordpress/?p=115
http://baguzajja.info/advanced-php-error-handling-via-htaccess
http://www.websyssupport.com/?page_id=228
http://perishablepress.com/press/2007/12/17/how-to-enable-php-error-logging-via-htaccess/

How to change wordpress theme directly from database?

I had some error in my new wp theme (hybrid-news). When I enabled the new theme, I got this error - Fatal error: Call to undefined function hybrid_get_prefix() in /media/Webroot/projects/wp/wp-content/themes/hybrid-news/functions.php on line 46 . I was unable to access my wordpress blog both from frontend and backend (admin panel).

In this case, either I need to change/fix my theme's code. So I decided to change the theme.

To do that, I open the phpMyAdmin, and selected the wp database. And then I searched the word "hybrid-news" in all the tables. When I do this search, I was able to see the word "hybrid-news" in the "wp_options" table. The option_id = 46, option_name = "stylesheet" and option_value = "hybrid-news". So I updated the "option_value" to "default"

UPDATE wp_options SET option_value = 'default' WHERE option_name = 'stylesheet';

The result - 1 row(s) affected. I was able to get my site (front-end and admin panel) back with default theam.

I hope you found these tips helpful. Be sure to drop a comment if you have any more ideas.

A basic introduction to jQuery

What is jQuery?

jQuery is a great and cross-browser JavaScript library designed to simplify the HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.  It is the most popular JavaScript library in use today. jQuery was released in January 2006 at BarCamp NYC by John Resig.

Why jQuery?

The jQuery library is providing many easy to use functions and methods to make rich applications. These functions are very easy to learn and even a designer can learn it fast. Due to these features jQuery is very popular and in high demand among the developers. You can use jQuery in all the web based applications irrespective of the technology.

Key features of jQuery

jQuery contains the following features:

  1. DOM element selections functions.
  2. jQuery Selectors allow you to select DOM elements so that you can apply functionality to them with jQuery’s operational methods.

  3. Events.
  4. Much of what is done in JavaScript code from DOM manipulation to AJAX calls are handled asynchronously and unfortunately the DOM implementations for event handling vary considerably between browsers. jQuery provides an easy mechanism for binding and unbinding events and providing a normalized event model for all supported browsers that makes it very easy to handle events and hook result handlers.

  5. DOM traversal and modification.
  6. CSS manipulation.
  7. Effects and animations.
  8. Ajax.
  9. Extensibility through plug-ins.
  10. Utilities - such as browser version and the each function.
  11. Cross-browser support.
  12. Can combine with Prototype.

If you already know some javascript, taking of with jQuery will be really easy.

How to use Jquery in a web page ?

It is very simple. Let's start developing the “Hello World” application in jQuery. For this example we are going to create our first jQuery application called "Hello World jQuery". This example will simply display a message box "Hello World - jQuery", when a user visit to the page.

Step – 1

We need to have a html page. So here, I am going to create a basic html page.

<html>
<head>
<title>jQuery Hello World Example</title>
</head>
<body>
</body>
</html>

Setp – 2

The next and most important thing is “Including the library”.

The jQuery library is a single JavaScript file, containing all of its common DOM, event, effects, and Ajax functions. It can be included within a web page by linking to a local copy, or to one of the many copies available from public servers.  If you like to have local copy, You need to download it from http://docs.jquery.com/Downloading_jQuery.

I have downloaded the library. So I can link to the local copy. In this case, I am going to add the following line under the <head></head> section of the html document.

<script type="text/javascript" src=" jquery-1.6.1.js"></script>

If you are using the above tag as it is , you need to save the " jquery-1.6.1.js" in the same folder in which you saved your html page. You can also save it in another folder but in that case you need to provide the relative path.

Step – 3

Display the message “Hello World - jQuery”

All your jQuery code should be inside this

$(document).ready(function() {
//insert your jQuery code here.
});

The jQuery document ready function tells your browser to execute the code within it after the document finished loading. It doesn't take into account images. This is of great advantage because the code that is usually used is window.onload(), but this takes place only after all the images are loaded, so this make your page execution smoother.

For using jQuery script , we need to write it inside <script> tag. The below code checks whether the page loading is finished (DOM elements are ready or fully loaded) and if page loading is finished then it executes the code in the block and display the message “Hello World - jQuery”.

We can add the following lines of code in <head></head>  section or <body></body> section of the html document.

<script type="text/javascript">
$(document).ready(function(){
alert("Hello World - jQuery");
});
</script>

The following is the complete code for this example.

<html>
<head>
<title>jQuery Hello World Example</title>
<script type="text/javascript" src=" jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert("Hello World - jQuery");
});
</script>
</head>
<body>
</body>
</html>

Here is the online demo –  http://blog.iyngaran.info/examples/jQuery/hello-world-example.html

Conclusion

So as you can see, jQuery is a really powerful library that once you know how to use will take your developing to a higher level. You can learn jQuery in a day and master it within 2-3 days. There are so many features available with jQuery and you may spend months to explore these features.

Speed Up Your Site – Web Site Optimization

The load time of websites is one of the most important factors affecting its usability; most Internet users will just skip a site altogether if it fails to load within a couple of seconds. Slow-loading websites are one of the main reasons that visitors may leave a site. As a result, it is important to ensure that your website is fast and regularly make improvements as content changes. The content should make up the majority of your pages. But as the majority of your pages, it is what you should focus on optimizing first. Content includes both text and images.

Below you will find the summary of the “Speed Up Your Site” series. Those are simple yet effective ways to make sure that your website is running fast. By following this article you will realize that a fast website will increase the user experience very much and this brings you returning visitors and, why not, happy visitors. You will also learn how to optimize your website for speed with almost no cost at all. There are almost 50 tricks to read, understand, analyze and implement into your website. Tricks that are designed to make your pages load faster under the same server, with the same investment in most cases.

Optimize the HTML

The HTML is what makes your page display in the browser, but you need to make sure that it is optimized as well.

Layout your pages with CSS, not tables

CSS downloads faster than tables because:

  • Browsers read through tables twice before displaying their contents, once to work out their structure and once to determine their content.
  • Tables appear on the screen all in one go - no part of the table will appear until the entire table is downloaded and rendered.
  • Tables encourage the use of spacer images to aid with positioning.
  • CSS generally requires less code than cumbersome tables.
  • All code to do with the layout can be placed in an external CSS document, which will be called up just once and then cached (stored) on the user's computer; table layout, stored in each HTML document, must be loaded up each time a new page downloads.
  • With CSS you can control the order items download on to the screen - make the content appear before slow-loading images and your site users will definitely appreciate it.

Don't use images to display text

There's no need to use images to display text as so much can be accomplished through CSS. Have a look at this code:

a:link.button, a:visited.button, a:active.button  {
color:#fff;
background:#747170;
font-size:1.2em;
font-weight:bold;
text-decoration:none;
padding:0.2em;
border:4px solid;
border-color:#000000
}

a:hover.button {
color:#fff;
background:#382D2C;
font-size:1.2em;
font-weight:bold;
text-decoration:none;
padding:0.2em;
border:4px solid;
border-color:#000000
}

This will give you a really simple button that appears to be pushed down when you mouseover it - See it in action.

Use contextual selectors

This is inefficient:

<p>This is a sentence</p>
<p>This is another sentence</p>
<p>This is yet another sentence</p>
<p>This is one more sentence</p>

.paragraph-text
{
color: #03c;
font-size: 2em
}

Instead of assigning a value to each individual paragraph, we can nest them within a <div> tag and assign a value to this tag:

<div class="paragraph-text">
<p>This is a sentence</p>
<p>This is another sentence</p>
<p>This is yet another sentence</p>
<p>This is one more sentence</p>
</div>

.paragraph-text p
{
color: #03c;
font-size:2em
}

This second CSS example basically says that every paragraph within should be assigned a colour value of #03c and a font size of 2em.

At first glance this doesn't look too important, but if you can apply this properly throughout your document you can easily knock off 20% of the file size.

Use shorthand CSS properties

You can use the following shorthand properties for the margin CSS command.

Use:

margin: 2px 1px 3px 4px (top, right, bottom, left)

...instead of

margin-top: 2px;
margin-right: 1px;
margin-bottom: 3px;
margin-left: 4px

Use:

margin: 5em 1em 3em (top, right and left, bottom)

...instead of

margin-top: 5em;
margin-right: 1em;
margin-bottom: 3em;
margin-left: 1em

Use:

margin: 5% 1% (top and bottom, right and left)

...instead of

margin-top: 5%;
margin-right: 1%;
margin-bottom: 5%;
margin-left: 1%

Use:

margin: 0 (top, bottom, right and left)

...instead of

margin-top: 0;
margin-right: 0;
margin-bottom: 0;
margin-left: 0

These rules can be applied to margin, border and padding.

Minimise white space, line returns and comment tags

Whitespace is the spaces between your coding, removing the unneeded tabs and spaces can help a lot! Doing this will take a lot of extra bytes off the total size of your page and will speed up load time quite a bit. (Careful using automatic squishers, I find they often squish too much and makes it rather hard to edit later.)

Every single letter or space in your HTML code takes up one byte. It doesn't sound like much but it all adds up. We've found that by working through your page source and eliminating unnecessary white space and comments, you can shave off up to, or even over (if your HTML is really inefficient) 10% of its file size.

Put CSS and JavaScript into external documents

To place CSS in an external document use:

<link type="text/css" rel="stylesheet" href="filename.css" />

To place JavaScript in an external document use:

<script language="JavaScript" src="filename.js" type="text/javascript"></script>

Any external file is called up just once and then cached (stored) on the user's computer. Instead of repeating JavaScript or CSS over and over again in HTML files, just write it out once in an external document.

That way the browser already has it in it's cache and won't have to read it each time another page loads. This one saves a ton of load time, specially for larger scripts!

Use / at the end of directory links

Don't do this:

<a href="http://www.URL.com/directoryname">

Do this instead:

<a href="http://www.URL.com/directoryname/">

Why? If there's no slash at the end of the URL the server doesn't know if the link is pointing to a file or to a directory. By including the slash the server instantly knows that the URL is pointing to a directory and doesn't need to spend any time trying to work it out.

Link to Pages and Images with Relative Paths

Absolute paths, including the host name, add additional characters that aren't required for links to images and pages on the same web server. An example of an absolute call up is: <a href="http://www.URL.com/filename.htm">. Much better would be <a href="filename.htm">. But what if some files are in different folders to other ones? Use these shorthand properties:

  • <a href="/"> - Calls up http://www.URL.com
  • <a href="/filename.html"> - Calls up http://www.URL.com/filename.html
  • <a href="/directory/filename.html"> - Calls up http://www.URL.com/directory/filename.html
  • <a href="./"> - Calls up index.html within that directory
  • <a href="../"> - Calls up index.html one directory above
  • <a href="../filename.html"> - Calls up filename.html one directory above
  • <a href="../../"> - Calls up index.html two directories above.

Remove unnecessary META tags and META content

Most META tags are pretty much unnecessary and don't achieve very much.  The most important tags for search engine optimisation are the keywords and description tags, although due to mass abuse they've lost a lot of importance in recent times. When using these META tags try to keep the content for each under 200 characters - anything more increases the size of your pages. Lengthy META tags are not good for search engines anyway because they dilute your keywords.

Speed Up Your CSS

CSS is another place where your pages can be slowed down. Large CSS files with styles that are never used are a waste of bandwidth.

When developing large sites, stylesheets can get fairly messy and hard to keep track of. If you don’t stay organized, you can end up making them larger than they really need to be and doing more work than you should have to. Here’s just a few ways to can help avoid that.

Reusing Semantic Class Names

While in most cases semantic class names really don’t help achieve much, there are a few in which they can be quite helpful. One of these is when describing element states, such as .selected.

Oftentimes, people only use classes when there are multiple elements on a page that are to share the same styles–this isn’t the only way to use them, however. Say we have a tabbed horizontal navigation on the top of our page:

<ul id="tabs">
<li><a href="#">tab 1</a></li>
<li><a href="#">tab 2</a></li>
<li><a href="#" class="selected">current tab 3</a></li>
<li><a href="#">tab 4</a></li>
</ul>

We’re going to want to give the .selected link some extra styles. But now say we also have a form somewhere on the page and are using JavaScript to add some styles when a radio button has been selected. When the button is selected, our code would look something like this:

<form action="#" method="post">
<input type="radio" name="button" value="value">
<input type="radio" class="selected" name="button" value="value2">
<input type="radio" name="button" value="value3">
<input type="radio" name="button" value="value4">
</form>

Using selectors, we can give each of these different styles:

li .selected {
/* styles go here */
}

form .selected {
/* styles go here */
}

This makes our CSS easy to read and our classes easy to keep track of. When you have tons of elements with different styles, keeping track of all the IDs and classes can become difficult–this shortens that list and lets us use easy-to-remember names.

Name your <body>

When working with multiple pages, most of the time you’ll be re-using many of your styles but will need slight variations. Having the same code repeated several times in your stylesheet with minor variations wastes space, is hard to keep track of, and just isn’t necessary. For an example, let’s take our previous example and say that our navigation has these styles:

ul#tabs li {
float: left;
padding: 5px;
color: #000;
background: #fff;
font: 1em tahoma;
}

Now what if on all our subpages we want the same thing, but with less padding? We could create a new list, copy/paste all these styles, then modify the padding. But that’d be pointless. Instead, we add a class to the body on our subpages (say, subpage) and just add this into our stylesheet:

.subpage ul#tabs li {
padding: 2px;
}

And that’s it.

Keeping IE Happy

One of the biggest time consumers in CSS development is, of course, IE debugging. With IE7 now on the loose, this can get even more complicated. However, using one IE-only stylesheet that can target both IE 6 and 7 as well as each individually, this can be made much simpler.

To do this, first we set up our conditional comment with included stylesheet:

<!--[if IE]>
<link rel="stylesheet" href="ie.css" type="text/css" media="screen" />
< ![endif]-->

Within this stylesheet, we can then add any styling fixes that are needed for all versions of IE (just make sure that your styles will take priority over the ones in your main stylesheet–I usually add “html body” at the beginning of each selector). For fixes that don’t need to be done on IE7, we simply use the * html hack. For IE7-only fixes, add html > body before the selectors.

By doing this, we can target specific version of IE within one stylesheet and still keep it separate from our main stylesheet.

Don't Use CSS Expressions

Internet Explorer versions 5 through 7 supported using JavaScript to modify the CSS programatically but these expressions are evaluated thousands of times as the page loads, is rendered, even as the scrollbar moves - all of which slows the page down

Don't Use CSS Filters

Internet Explorer provides a filter AlphaImageLoader to fix a problem with semi-transparent PNGs in versions lower than 7, but this filter blocks rendering and freezes the browser while the image is downloaded.

Speed Up Your JavaScript

Javascript is becoming increasingly popular on websites, from loading dynamic data via AJAX to adding special effects to your page. Unfortunately, these features come at a price: you must often rely on heavy Javascript libraries that can add dozens or even hundreds of kilobytes to your page. Users hate waiting, so here are a few techniques you can use to trim down your sites.

JavaScript and Ajax can make pages slower, especially if you have them load right away. Most scripts are not used until the entire page is loaded, and if they load first that makes the page appear slower.

Compress Your Javascript

First, you can try to make the javascript file smaller itself. There are lots of utilities to “crunch” your files by removing whitespace and comments.

  • Run JSLint (online (http://www.jslint.com/) or downloadable version) to analyze your code and make sure it is well-formatted.
  • Use Rhino to compress your javascript. There are some online packers (http://dean.edwards.name/packer/), but Rhino actually analyzes your source code so it has a low chance of changing it as it compresses, and it is scriptable.

This compresses myfile.js and spits it out into myfile.js.packed. Rhino will remove spaces, comments and shorten variable names where appropriate. The “2>&1″ part means “redirect standard error to the same location as the output”, so you’ll see any error messages inside the packed file itself (cool, eh? Learn more here.).

Optimize Javascript Placement

Place your javascript at the end of your HTML file if possible. Notice how Google analytics and other stat tracking software wants to be right before the closing </body> tag.

This allows the majority of page content (like images, tables, text) to be loaded and rendered first. The user sees content loading, so the page looks responsive. At this point, the heavy javascripts can begin loading near the end.

I used to have all my javascript crammed into the <head> section, but this was unnecessary. Only core files that are absolutely needed in the beginning of the page load should be there. The rest, like cool menu effects, transitions, etc. can be loaded later. You want the page to appear responsive (i.e., something is loading) up front.

Load Javascript On-Demand

An AJAX pattern (http://ajaxpatterns.org/On-Demand_Javascript) is to load javascript dynamically, or when the user runs a feature that requires your script. You can load an arbitrary javascript file from any domain using the following import function (http://www.activewidgets.com/javascript.forum.6114.43/dynamic-load-javascript-from-javascript.html):

function $import(src){
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src',src);
scriptElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

// import with a random query parameter to avoid caching
function $importNoCache(src){
var ms = new Date().getTime().toString();
var seed = "?" + ms;
$import(src + seed);
}

The function $import('http://example.com/myfile.js') will add an element to the head of your document, just like including the file directly. The $importNoCache version adds a timestamp to the request to force your browser to get a new copy.

To test whether a file has fully loaded, you can do something like

if (myfunction){
// loaded
}
else{ // not loaded yet
$import('http://www.example.com/myfile.js');
}

There is an AJAX version as well (http://ajaxpatterns.org/On-Demand_Javascript#XMLHttpRequest-Based_On-Demand_Javascript) but I prefer this one because it is simpler and works for files in any domain.

Delay Your Javascript

Rather than loading your javascript on-demand (which can cause a noticeable gap), load your script in the background, after a delay. Use something like

var delay = 5;
setTimeout("loadExtraFiles();", delay * 1000);

This will call loadExtraFiles() after 5 seconds, which should load the files you need (using $import). You can even have a function at the end of these imported files that does whatever initialization is needed (or calls an existing function to do the initialization).

The benefit of this is that you still get a fast initial page load, and users don’t have a pause when they want to use advanced features.

In the case of InstaCalc (http://instacalc.com/), there are heavy charting libraries that aren’t used that often. I’m currently testing a method to delay chart loading by a few seconds while the core functionality remains available from the beginning.

You may need to refactor your code to deal with delayed loading of components. Some ideas:

  • Use SetTimeout to poll the loading status periodically (check for the existence of functions/variables defined in the included script).
  • Call a function at the end of your included script to tell the main program it has been loaded.

Cache Your Files

Another approach is to explicitly set the browser’s cache expiration. In order to do this, you’ll need access to PHP or Apache’s .htaccess so you can send back certain cache headers.

Rename myfile.js to myfile.js.php and add the following lines to the top:

<?php
header("Content-type: text/javascript; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
?>

In this case, the cache will expire in (60 * 60 * 24 * 3) seconds or 3 days. Be careful with using this for your own files, especially if they are under development. I’d suggest caching library files that you won’t change often.

If you accidentally cache something for too long, you can use the $importNoCache trick to add a datestamp like “myfile.js?123456″ to your request (which is ignored). Because the filename is different, the browser will request a new version.

Setting the browser cache doesn’t speed up the initial download, but can help if your site references the same files on multiple pages, or for repeat visitors.

Cookies Affect Speed

Cookies are a powerful tool for web designers and developers, but they can also cause your pages to slow down. These tips can help you speed up your cookies.

  • Keep cookies small - the larger the cookies are, the more data that must be passed .
  • Eliminate unnecessary cookies - the fewer cookies you set the less that have to be downloaded with your page.
  • Set your cookies at the appropriate domain level - so that only the domains and sub-domains that need cookies, and the rest don't.
  • Serve static content from a cookieless domain - static content like images can't use cookies anyway, so serving cookies along with them just adds more requests that aren't used.

Speed up the loading of HTML files with images


Don't Go Overboard On Images

While images can greatly enhance the look of a site they can really slow it down if there are too many. Try to decide if all your images are really needed (quite a few nice effects can be done with css, so sometimes images are unneeded.)

Height And Width Tags

Here's a good old HTML trick that will help most WWW browsers display HTML pages with images faster. Simply add the WIDTH and HEIGHT tags to your IMG tags. For example, if your original image (IMG) tags looks like:

<IMG SRC="MyLogo.gif">

and the width and height of MyLogo.gif is 32 by 50, change the above tag to:

<IMG SRC="MyLogo.gif" WIDTH=32 HEIGHT=50>

So why would adding WIDTH and HEIGHT tags improve the speed? Well, if you don't specify the size of the image, the browser would have to spend time to actually load the image to find out the size of it and only then can calculate how to layout rest of the elements on the page. As you can see, if you have many images on your page, taking time to load each image before calculating the final layout of the page would take longer.

GIF vs JPG vs PNG

Personally on new sites I design I tend to go for optimized pngs. They have lossless compression (jpgs are lossy) and can be used without worry (gifs have the potential to have copyright issues) and load fast when optimized. Jpgs however are usually better for photos and sometimes highly detailed images. The best idea is really to try the image you want in different formats and compare file size to quality.

Here's a bit of fast info... If you don't need sharp resolution, choose PNGs or GIFs over JPEGs, as PNGs and GIFs generally load quicker. JPGs are generally best for photos, PNGs or GIFs for anything else.

Speed up your site with Caching and cache-control

Caching with .htaccess and Apache will take your website and your web skills to the next level. This is some technical and advanced methods condensed to simple htaccess code examples for you. But you must take the time to understand caching with cache-control and other headers and HTTP options before you implement on a production server. Read more about the Caching The Web from here (http://www.david-guerrero.com/papers/squid/squid.htm)

To apply Cache-Control headers, you'll need to use the mod_headers module, which allows you to specify arbitrary HTTP headers for a resource. See http://www.apache.org/docs/mod/mod_headers.html

Here's an example .htaccess file that demonstrates the use of some headers.

htaccess files allow web publishers to use commands normally only found in configuration files. They affect the content of the directory they're in and their subdirectories. Talk to your server administrator to find out if they're enabled.

### activate mod_expires
ExpiresActive On
### Expire .gif's 1 month from when they're accessed
ExpiresByType image/gif A2592000
### Expire everything else 1 day from when it's last modified
### (this uses the Alternative syntax)
ExpiresDefault "modification plus 1 day"
### Apply a Cache-Control header to index.html
<Files index.html>
Header append Cache-Control "public, must-revalidate"
</Files>

Server-Side Scripting

PHP

PHP (http://www.php.net/) is a server-side scripting language that, when built into the server, can be used to embed scripts inside a page's HTML, much like SSI, but with a far larger number of options. PHP can be used as a CGI script on any Web server (Unix or Windows), or as an Apache module.

By default, objects processed by PHP are not assigned validators, and are therefore uncacheable. However, developers can set HTTP headers by using the Header() function.

For example, this will create a Cache-Control header, as well as an Expires header three days in the future:

<?php
Header("Cache-Control: must-revalidate");

$offset = 60 * 60 * 24 * 3;
$ExpireString = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
Header($ExpireString);
?>

Remember that the Header() function MUST come before any other output.

As you can see, you'll have to create the HTTP date for an Expires header by hand; PHP doesn't provide a function to do it for you. Of course, it's easy to set a Cache-Control: max-age header, which is just as good for most situations.

For more information, see http://www.php.net/manual/en/function.header.php

Speed up your site with Memcached

"memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load." In plain English, this means memcached is an application that you can use to take advantage of spare free memory on any number of machines to cache pretty much anything you want (with a few exceptions) and retrieve it very quickly.

For more information, see http://en.wikipedia.org/wiki/Memcached

Reference Links

http://developer.yahoo.com/performance/rules.html
http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/
http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/

I hope you found these tips helpful. Be sure to drop a comment if you have any more ideas.

Adding and removing javascript and css when and where you need it – in Magento

Adding and removing javascript and css is handled separately within Magento. CSS is added in the usual fashion, where you have a <link rel=”stylesheet”… />. However, any included javascript (unless linked to “by hand” from a theme’s skin) is pulled via a php files which reads through the “js” folder in the root directory (root/js/index.php is responsible for this)

That is all well and good for Magento. The real question is how we, as developers, add these items when we need them. How you as a developer add css or javascript is, luckily, handled the same.

In this post, we will show how to add and remove javascript and css to a CMS page (and anywhere else) that you may need.

Method 1: Layout xml.

a) For files you want to include on every page

For css or js files you want to add to every page, you edit the page.xml files located in your layout folder (app/design/frontend/default/your_theme/layout/page.xml). Within this file, at the top you will find the <default> area with the <block name=”root” … >. This block has a child named “head” which contains the included css and js elements.

<block type="page/html_head" name="head" as="head">
<action method="addJs"><script>prototype/prototype.js</script></action>
<action method="addJs" ifconfig="dev/js/deprecation"><script>prototype/deprecation.js</script></action>
<action method="addJs"><script>lib/ccard.js</script></action>
<action method="addJs"><script>prototype/validation.js</script></action>
<action method="addJs"><script>scriptaculous/builder.js</script></action>
...

</block>

Here you can add your javascript and css. Note that any Js files you add are relative to the “js” folder in your root directory. The css files are included from the skin files of the current and default templates (skin/frontend/default/your_template(& default)/css).

b) Specific areas

If you want to include css or js on only certain areas (such as the checkout process or catalog pages), you can do that also. For instance, if you want it in a single product view (product view vs product list), you can open up catalog.xml, find <catalog_product_view> area (near line 168 in vs 1.2.1).  Add your code in there – notice that we are using the <reference> tag rather than <block> tags. We use the “reference” tag to reference other blocks that are in other areas of the template.

<reference name="head">
<action method="addJs"><script>varien/product.js</script></action>
<action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/>

<!--<if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/lang/calendar-en.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
<action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
</reference>

The use of can also be used in your layout XML areas in the admin backend (CMS pages, category and product designs). This can accomplish the same thing, as well as adding or removing other blocks.

Method 2: Block Code

We can accomplish all of this in code as well. These functions are defined within Mage_Page_Block_Html_Head. So, we can use this code with in a block class (not a .phtml file!):

$headBlock = $this->getLayout()->getBlock('head');
$headBlock->addJs('somefolder/yay.js');

I suggest looking over the page.xml files as long as finding the removeItem syntax ($type, $name for the method, for the xml), which will be very handy for you for adding or removing assets as and when you need them!

<action method="removeItem"><type>js</type><name>calendar/calendar.js</name</action>
$this->getLayout->getBlock('head')->removeItem('js', 'calendar/calendar.js');

Create Custom Module “HelloWorld” – in Magento

Part of customizing Magento is, of course, creating custom Modules. These allow you to inject functionality anywhere, whether in a “static” block fashion that’s more than static, or a shipping/payment module, or large module to do something as large as integrating a 3rd party system (or multiple systems).

There are many things custom Modules can do, from editing your Database, to handling module upgrades to overriding classes (Blocks, Controllers, Models) … and more!

Note - All of your customizations need to go into the [root]\app\code\local folder. This is where Magento expects to find them and it’s also a factor in maintaining your upgrade path. When the next version of Magento is released you’ll be able to backup your “local” folder and blow away everything else.

Before we get too far into this let’s setup our development environment, go to:

Admin -> System -> Cache Management: Cache Control – All Cache = Disable (This will save you many hours of self-torture while you’re developing.)

Magento is now correctly configured for development so let’s dive into building a custom module.

This blog post is a very basic start on creating your own custom module and hooking it up to a phtml file in your own theme.

I will be creating a Iyngaran HelloWorld module. ‘Iyngaran’ is the namespace, ‘HelloWorld’ is the module.

Sample file structure:

[root]\app\code\local\{Namespace}\{Modulename}

[root]\app\code\local\{Namespace}\{Modulename}\controllers

[root]\app\code\local\{Namespace}\{Modulename}\etc

[root]\app\code\local\{Namespace}\{Modulename}\etc\config.xml

[root]\app\code\local\{Namespace}\{Modulename}\Helper

[root]\app\code\local\{Namespace}\{Modulename}\Model

[root]\app\code\local\{Namespace}\{Modulename}\{Modulename}.php

{Namespace} is a user defined variable. Basically it’s just a mechanism that allows the user to create disparate classes that would otherwise have the same names.

{Modulename} this is the name of your module.

controllers is where all the controllers go.

Model holds all of the models for your module.

For my examples I’m going to use “Iyngaran” as my namespace and “Helloworld” as my Module. I’m not entirely sure if it matters or not, but as a general rule I always capitalize the first letter and leave the rest lower case.

Step One

Inform Magento that you have a custom module. Note the file locations (need to create directories as necessary).

app/etc/modules/Iyngaran_HelloWorld.xml

<?xml version="1.0"?>

<config>

<modules>

<Iyngaran_HelloWorld>

<active>true</active>

<codePool>local</codePool>

</Iyngaran_HelloWorld>

</modules>

</config>

I have informed Magento that I have an active module (you can turn it off from here by setting ‘active’ to false. I have also informed Magento that it is located in the ‘local’ code pool.

Step Two

Configure your new module. Note the file locations (need to create directories as necessary).

app/code/local/Iyngaran/HelloWorld/etc/config.xml

<?xml version="1.0"?>

<config>

<global>

<modules>

<iyngaran_helloworld>

<version>0.1.0</version>

</iyngaran_helloworld>

</modules>

<blocks>

<helloworld>

<rewrite>

<helloworld>Iyngaran_HelloWorld_Block_HelloWorld</helloworld>

</rewrite>

</helloworld>

</blocks>

</global>

<frontend>

<routers>

<helloworld>

<use>standard</use>

<args>

<module>Iyngaran_HelloWorld</module>

<frontName>helloworld</frontName>

</args>

</helloworld>

</routers>

<layout>

<updates>

<helloworld>

<file>helloworld.xml</file>

</helloworld>

</updates>

</layout>

</frontend>

</config>

I have informed Magento of my module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).

I have also informed Magento that my module contains block files which are found in Iyngaran/HelloWorld/Block. My class name will have “Iyngaran_HelloWorld_Block”. If you want to see the many possibilities of stuff that goes in here, check out Mage config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there.

Step Three

Here is my block code. It doesn’t really do anything, but shows some functionality.

app/code/local/Iyngaran/HelloWorld/Block/HelloWorld.php

<?php

class Iyngaran_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template

{

public function _prepareLayout()

{

$this->getLayout()->getBlock('breadcrumbs')

->addCrumb('home',

array('label'=>Mage::helper('catalogsearch')->__('Home'),

'title'=>Mage::helper('catalogsearch')->__('Go to Home Page'),

'link'=>Mage::getBaseUrl())

)

->addCrumb('customer',

array('label'=>Mage::helper('customer')->__('Foo'))

);

return parent::_prepareLayout();

}

public function myMessage(){

return "I am Iyngaran, This is my module.";

}

}

?>

Step Four

Here we create our template (phtml) file.

app/design/frontend/default/default/template/helloworld/helloworld.phtml

<div>

<?php

echo 'Hello World ! I am Iyngaran Iyathurai';

echo "<BR/>";

echo $this->myMessage();

?>

</div>

This just outputs some HTML and also runs the myMessage(); function from our block (HelloWorld .php).

Two caveats here. By placing our helloworld.phtml file in it’s location, we have created our own theme. You must make sure that

a) Magento knows about your theme (Admin->System->Design)

The new module is ready to run and hit browser with url

http://localhost/web/tutorials/magento/index.php/helloworld/ and see result.

Customizing Magento - Custom Module “HelloWorld”

b) If you use the this block in a CMS page, you set the CMS page to use your theme (Admin->CMS->Manage Pages->’Your Page’->Custom Design->Custom Theme drop down)

In a cms page, add this to your content:

{{block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"}}

and see result.

Customizing Magento - Custom Module “HelloWorld”

Reference - http://www.magentocommerce.com/wiki/index/categories/

Create and customize the Magento store

Magento content management system is an open source eCommerce application, perfect for online stores. It is a powerful software characterized by great flexibility and full control over the look, content and functionality of your online shop. Magento CMS was created on March 31, 2008. It was created by Varien, building on components of the Zend Framework.

Magento engine installation procedure

First of all go to http://www.magentocommerce.com/download/noregister and download the Downloader as zip (not the Full release). I would like to recommend you to download the “Downloader”

Create and customize the Magento store - download

Then extract the files. And after that upload them to server through FTP. Pay attention that you follow all server requirements. For this example, I am going to install it on my localhost. So now I need to extract the files to the following directory /var/www/web/tutorials/magento

iyngaran@iyngaran-laptop:~$ sudo unzip -d /var/www/web/tutorials/ /home/iyngaran/Downloads/magento-downloader-1.3.2.1.zip


Create and customize the Magento store - unzip

The unzip process is successfully completed

Create and customize the Magento store - unzip-success

Set file permissions: navigate to the directory with your FTP client. Then locate the function “Change Permissions” or “Change Mode” in your FTP client and select it. Change mode to writable.

In my localhost

iyngaran@iyngaran-laptop:/$ sudo chmod 777 -R /var/www/web/tutorials/magento


Create and customize the Magento store - set-permission

And then you can simply install the Magent.

Step - 1 : Open your favorite web browser and enter the url. Ex - In my localhost the url is - http://localhost/web/tutorials/magento/. You will get the installation wizard on the browser. Start the download process here

Create and customize the Magento store - start the download process

Downloading.....

Create and customize the Magento store - the proccess

Step - 2 : The download process is completed.

Create and customize the Magento store - download-completed

Step - 3 : Start the installation process.

Create and customize the Magento store - Install-step1

Step - 4 : The local settings such as language, currency and etc for your test store.

Create and customize the Magento store - Step2

Step - 5 : Do the configuration such as database configuration and etc for your store

Create and customize the Magento store - Step-3

Step - 6 : Setup the administrator user account for your store

Create and customize the Magento store - step-4

Step - 7 : The final page - you have successfully installed a store :)

Create and customize the Magento store - step-5

Step - 8 : Now let's go to store back-end/Administration panel.

Create and customize the Magento store - index-not-upto-date

There are few warning errors in the admin Panel.

1. {{base_url}} is not recommended to use in a production environment to declare the Base Unsecure Url / Base Secure Url. It is highly recommended to change this value in your Magento configuration.

Create and customize the Magento store - reindex

To sort this issue, Go the System->Configuration->Web, there replace your http url (Example - http://localhost/web/tutorials/magento/) for {{base_url}} in the configuration settings

Create and customize the Magento store - Base URL Configuration Value

If you had to update your configuration as described above, please go to System > Cache management and refresh all caches.

2. One or more Indexes are not up to date: Product Attributes, Product Prices, ... .Click here to go to Index Management and rebuild required indexes.

Create and customize the Magento store - index-not-upto-date

To sort this issue, Go to the System->Index management and reindex those indexes and refresh the page.

3. Latest Message: Magento CE Version 1.4.1.1 Patch Available Read details

This is just a message. So at the moment, I am not going to do anything for this.

The Admin Panel without any errors

Create and customize the Magento store - Admin Panel

Step - 9 : Now the Magento store is ready with front-end store and administration panel.

Step - 10 : Now the store is working without any errors. But there is no products in the home page. So I am going to add a product from Admin Panel. To add a product from Admin Panel, Go to the Admin Panel Catalog->Manage Products->Add Product

Create and customize the Magento store - adding products in admin page

Note - Make sure, you have add the product to the Main Website and set category as default.

Go to Catalog->Manage Products, and select the product (tick the product's check box) and select the "Update Attributes" for the Actions combo box and click on Submit button.

Create and customize the Magento store - Manage Products

And add that product to the "Main Website"

Create and customize the Magento store - update product attributes

Step - 11 : I have added a product in the Admin Panel. But still in the home page the product is not displaying.

Create and customize the Magento store - magento default home page

Step - 12 : I have added a product in the Admin Panel. But still in the home page the product is not displaying.

The product is not displaying on the home page. Because the code on the home page is not designed to show products by default. So the next thing, I have to add code to the home page, which shows some products on the page. To add code to the home page, Go to the Admin Panel CMS->Pages. Click on Home page and click on "Content" tab under the page information. Add the following lines of code to the content.

{{block type="catalog/product_list" template="catalog/product/list.phtml"}}

Create and customize the Magento store - home page contents code

Step - 13 : Refresh the home page.

Create and customize the Magento store - displaying products in magento home page

Yes Well Done! The product is displaying on the homepage. :)

So lets play around with the new store and customize it. :) :) :)

Generate Constructor, Getters and Setters in NetBeans PHP IDE

This morning I have committed a feature to the NetBeans PHP support that will be part of NetBeans IDE 6.5, which offers generating of constructor, getters and setters in a PHP class. To invoke the functionality, the caret position has to be inside a PHP class and you have to press shortcut ALT+Insert (CTLRL+I on Mac). After invoking the shortcut, all possible generators are offered.

Let's explain on a simple example. I have very simple PHP class, where I have only two properties - $name and $age. At first I want to add constructor. After pressing ALT+Insert (CTLRL+I on Mac), the constructor generator is offered - Constructor... item in the Generate menu. After invoking this item, the Generate Constructor dialog is displayed. There I can choose parameters of the constructor. It is possible to chose any property, then the constructor is generated without any parameter and empty. If I check / uncheck the User class, then all properties are selected / unselected. For my demonstration I have chose $name property.  After pressing OK button, the constructor with one parameter is generated.

Note the following screenshot, I have highlighted two variables, and my mouse pointer is located on one of the the selected variable. Then I pressed ALT+Insert.
View Screen Shot 1
In that screenshot, only "connect to database" and "database table" menus are available. But the expected menu Generate "Getter and Setter" and etc are not available.

But In the following screenshot you can see, my mouse pointer is located in the class, But not on the variables.
View Screen Shot 2

Now I want to generate getter for the $name. After invoking Generate menu, you can notice that the Constructor... item is not offer anymore, because the class already has a constructor. I choose Getter... item and Generate Getters dialog is displayed. In the dialog you can choose, for which properties you want to generate getters. Again you can check / uncheck the class node, which selects / unselects all properties.
View Screen Shot 3

As the next step I want to generate getter and setter for $age property. After choosing Getter and Setter... item in Generate menu, the dialog offers only $age property, because only this property has neither getter nor setter. When I invoke Generate menu after creating getter and setter for $age property, only setter generator is offered, because there is not defined only setter for $name property
View Screen Shot 4

The generate functionality is designed that you can work just with the keyboard and you don't have to use mouse.