Monthly Archives: September 2012

CODING TIPS FOR PERFORMANCE IMPROVEMENT

In this post I cover most performance improvement tips related JavaScript, CSS and PHP. While working with small web application its OK to ignore these tips but whenever you are going to dealing with large web application which will have so many user base and may increase database day by day then you should have to take care about these tips and I am sure it will give drastic change in your website performance.

Normally developers are using the way which is most comfortable for them or which they are more aware of. I know you are good programmer as you are here. :) So being a good web programmer start to follow below tips on your coding style and it will increase your web page performance and defiantly increase your confidence level as well.

JavaScript:

  • If external JavaScript or custom build function not required performing onLoad of page then put it on bottom of page. i.e. Load it after page content so that your page content load first.
  • Always make habit to declare variable and then use.
  • Don’t use
    for(i=0; i<=array1.length; i++){….} // method 1Instead of this usevar arrLen = array1.length;
    for(i=0; i<=arrLen; i++){….} // method 2
    A first method will call length function to count array length on each iteration.
    A second method will call length function to count array length ones.
  • Remove unnecessary scripts from the page.
  • Always try to use min version of external scripts. There are so many online converter avail online to convert your scripts into min version.

CSS:

  • Load after page content. Put in bottom of page.
  • Always try to use min version of all css.
  • Always try to use external css as browser cache css so it may not take time for second request or for other page.
  • Ignore conditional css.

PHP:

  • Use always echo as it is faster than print. Both function used for the printing value on page. Try to ignore print until it does not require.
  • include_once is more costly than include statement. Because it has to search for class definition you are trying to include is already included or not?
  • Always use single quotes for long strings instead of double quotes. Because in double quotes it will search for php variable to evaluate them. So in this case, echo ‘This is long string’ . $name is faster than echo “This is long string $name”. But from above both echo ‘This is long string’ , $name, is faster because it does not require any string manipulation.
  • As we see for JavaScript the same thing applies for PHP as wellDon’t usefor($i=0; $i<count($names);$i++){…}Instead of this use$arrsize = count($names);for($i=0; $i<$arrsize;$i++){…}.The first method will call count function on each iteration of for loop, while in second iteration count function is being called only once.
  • If you can solve your problem without using regular expression then don’t use it. Regular expression are slower than their php counterparts. For example use str_replace instead of preg_replace.
  • Don’t use short tags <?=$name> and try to using <?php echo $name; > , It can create a problem for you if you are going to deploy your application on another server.
  • Don’t use or relay on register_globals or magic quotes and read and configure your php.ini settings carefully.
  • Always use pagination if page having so many data to display in web appliaton.
  • Use always joins if possible to get data instead of sub query in loop.
  • Create indexes in database to get data faster.
  • Never use “select * from ….”. Always make habit to write column list how many you require in page. For example “select id, firstname, lastname from …..”.
  • Always crop images as per height n width.

Reset MD5 password using phpMyAdmin?

As you know MD5 (Message-Digest algorithm 5) is one way encryption method. In order to reset MD5 password you have to run database query. Here I have got one direct solution for resetting MD5 password using phpMyAdmin GUI.

Follow below steps to reset MD5 Password.

  • Open phpMyAdmin.
  • Open record in edit format which you want to reset.

    edit record

    edit record

  • Enter password or string whichever you want to encrypt in original format.

    Enter New Password or String

    Enter New Password or String

  • Select MD5 in function column and press GO.

    Password or String should be in original format

    Password or String should be in original format

  • Your password is reset now.

Important Rule of Abstract Class

1. Class is declare with keyword “abstract”

public abstract parentClass  {  }

2. May or May not  Include abstract method

3. Abstract methods do not have implementation or body part.

public abstract void moveTo(int x, int y);

4. Abstract classes cannot be instantiated , but they can be subclassed

5.If a class includes abstract methods, the class itself must be declared abstract.

6.When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract

7. Can not create object of abstract class.

Example :

[code language=”php”]

abstract class GraphicObject {
int x, y;

void moveTo(int newX, int newY) {

}
abstract void draw();
abstract void resize();
}

class Circle extends GraphicObject {
void draw() {

}
void resize() {

}
}
class Rectangle extends GraphicObject {
void draw() {

}
void resize() {

}
}

[/code]

get rid of write array name each time in PHP

In today’s era noone has time and every person wants to save their time. As a being a good programmer I also have to reduce my coding time so I can go for other stuff. If you are PHP developer then you know you need to write array name each time like $_POST, $_GET, $_SESSION…. We need to press dollar($) with shift key same for underscore and each time need to write array name in caps. Specially for pre-defined PHP array not for custom made array. So finally I deside to made function like extract array and see OMG it is already avail in PHP. I feel very happy and started to using extract function.

extract()

The extract() function returns the number of variables successfully imported into the symbol table. You can overwrite existing variables value and keep as it is. Also you can change prefix of variables if it is already exists.

Example

<?php
        $empinfo = array(
                “firstname” => “Bharat”,
                “lastname” => “Patel”,
                “email” => “sourcecodemart@gmail.com”
        );
        extract($empinfo);
        echo $email;
?>

<?php

/* Suppose that $var_array is an array returned from
   wddx_deserialize */

$size = “large”;
$var_array = array(“color” => “blue”,
                   “size”  => “medium”,
                   “shape” => “sphere”);
extract($var_array, EXTR_PREFIX_SAME, “wddx”);

echo “$color, $size, $shape, $wddx_size\n”;

?>

Click to get more about extract().

Some Most Useful PHP string functions

In today’s era PHP is more popular web based scripting language. If you are PHP developer then below string function you may need in your programming.

trim

Strip whitespace from the beginning and end of a string

Syntax : string trim ( string $string [, string $charlist ] )

Return : Terminated String

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip (\n,\r,\t,) characters from string.

Example:

$stringVal = “ How Are you ? “;

$stringVal = trim($stringVal);

Output :            ‘How Are you ?’

strrev

Reverse a string

Syntax : string strrev ( string $string )

Return :Returns the reversed string.

echo strrev(“Hello world!”); // outputs “!dlrow olleH”

strlen

Returns the length of the given string.

Syntax : int strlen ( string $string )

Return : The length of the string on success, and 0 if the string is empty.

$str = ‘abcdefghi’;
echo strlen($str); // 9

strtolower

Make string’s all characters in lowercase

Syntax : string strtolower ( string $str )

Return: Returns the lowercased string.

strtoupper

Make string’s all characters in uppercase

Syntax :string strtoupper ( string $string )

Return: Returns the uppercase string.

ucfirst

Make a string’s first character uppercase

Syntax : string strtoupper ( string $string )

$str = “i am fine here”;
$str = strtolower($str);
echo $str; // I Am Fine Here

lcfirst

Make a string’s first character lowercase

Syntax : string lcfirst ( string $str )

$foo = ‘Hello World’;
$foo = lcfirst($foo);             // hello world

substr

Returns the portion of string specified by the start and length parameters.

Syntax : string substr ( string $string , int $start [, int $length ] )

string

 The input string. Must be one character or longer.

start

If start is non-negative, the returned string will start at the start’th position in string, counting from zero. For instance, in the string ‘abcdef’, the character at position 0 is ‘a’, the character at position 2 is ‘c’, and so forth.

If start is negative, the returned string will start at the start’th character from the end of string.

If string is less than or equal to start characters long, FALSE will be returned.

length

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned.

If length is given and is 0, FALSE or NULL an empty string will be returned.

If length is omitted, the substring starting from start until the end of the string will be returned.

E.g.

$rest = substr(“abcdef”, 0, -1);  // returns “abcde”

$rest = substr(“abcdef”, 2, -1);  // returns “cde”

$rest = substr(“abcdef”, 4, -4);  // returns false

$rest = substr(“abcdef”, -3, -1); // returns “de”

Return: Returns the extracted part of string; or FALSE on failure, or an empty string.

How to get first and last day of month in PHP?

In order to run report with date range, most of people want to set default date range of current month. There may be two type of requirement in this type of case.

first and last day of month

first and last day of month

  • Fromdate should be first day of month and Todate should be today date.
  • Fromdate should be first day of month and Todate should be last day of month.

I have used mktime() function to get time.

Here is the solution to get first, current and last day of month.

To get first day month.

$firstdate = date(‘m-d-Y’, mktime(0,0,0,date(‘m’),1,date(‘Y’)));
//or another simple way to get first day of month;
$firstdate = date(‘m’) . ‘-01-‘ . date(‘Y’);

To get today day

$today = date(‘m-d-Y’);

To get last day

$lastday = date(‘m-d-Y’, mktime(0,0,0,date(‘m’)+1,0,date(‘Y’)));

Click to view live demo.