Search This Blog

Wednesday, 26 June 2013

Perl scripting

PERL (Practical Extraction Report language)

  • Perl is developed by "Larry Wall" in 1986.

  • The home of the Perl is Unix

  • Perl is written in "C" language.

  • Perl is interpreter based language.

  • Perl is a case sensitive scripting language.
Differences between Scripting Language and Programming Language
Scripting Language
  1. It is an Interpreter based language.

  2. Interpreter converts high level instructions into machine language line by line.

  3. It doesn’t create .exe file.

  4. No need to compile the source code.

  5. It takes less lines of code.

  6. It reduces cost of maintenance

  7. Basically this executes at server side.
  8. Programming Language
    1. It is a compiler based language.

    2. Compiler converts whole program in single shot into machine language.

    3. It creates .exe file.

    4. Needs to compile the program.

    5. It takes numerous lines of code.

    6. It increases cost of maintenance.

    7. These are used for client based applications.
    8. The perl borrowed many features from Unix utilities (like awk, sed, grep, tr ) and added "C" language functionality.
      The features of Perl
      1. Free software.

      2. Open source code.

      3. It is simple and easy to learn.

      4. It is rich in procedural and object oriented.

      5. It is highly portable language i.e The Perl programs are written in one platform allows to run in another platform with or without modifications.

      6. Perl supports DB Connectivity.

      7. Perl supports CPAN (Comprehensive Perl Archive Network) modules. You can refer the following website for CPAN modules ;
      8. www.cpan.org
      9. The Perl initially designed for to do manipulations in text files, later it is used in wide range of the following areas

        • System Administration

        • Database Administration

        • Web Development (CGI)

        • Networking (Net)

        • Bioinformatics (Bio)

        • Testing (Test)

        • VLSI

        • Telecom

        • GUI development
      10. The extension of the Perl program is ".pl".

      11. The name of the Perl interpreter is "perl"

      12. The motto of the Perl is more than one way to do it.

      13. Perl supports 2 types of comments.

        • Single line comment (#)

        • Multi line comment
          =pod (plan old documentation)
          ------------------
          ------------------
          ------------------
          =cut
          How to run Perl programs on windows platform
          1. Open text editor (notepad)

          2. Write Perl program

          3. Save program with .pl extension

          4. Run program at command prompt C:\>perl program.pl
          5. How to run Perl programs on Linux platform
            1. Open text editor (vi)

            2. Write Perl program

            3. Save and quit from the vi editor

            4. Run the program at $ prompt ;
            5. $perl program.pl
              $chmod a+x program.pl
              $./program.pl
              How to see location of the Perl?
              $which perl ß
              /usr/bin/perl
              How to see the help in Linux?
              $man perl
              How to see the version of the perl?
              $perl –v
              Write a program to print welcome message?
              #!/usr/bin/perl -w
              #Author: Pavankumar
              # -w displays warnings
              print "welcome to SEI \n";
              print "This is my first perl program \n";



              Variable
              1. It is a data name or memory location

              2. It is a temporary storage location

              3. It value can change during the execution of the program

              4. Perl allows implicit variable declaration i.e. No need to declare the variables explicitly by programmer

              5. Every variable occupies memory during execution time

              6. Variables are classified into 3 types

                • Scalar variables

                • Array variables or Indexed array variables

                • Hash array variables or Associated array variables
                  Scalar variables
                  • It holds only one value

                  • The value may be integer/float/string

                  • It should begin with "$" symbol
                  • Array variables
                    • It is a group of scalar variables

                    • It should begin with "@" symbol
                    • Hash array variables
                      • It is a group of key pair values

                      • It should begin with "%" symbol
                      • Print:
                        "print" is a predefined function and it is used for to write data to the output screen.
                        Ex: print ("Hello");
                        print "Hello";
                        print STDOUT "Hello";
                        #hello.pl
                        #!/usr/bin/perl -w
                        print ("hello, perl\n");
                        print "hello, perl\n";
                        print STDOUT "hello, perl\n";
                        The standard input/output/error buffers are
                        • STDIN

                        • STDOUT

                        • STDERR
                        <STDIN> is the standard input handler used to take input from user.
                        <STDOUT> is the standard output handler used to write data to the screen.
                        <STDERROR> is the standard error handler used to write errors.





                        #Write a program to accept the name and display
                        #prg2-chomp.pl
                        #!/usr/bin/perl -w
                        print "Enter a name:";
                        $name=<STDIN>; #<> -- Diamond operator
                        chomp($name);
                        print "Hello, $name, How are you?\n";
                        print "Enter a name:";
                        chomp($name=<STDIN>);
                        print "Hello $name, How are you?\n";
                        print "Enter a name:";
                        chomp($name=<>); # By default it reads input from the keyboard
                        print "Hello $name, How are you?\n";
                        Note:
                        "chomp" is a predefined function, it deletes the given string last character, if it is new line character
                        Scalar variable Examples
                        $a=100; # integer
                        $b=10.5; # float
                        $course="perl"; # String
                        $name=’Tecno soft’; #String
                        $k="100"; # String
                        $m="25.67"; #String
                        #prg-scalar.pl
                        #!/usr/bin/perl -w
                        $a=100; # integer
                        $b=10.5; # float
                        $course="perl"; # String
                        $name='Tecno soft'; #String
                        $k="100"; # String
                        $m="25.67"; #String
                        print "a=$a, b=$b, course=$course, name=$name, k=$k, m=$m\n";
                        Strings are classified into 3 types
                        Double quoted strings (" ") qq// or qq{} or qq() or qq<> or qq[]
                        Single quoted string (‘ ‘) q// or q{} or q() or q<> or q[]
                        Back quoted strings or Back tick strings (` `) qx// or qx{} or qx() or qx<> or qx[]
                        Ex1:
                        $str="perl";
                        $x="I like $str";
                        print $x;
                        Ex2:
                        $str="perl";
                        $x=’I like $str’;
                        print $x;
                        Ex3:
                        $str="perl";
                        $x="I like \n $str";
                        print $x;
                        Ex4:
                        $str="perl";
                        $x=’I like \n $str";
                        print $x;
                        Note:
                        In double quoted strings, variable substitution takes place but in single quoted strings, every thing it treats as normal text.
                        $str = "I said, "Don’t write to dist""; -- Incorrect
                        $str = "I said, \"Don’t write to disk\"’; -- Correct
                        $str = ‘I said, "Don\’t write to disk"’; -- Correct
                        #!/usr/bin/perl -w
                        $x = "disk";
                        $str = qq/I said, "Don’t write to $x"\n/;
                        print $str;
                        Output:
                        I said, "Don’t write to disk
                        #!/usr/bin/perl -w
                        $x = "disk";
                        $str = "q/I said, "Don’t write to $x"\n/;
                        print $str;
                        Output:
                        I said, "Don’t write to $x\n"
                        Back quote (``): It is used to execute operating system commands.
                        #!/usr/bin/perl -w
                        $x=`ls -lrt`;
                        print $x;
                        #!/usr/bin/perl -w
                        $x=qx/who/;
                        print $x;



                        Operators:
                        Arithmetic operators
                        : + - * / % **
                        Ex1:
                        $a=10;
                        $b=4;
                        print $a+$b; #14
                        Ex2:
                        $a=10;
                        $b="25abc";
                        print $a+$b; #35
                        Ex3:
                        $a=10;
                        $b="abc25";
                        print $a+$b; #10
                        Ex4:
                        $a="Hello";
                        $b="Pavan";
                        print $a+$b; #0
                        Ex5:
                        $a=10;
                        $b="456abc";
                        print $a+$b; #466
                        Ex6:
                        $a=10;
                        $b="25abc";
                        print $a+$b; #35
                        print $a.$b; #1025abc
                        Ex7:
                        $a=2
                        $b=4
                        print $a**$b; #2**4=16
                        Relation operators:
                        a) Numeric comparison operators
                        : <, >, <=, >=, = =, ! =, <=> (Three way comparison operator)
                        b) String comparison operators:
                        lt, gt, le, ge, eq, ne, cmp (Three way comparison operator)
                        Ex1:
                        $a=100;
                        $b=20;
                        $a>$b ---- True
                        $a gt $b ---- False
                        Ex2:
                        $x ="hello";
                        $y ="pavan";
                        $x gt $y --- True
                        $x > $y --- False
                        Ex3:
                        $c = $a <=> $b;
                        If a>b à 1
                        a<b à -1
                        a= =b à 0
                        Ex4:
                        $k = $x cmp $y
                        If x>y à 1
                        x<y à -1
                        x= =y à 0
                        Logical operators:
                        &&, ||, ! or and, or, not
                        Sting multiplication operator:
                        x
                        $str = "perl";
                        $k = $str x 5; # It multiplies str by 5 times
                        print $k; # perlperlperlperlperl
                        String concatenation operator:
                        $str1 = "SEI";
                        $str2 = "Investments";
                        a) $k = $str1.$str2;
                        print $k; #SEIInvestments
                        b) $k = $str1." ".$str2;
                        print $k; #SEI Investments
                        Range operator:
                        1..10 ----- Correct
                        a..z ------ Correct
                        -10..-1 ---- Correct
                        10..1 ---- Incorrect
                        z..a ----- Incorrect
                        -1..-10 ---- Incorrect
                        print 1..10 # It prints no’s 1 to 10
                        Assignment operators:
                        $a = 10;
                        $b = 20;
                        $c = 30;
                        Or ($a,$b,$c)=(10,20,30)
                        Short hand assignment operator:
                        +=, -=, *=, !=, %=, .=, x=
                        Ex:
                        1. $a=10;

                        2. $a=$a+5; (or) $a+=5;
                        3. $str="load";
                        $str=$str."ing"; (or) $str.="ing";
                        Increment operator: ++
                        $a = 10;
                        $a = $a+1; (or) $a+=1; (or) $a++;
                        Decrement operator: --
                        $a = 10;
                        $a = $a-1; (or) $a-=1; (or) $a--;
                        IF Statements:
                        1. Simple if
                        2. if(condition)
                          {
                          ------------
                          ------------
                          }
                          -------------
                          -------------
                        3. simple unless
                        4. unless(condition)
                          {
                          -------------
                          -------------
                          }
                          -------------
                          -------------
                        5. if….else
                        6. if(condition)
                          {
                          ------------
                          ------------
                          }
                          else
                          {
                          -----------
                          -----------
                          }
                          -----------
                          -----------
                        7. unless…else
                        8. unless(condition)
                          {
                          ------------
                          ------------
                          }
                          else
                          {
                          ------------
                          ------------
                          }
                          --------------
                          --------------
                        9. if…elseif…
                        10. if(condition)
                          {
                          ------------
                          ------------
                          }
                          elsif(condition)
                          {
                          -------------
                          -------------
                          }
                          else
                          {
                          ------------
                          ------------
                          }
                        11. single line if statement
                        12. statement1 if(condition);
                          ---------------
                          ---------------
                        13. Single line unless statement
                        Statement1 unless(condition);
                        ------------------
                        ------------------
                        Looping statements:
                        1. while loop
                        while(condition)
                        {
                        -----------
                        -----------
                        }
                        ---------
                        ---------
                      • until loop
                      • until(condition)
                        {
                        -----------
                        -----------
                        }
                        -----------
                        -----------
                      • do…while loop
                      • do
                        {
                        -----------
                        -----------
                        }
                        while(condition);
                      • do…until loop

                      • do
                        {
                        -----------
                        -----------
                        }
                        while(condition);
                        ------------
                        ------------
                      • for loop
                      • for(initialization;condition;incr/decr)
                        {
                        ---------------
                        ---------------
                        }
                        --------------
                        --------------
                      • foreach loop
                      • foreach variable(list of values)
                        {
                        --------------
                        --------------
                        }
                        ------------
                        ------------
                        last :
                        It is used for to terminate the loop.
                        next:
                        It is used for to start the loop again.
                        while(condition)
                        {
                        ------------
                        ------------
                        last;
                        ------------
                        ------------
                        }
                        -----------
                        -----------
                        while(condition)
                        {
                        -------------
                        -------------
                        next;
                        -------------
                        -------------
                        }
                        -------------
                        -------------
                        Programs on if statements:
                        #write a program to accept a number and check the no is an even or odd?
                        #!/usr/bin/perl -w
                        print "\nEnter number:";
                        chomp($n=<STDIN>);
                        if($n%2==0)
                        {
                        print "\n$n is an Even no\n";
                        }
                        else
                        {
                        print "\n$n is an Odd no\n";
                        }
                        #WAP Accept a number and check the no is 3 digit no or not?
                        #!/usr/bin/perl -w
                        print "\nEnter a number:";
                        chomp($n=<STDIN>);
                        if($n>=100&&$n<=999)
                        {
                        print "\n$n is a 3 digit number\n";
                        }
                        else
                        {
                        print "\n$n is not a 3 digit number\n";
                        }
                        #WAP to accept username and password and check the user is valid or not?
                        #!/usr/bin/perl -w
                        print "\nEnter Username:";
                        chomp($username=<STDIN>);
                        print "\nEnter Password:";
                        chomp($password=<STDIN>);
                        if($username eq "pbandaru" && $password eq "pbandaru")
                        {
                        print "\nWelcome to SEI\n";
                        }
                        else
                        {
                        print "\nInvalid username or password\n";
                        }
                        #WAP to accept 2 strings and check string1 >string2 or string1<string2 or both strings are equal?
                        #!/usr/bin/perl -w
                        print "\nEnter a string1:";
                        chomp($str1=<STDIN>);
                        print "\nEnter a string2:";
                        chomp($str2=<STDIN>);
                        $x=($str1 cmp $str2);
                        if($x = =1)
                        {
                        print "\n$str1 is greater than $str2\n";
                        }
                        elsif($x = =-1)
                        {
                        print "\n$str1 is less than $str2\n";
                        }
                        elsif($x = =0)
                        {
                        print "\nboth are equal\n";
                        }

                        #WAP to check whether variable exist or not?
                        #!/usr/bin/perl -w
                        $a=10;
                        undef($a); #undef function is used for to delete a variable
                        if(defined($a)) #defined function returns true, if the variable defined otherwise false
                        {
                        print "variable exist\n";
                        }
                        else
                        {
                        print "No such variable\n";
                        }
                        Looping Statements:
                        #WAP to print numbers from 1 to 10
                        #!/usr/bin/perl -w
                        $i=1;
                        while($i<=10)
                        {
                        print "$i\t";
                        $i++;
                        }
                        print "\n\n\n";
                        for($i=1;$i<=10;$i++)
                        {
                        print "$i\t";
                        }
                        print "\n\n\n";
                        foreach $i (1..10)
                        {
                        print "$i\t"
                        }
                        print "\n\n\n";
                        foreach (1..10)
                        {
                        print "$_\t"; #$_ is a special variable which stores the default values
                        }
                        print "\n";
                        Arrays:
                        1. It is a collection of scalar variables. i.e collection of dissimilar type of values

                        2. It should begin with @ symbol

                        3. It has an infinite length

                        4. The array index starts with ‘0’
                        5. Syntax: @array_variable=(list of scalars);
                          Ex: @num=(10,20,30,40,50,60);
                          @x=(10,’perl’,4.5,60,"unix");
                          @days=("sun","mon","tue","wed",’thu","fri","sat");
                          @days=qw(sun mon tue wed thu fri sat);
                          Accessing array elements
                          print "@num"; #10 20 30 40 50 60 à With space
                          print @num; #102030405060 à Without space
                          print $num[2]; #30 à Prints third element
                          print "@num[1..4]";#20 30 40 50 à Prints elements 1 to 4
                          print "$num[-1]"; #60 à It prints the last element
                          print "@num[0,1,-1,-2]";10 20 60 50 à More than one element array representation
                          EX:
                          #!/usr/bin/perl -w
                          @num=(10,20,30,40,50,60);
                          print "@num"; #10 20 30 40 50 60 With space
                          print "\n";
                          print @num; #102030405060 Without space
                          print "\n";
                          print $num[2]; #30 Prints third element
                          print "\n";
                          print "@num[1..4]"; #20 30 40 50 Prints elements 1 to 4
                          print "\n";
                          print "$num[-1]"; #60 It prints the last element
                          print "\n";
                          print "@num[0,1,-1,-2]"; #10 20 60 50 More than one element array representation
                          print "\n";
                          Writing elements to array
                          $num[6]=70;
                          $num[3]=100;
                          @num[7..10]=(100,200,300,400); # It overwrites if it exists, if not creates.
                          $num[100]="abc"; # If the last index is 50 then it creates remaining indexes before 100.
                          EX:
                          #!/usr/bin/perl
                          @num=(10,20,30,40,50,60);
                          $num[6]=70; # It will create a new index and add an element
                          print $num[6];
                          print "\n";
                          $num[3]=100; # It will overwrite the existing element
                          print $num[3];
                          print "\n";
                          @num[7..10]=(100,200,300,400);
                          print "@num";
                          print "\n";
                          $num[100]="abc";
                          print "$num[100]";
                          print "\n";
                          $#array:
                          It returns the last index of the array.
                          EX:
                          #!/usr/bin/perl -w
                          @num=(10,20,30,40,50,60);
                          print "\nnum array last index is: $#num"; #5
                          print "\nTotal elements in num array is:",$#num+1; #6
                          print "\n";
                          $num[$#num+1]="hello";
                          @k=@num; #copying array
                          print "Copied array elements are:@k";
                          print "\n";
                          $n=@num; #Assigining lenth of the array
                          print "Length of the array is:$n"; #7
                          print "\n\n";
                          EX:
                          #!/usr/bin/perl -w
                          @x=(10,20,30,40,50,60);
                          $i=0;
                          while($i<=$#x)
                          {
                          print "$x[$i]\n";
                          $i++;
                          }
                          print "\n";
                          @y=(10,20,30,40,50,60);
                          for($i=0;$i<=$#y;$i++)
                          {
                          print "$y[$i]\n";
                          }
                          print "\n";
                          @z=(10,20,30,40,50,60);
                          foreach (@z)
                          {
                          print "$_\n";
                          }
                          print "\n";
                          EX:
                          #!/usr/bin/perl -w
                          print "Enter elements to store into array at end press ctl+d:";
                          chomp(@a=<STDIN>);
                          print "Entered elements are\n";
                          foreach $x (@a)
                          {
                          print "$x \n";
                          }
                          print "\n Total no of elements:",$#a+1;
                          print "\n";

                          EX:
                          #!/usr/bin/perl -w
                          #Accept n integer elements and store into array and find sum and display
                          print "Enter no of elements:";
                          chomp($n=<STDIN>);
                          $i=0;
                          $total=0;
                          while($i<$n)
                          {
                          print "\n Enter number:",$i+1,":";
                          chomp($a[$i]=<STDIN>);
                          $total=$total+$a[$i];
                          $i++;
                          }
                          print "\n given elements are:\n";
                          print "@a\n";
                          print "\nSum of above elements:$total";
                          print "\n"
                          Hash Array Variable:
                          It is a group of key pair values
                          It should begin with % symbol
                          %variable = (list of key pairs)
                          Examples
                          %names=("hari",10000,"venkat",9500,"neeraja",8000,"sai",9800);
                          %name=("hari"=>10000,"venkat"=>9500,"neeraja"=>8000,"sai"=>9800);
                          %cities=("ap"=>"hyd","tn",=>"chennai","kn"=>"bangalore");
                          Hash Array Functions:
                          Keys:
                          It returns the given hash array keys
                          keys%hasharrayname;
                          eg: keys%cities
                          output: ap tn kn
                          Values:
                          It returns the given hash array values
                          values%hasharrayname;
                          eg: values%cities
                          output: hyd chennai bangalore
                          each:
                          It returns the given hash array one key pair value
                          each%hasharrayname
                          eg: each%cities
                          output: tn chennai
                          exists:
                          It returns true if the given key exist in the given array
                          exists%hasharrayname
                          delete:
                          It deletes the given key pair from the given hash array
                          delete $hasharrayname{key};
                          eg: delete $cities{m};
                          Ex: print-hash-array-element.pl
                          #!/usr/bin/perl -w
                          %names=("anu"=>4000,"madhu"=>8000,"latha"=>3000,"hari"=>9000,"babu"=>5000,"balu"=>4000,"anu"=>2000);
                          foreach $x (keys%names)
                          {
                          print "\n$x salary is: $names{$x}\n";
                          }
                          print "\n";
                          EX: print-hash-array-element1.pl
                          #!/usr/bin/perl -w
                          %names=("anu"=>4000,"madhu"=>8000,"latha"=>3000,"hari"=>9000,"babu"=>5000,"balu"=>4000,"anu"=>2000);
                          while(($x,$y)=(each%names))
                          {
                          print "\n$x salary is: $y\n";
                          }
                          $x=keys%names;
                          print "\n";
                          print "total no of variables:$x";
                          print "\n";
                          File Handling:
                          File:
                          It is collection of data or group of records
                          The following are functions to handle files
                          open():
                          It is used for to create a new file or to open an existing file or to append data to the existing files.
                          open(FILEHANDLE,"mode Filename");
                          FILEHANDLE is a user defined name
                          Modes are classified into 3 types
                          1. read mode (<) – Default mode

                          2. write mode (>)

                          3. append mode (>>)
                          How to open a file
                          Syn: open(FILEHANDLE,"<filename");
                          Ex: open(FH,"<sample.txt");
                          Note: In read mode if the given file exists, it opens a file and places a file pointer at the beginning of the file and returns true. If the file doesn’t exist, it fails to open file and returns false.
                          How to create a file
                          Syn:open(FILEHANDLE,">filename");
                          Ex: open(FH,">sample.txt");
                          Note: In write mode if the given file exists, it opens a file and deletes all file contents and places a file pointer at the beginning of the file. If the file doesn’t exist, it creates a new file and places file pointer at the beginning of the file.
                          How to append data to the file
                          Syn: open(FILEHANDLE,">>filename");
                          Ex: open(FH,">>sample.txt");
                          Note: In append mode if the given file exists, it opens a file and places a file pointer at the end of the file. If the file doesn’t exist, it creates a new file and places file pointer at beginning of the file.
                          close():
                          It is used for to close file, which is already opened
                          Syn: close(FILEHANDLE);
                          File Test commands:
                          -f:
                          It returns true if the given file is a regular file
                          -d:
                          It returns true if the given file is a directory file
                          -l:
                          It returns true if the given file is a link file
                          -e:
                          It returns true if the given file is exist
                          -z:
                          It returns true if the given file is empty
                          -r:
                          It returns true if the given file has read permission
                          -w:
                          It returns true if the given file has write permission
                          -x:
                          It returns true if the given file has execute permission
                          -T:
                          It returns true if the given file is a Text file
                          -B:
                          It returns true if the given file is a Binary file
                          Ex: file-existence.pl
                          #!/usr/bin/perl -w
                          #Program to check the given file exists or not
                          print "\n Enter a filename::";
                          chomp($fname=<STDIN>);
                          if(open(FH,"<$fname"))
                          {
                          print "$fname file exists\n";
                          close(FH);
                          }
                          else
                          {
                          print "\n $fname file doesn't exist\n";
                          }
                          Ex: file-existence1.pl
                          #!/usr/bin/perl -w
                          print "\n Enter a filename:";
                          chomp($fname=<STDIN>);
                          #die: Predefined function, used to terminate the program
                          #$!: It displays perl generated error message
                          die "cann't open a file. $!" unless(open(FH,"$fname"));
                          print "\n$fname file exists";
                          close(FH);
                          print "\n";
                          Ex: file-open.pl
                          #!/usr/bin/perl -w
                          #Program for opening a file
                          print "\n Enter a file name:";
                          chomp($fname=<STDIN>);
                          die "cann't open a file. $!" unless(open(FIN,"$fname"));
                          while($x=<FIN>)
                          {
                          print "$x";
                          }
                          close(FIN);
                          Ex: file-open1.pl
                          #!/usr/bin/perl -w
                          print "\n Enter a filename:";
                          chomp($fname=<STDIN>);
                          die "Can't open a file. $! unless(open(FH,"$fname"));
                          @x=<FIN>;
                          print "@x";
                          print "\n Total lines:",$#x+1;
                          close(FIN);
                          Ex: print-oddlines-from-file.pl
                          #!/usr/bin/perl -w
                          print "\nEnter a filename:";
                          chomp($fname=<STDIN>);
                          die "Cann't open a file.$!" unless(open(FIN,"$fname"));
                          $i=0;
                          while($x=<FIN>)
                          {
                          $i++;
                          next if($i%2==0);
                          print "$i.$x";
                          }
                          close(FIN);
                          Ex:
                          create-file.pl
                          #!/usr/bin/perl -w
                          print "\nEnter a filename to be created:";
                          chomp($fname=<STDIN>);
                          open(FOUT,">>$fname");
                          print "Enter data to the file and press ctl+d:";
                          while($x=<STDIN>)
                          {
                          print FOUT "$x";
                          }
                          print "**********$fname file created*********\n";
                          close(FOUT);
                          Ex: check-file-type.pl
                          #!/usr/bin/perl -w
                          print "\nEnter a file name:";
                          chomp($fname=<STDIN>);
                          if(-e $fname)
                          {
                          if(-f $fname)
                          {
                          print "\n $fname is a regular file\n";
                          }
                          elsif(-d $fname)
                          {
                          print "\n $fname is a directory\n";
                          }
                          }
                          else
                          {
                          print "\n$fname file doesn't exist\n";
                          }
                          Directory Handling
                          Directory is a collection of files
                          Directory Functions
                          opendir()
                          : It is used for to open directory
                          opendir(DIRHANDLE,"dirname");
                          ex: opendir(DH,"abc");
                          readdir():
                          It is used for to read files from given directory
                          readdir(DIRHANDLE);
                          ex: readdir(DH);
                          rewinddir():
                          It places pointer at the beginning of the given directory
                          rewinddir(DIRHANDLE);
                          ex: rewinddir(DH);
                          closedir():
                          It is used for to close the directory which is already opened
                          closedir(DIRHANDLE);
                          ex:closedir(DH);
                          mkdir():
                          To create a new directory
                          mkdir(dirname);
                          ex: mkdir("dirname");
                          chdir():
                          To change directory
                          chdir(dirname);
                          ex: chdir("abc");
                          rmdir():
                          To remove a directory
                          rmdir(dirname);
                          ex: rmdir("abc");
                          Ex:file-count.pl
                          #!/usr/bin/perl -w
                          #WAP to accept a directory and print all files and count no of file
                          print "\nEnter a directory name:";
                          chomp($dname=<STDIN>);
                          die "Can't open a directory. $!" unless(opendir(DH,"$dname"));
                          $cnt=0;
                          while($x=readdir(DH))
                          {
                          print "$x\n";
                          $cnt++;
                          }
                          print "\nTotal no of files in $dname directory: $cnt\n";
                          closedir(DH);
                          Ex:
                          dir-subdir-count.pl
                          #!/usr/bin/perl -w
                          #WAP to accept a directroy and count no of files and no of sub directories
                          print "\nEnter a directory name:";
                          chomp($dname=<STDIN>);
                          die "Can't open a directory. $!" unless(opendir(DH,"$dname"));
                          $fcnt=0;
                          $dcnt=0;
                          while($x=readdir(DH))
                          {
                          if(-f $x)
                          {
                          $fcnt++;
                          }
                          elsif(-d $x)
                          {
                          $dcnt++;
                          }
                          }
                          print "\nTotal no of files in $dname directory:$fcnt";
                          print "\nTotal no of subdirectories : $dcnt\n";
                          closedir(DH);

                          Ex: rem-directory.pl
                          #!/usr/bin/perl -w
                          #WAP to remove directory
                          print "\nEnter a dir name to remove:";
                          chomp($dname=<STDIN>);
                          rmdir($dname);
                          print "*******$dname directory has been deleted********\n";
                          Regular Expressions
                          Any string contains wild card character known as regular expression
                          Wild card characters: *, ., ?, [, ], -
                          t.*t à Regular expression
                          /t.*t/ à Pattern
                          The 2 binding operators are
                          =~ à It returns true if the given pattern found
                          !~ à It returns true if the given pattern not found
                          Wild card characters or Meta characters
                          1)* à It matches Zero or more occurrence of preceding character
                          2) + à It matches one or more occurrence of preceding character
                          3)? à It matches Zero or one occurrence of preceding character
                          4). à It matches any single character
                          5)[ ] à It matches any single character in the given list
                          6)[^] à It matches any single character other than in the given list
                          7)[-] à It matches any single character in the given range
                          8)(|) à It matches any one string in the list
                          9){m} à It matches exact occurrence of preceding character
                          10){m,n} à It matches min m occurrence and max n occurrence of its preceding character
                          11){m,} à It matches min m occurrence and max no limit of its preceding
                          12)^ à Start of the line
                          13)$ à End of the line
                          14)\d or [0-9] à Any single digit
                          [0-9] [0-9] [0-9] [0-9] or [0-9]{4} or \d\d\d\d or \d{4}
                          15)\D or [^0-9] à Any single non digit
                          16)\w or [a-zA-Z0-9_] à Any alphanumeric
                          17)\W or [^a-zA-Z0-9_] à Any non alphanumeric or special character
                          18)\s à ‘ ‘, ‘\t’, ‘\n’
                          19)\b à Word Boundary
                          Examples:
                          $str=~/perl/ à It searches the perl sting ( It will search character by character)
                          $str=~/\bperl/ à Word starting with perl
                          $str=~/perl\b/ à Word ending with perl
                          $str=~/^perl/ à Line starting with perl
                          $str=~/perl$/ à Line ending with perl
                          If($str=~/^perl$) à Line should contain only perl
                          If($str=~/^perl.*perl$/) à line starting with perl and line ending with perl
                          If($str=~/^$/) à blank lines
                          If($str=~/\b\d{4}\b/) à 4 digit number
                          If($str=~/\b\d{3,5}\b/) à searching 3 or 4 or 5 digit number
                          If($str=~/\b\w{3,5}\b/) à searching 3 or 4 or 5 digit character word
                          If($str=~/^\w+\s\w+\s\w+\s$/) à the line is having exactly 3 words
                          If($str=~/\b(2[6-9][34][0-9]5[0-5]\b/) à searching no b/w 26 to 55
                          If($str=~/\b\d{2}-\d{2}-\d{2}\b/) à 02-08-13
                          If($str=~/\b\d{2}-\d{2}-(\d{2}|\d{4}\b})\b/) à 02-08-13 or 02-08-2013
                          If($str=~m{\b\d{2}[-/]\d{2}[-/](\d[2]|\d{4})\b}) à 02-0-13 or 02-08-2-13 or 02/08/13 or 02/08/2013 or 02-05/13
                          If($str=~m{\b\d{2}([-/#])\d{2}/1(\d[2]|\d{4})\b}) à 02-0-13 or 02-08-2-13 or 02/08/13 or 02/08/2013 or 02/05/13
                          Substitution string by string
                          if($str=~s/Perl/linux/gi) à Every line all the occurrences
                          if($str=~s/^Perl/linux/gi) à Ever line first occurrence
                          if($str=~s/Perl//gi) à Replacing empty string
                          Translation character by character
                          If($str=~tr/a/t)
                          If($str=~tr/am/tp)
                          If($str=~tr/[a-z]/[A-Z]/)
                          PERL Predefined Functions
                          String Functions
                          1)ord():
                          It returns given character ASCII value
                          Print ord(‘a’); #97
                          Print ord(‘A’); #65
                          2)chr():
                          It returns given ASCII code character
                          Print chr(65); #A
                          Print chr(97); #a
                          3)uc():
                          It returns the given string in upper case
                          Print uc("pavan"); #PAVAN
                          4)lc():
                          It returns the given string in lower case
                          Print lc("PAVAN") #pavan
                          5)ucfirst():
                          It returns the given sting first character into upper case
                          Print ucfirst("pavan") #Pavan
                          6)lcfirst():
                          It returns the given string character into lower case
                          Print lcfirst("PAVAN") #pAVAN
                          7)length():
                          It returns the length of the given string
                          Print length("pavan") #5
                          8)substr("string,start,length) :
                          It extracts the specified portion from the string
                          Print substr("I like Perl",4,5); #ke pe
                          9) index(mainstring,substring):
                          It returns position of the substring in main string,
                          if substring not found in main string, it returns -1
                          print index("I like perl","perl"); #7
                          print index("I like perl","unix"); #-1
                          10) chop():
                          It deletes the given string last character
                          $str="I like perl";
                          chop($str);
                          print $str; #i like per
                          11) split():
                          It is used for to split the string into multiple values based on one or more delimiters.
                          $str="This is perl scripting class";
                          @x=split(" ",$str);
                          print "total elements:",$#x+1;
                          $str="This is,perl scripting:class";
                          @x=split(",| |:",$str);
                          Print "\n Total elements: ",$#x+1;
                          12) join():
                          It is used for to join multiple values into single string based on delimiter @num=(10,20,30,40,50,60);
                          $x=join(":",@num);
                          Print "$x"; #10:20:30:40:50:60
                          Array Functions:
                          1. push() :
                          it adds elements at end of the array
                          @x=(10,20,30,40);
                          Push(@x,50,60,70);
                          Print "@x"; # 10 20 30 40 50 60 70
                        6. unshift():
                        7. it adds elements at beginning of the array
                          @x=(10,20,30,40);
                          unshift(@x,50,60,70);
                          Print "@x"; 50 60 70 10 20 30 40
                        8. pop():
                        9. it returns and deletes last element from the array
                          @x=(10,20,30,40);
                          $k=pop(@x);
                          Print "The deleted element is : $k"; #40
                          Print "@x"; # 10 20 30
                        10. shift():
                        11. it returns and deletes first element from the array
                          @x=(10,20,30,40);
                          $k = shift(@x);
                          Print "The deleted element is : $k"; #10
                          Print "@x"; #20 30 40
                        12. sort():
                        13. it sorts given array elements in asc order
                          @x=qw(one two three four five);
                          @y=sort(@x);
                          Print "@y"; #five four one three two
                          Print "@x"; #one two three four five
                        14. reverse():
                        15. It returns elements last first from the given array
                          @x=qw(one two three four five);
                          @y=reverse(@x);
                          Print "@y"; #five four three two one
                          Print "@x"; #one two three four five
                          reverse(sort(@x));
                        16. splice():
                        17. It is used for to replace particular portion from the array or to append elements at end of the array
                          splice(@oldarray,start,length,@newarray)
                          @x=qw( a b c d e f);
                          @num=(1,2,3,4);
                          splice(@x,2,3,@num);
                          print "@x"; #a b 1 2 3 4 f
                          splice(@x,2,0,@num);
                          print "@x"; #a b 1 2 3 4 c d e f
                          splice(@x,2,3)
                          print "@x"; #a b f
                          Mathematical Functions
                          1. abs():
                          it returns absolute value
                          print abs(-45);#45
                        18. sqrt():
                        19. it returns square root of the given number
                          print sqrt(100); #10
                          print sqrt(abs(-100)); #10
                        20. rand:
                        21. it returns random number between 0 to 1
                        22. rand(n)
                        23. : it returns random number between 0 to n
                        24. sin(x):
                        25. it returns sin value
                        26. cos(x):
                        27. it returns cos value
                        28. tan(x):
                        29. it returns tan value
                        30. log(x):
                        31. it returns log value
                          Date and Time Functions
                          localtime():
                          it returns date and time
                          Sub Routines or User defined functions
                          Function is a group of statements to perform certain task and it must return a value. The main concept of function is to reduce length code of the program, easy to maintain, supports reusability, reduces cost of maintenance.
                          Syntax:
                          &functionname(arg1,arg2,……); ---- > Calling Function
                          -----------
                          -----------
                          -----------
                          -----------
                          Sub funcationname ---- > called function or defining function
                          {
                          -----------
                          -----------
                          -----------
                          -----------
                          }
                          @_ is a special variable; it holds all function call arguments
                          Example 1:
                          sub hello
                          {
                          print "\n , hello, good evening";
                          }
                          hello;
                          print "\n bye, have a nice day";
                          Example 2:
                          &hello; #forward reference
                          hello;
                          print "\n bye, have a nice day";
                          sub hello
                          {
                          Print "\n hello, good evening";
                          }
                          Example 3:
                          display("hello","good","evening");
                          sub display
                          {
                          Print "Total no of args:", $#_+1;
                          Print "\n @_";
                          }
                          Example 4:
                          sum(10,20,30);
                          sub sum
                          {
                          ($x,$y)=@_;
                          Print "\n sum=$n";
                          }
                          Example 5:
                          sum(10,20);
                          sub sum
                          {
                          $x=$_[0];
                          $y=$_[1];
                          $n=$x+$y;
                          Print "\n sum=$n";
                          }
                          Example 6:
                          sum(10,20);
                          sub sum
                          {
                          $x=shift(@_);
                          $y=shift(@_);
                          $n=$x+$y;
                          Print "\n sum =$n";
                          }
                          Example 7:
                          $n=&sum(10,20,30);
                          Print "\n sum1 = $n";
                          $n=$sum(10,20,30,40,50,60,70);
                          Print "\n sum2= &n";
                          sub sum
                          {
                          $total=0;
                          foreach $k (@_)
                          {
                          $total=$total+$k;
                          }
                          Return $total;
                          }
                          Example 8:
                          %days=("mon"=>1,"tue"=2,"wed"=>3,"thu"=>4,"fri"=>5);
                          &display(%days,"sat",6,"sun",7);
                          sub display
                          {
                          %h=@_;
                          while($x,$y)=each%h)
                          {
                          Print "\n $x week day no is : $y";
                          }
                          }
                          Example 9:
                          sub sum($\$); #prototype declaration
                          $a=10;
                          $b=20;
                          @x=(10,20,30,40,50);
                          sum($a,$b); #calling function
                          #sum($a); - wrong
                          #sum($a,$b,30,40); - wrong
                          #sum($a,@x); - wrong
                          sub sum($/$) # prototype declaration
                          {
                          $x=$_[0];
                          $y=$_[1];
                          $n=$x+$y;
                          print "\n sum=$n";
                          }

                          Scope of variables
                          1)our
                          2)my
                          3)local
                          The default scope is our scope.
                          The our scope variables can be accessed any where in the program
                          The my scope variables can be accessed within that block only.
                          The local scope variable can be accessed within that function and it child functions
                          Example 1:
                          $x=100;
                          &f1();
                          &f2();
                          Print "\n In main, x=$x, y=$y,z=$z"; # 110,empty,empty
                          sub f1
                          {
                          my $y=200;
                          local $z=300;
                          print "\n In f1, x=$x, y=$y,z=$z"; # 100,200,300
                          $x=$x+10;
                          &f3();
                          }
                          sub f3
                          {
                          print "\n In f3, x=$x, y=$y,z=$z"; # 110,empty,300
                          &f2();
                          }
                          sub f2
                          {
                          print "\n In f2, x=$x, y=$y,z=$z"; # 100,empty,empty
                          }
                          Example 2:
                          use strict; #It forces the user to declare variables explicitly
                          use warnings;
                          our $count=1;
                          our $x=10;
                          while($count<=3)
                          {
                          print "$x \n";
                          $x=$x+10;
                          $count=$count+1;
                          }

                          Command line arguments
                          At the time of execution of perl script, if user passes any arguments known as command line arguments. @ARGV is a special variable, it holds all command line argument values
                          Example 1:
                          #perl hello.pl pavan kumar Bangalore
                          print "\n Total no of Args:",$#ARGV+1;
                          Example 2:
                          #perl sum.pl 10 20
                          $n=@ARGV;
                          if($n= =2)
                          {
                          my($a,$b)=@ARGV;
                          my $c=$a+$b;
                          print "\n sum: $c";
                          }
                          else
                          {
                          print "\n Invalid Arguments";
                          }
                          Example 3:
                          #perl copy.pl sample.txt temp.txt
                          $n=@ARGV;
                          if($n= =2)
                          {
                          $src=$ARGV[0];
                          $tar=$ARGV[1];
                          die "can’t open a source file. $!" unless(open(FIN,"<$src"));
                          open(FOUT,">$tar");
                          while($str=<FIN>)
                          {
                          print FOUT "$str";
                          }
                          print "\n File copied successfully";
                          close(FIN);
                          close(FOUT);
                          }
                          else
                          {
                          Print "Invalid no of Arguments";
                          }
                          Modules:
                          Module is a collection of properties (variables, methods, functions)
                          1. pakage is a keyword to create a module

                          2. pakage name and module name must be same

                          3. extension of the perl module is .pm

                          4. the perl module must register in perl/site/lib directory

                          5. module must return a true value

                          6. main concept is reusability

                          7. use and require are the keywords to import perl modules

                          8. use keyword imports perl module properties and methods at compile time

                          9. require keyword imports perl modules and methods at runtime
                          How to access perl properties and methods
                          <Module name>::<Method name>
                          Or
                          <Module name>;
                          $object_name=new
                          $object_nameà Method name

                          Saturday, 22 June 2013

                          Log4J Levels

                          Five standard log4j levels

                          DEBUG Level

                          This log4j level helps developer to debug application. Level of message logged will be focused on providing support to a application developer.

                          INFO Level

                          This log4j level gives the progress and chosen state information. This level will be generally useful for end user. This level is one level higher than DEBUG.

                          WARN Level

                          This log4j level gives a warning about an unexpected event to the user. The messages coming out of this level may not halt the progress of the system.

                          ERROR Level

                          This log4j level gives information about a serious error which needs to be addressed and may result in unstable state. This level is one level higher than WARN.

                          FATAL Level

                          This log4j level is straightforward and you don’t get it quite often. Once you get this level and it indicates application death.

                          Two special log4j levels

                          ALL Level

                          This log4j level is used to turn on all levels of logging. Once this is configured and the levels are not considered.

                          OFF Level

                          This log4j level is opposite to ALL level. It turns off all the logging.

                          New Trace Level added in Log4j

                          TRACE Level

                          This log4j level gives more detailed information than the DEBUG level and sits top of the hierarchy. This level is introduced from version 1.2.12 in log4j.

                          Custom log4j levels

                          Log4j’s levels are mostly sufficient for all common applications. Rarely you may need a new Level apart from the levels provided by log4j. In that case you can extend org.apache.log4j.Level class and have your own custom level implementation.

                          Log4j Logger Output

                          When a logger is created, generally you assign a level. The logger outputs all those messages equal to that level and also all greater levels than it. So the order for the standard log4j levels are:

                          Log4J Levels

                          TRACE Level DEBUG Level INFO Level WARN Level ERROR Level FATAL Level
                          TRACE Level Y Y Y Y Y Y
                          DEBUG Level N Y Y Y Y Y
                          INFO Level N N Y Y Y Y
                          WARN Level N N N Y Y Y
                          ERROR Level N N N N Y Y
                          FATAL Level N N N N N Y
                          ALL Level Y Y Y Y Y Y
                          OFF Level N N N N N N

                          Log4j Level Inheritance Rule

                          There can be instances when you don’t assign a level to the logger. In such cases log4j handles it seamlessly based on the following level inheritance rule:
                          The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.
                          That means, if you have a package as com.foo.bar and you didn’t allocate a level, then it will inherit the level from com.foo package. Still in that package also if the level is not available, then it will inherit from the log4j root level. The log4j’s root logger is instantiated and available always. Log4j’s root logger by default has DEBUG level.

                          Apache Redirects


                          Overview

                          What you are trying to accomplish here is to have one resource (either a page or an entire site) redirect a visitor to a completely different page or site, and while doing so tell the visitor's browser that the redirect is either permanent (301) or temporary (302).
                          Therefore you need to do three things:
                          1. Have 2 resources - one source page or website, and one destination page or website.
                          2. When an attempt to  access the source resource is made, the webserver transfers the visitor to the destination instead.
                          3. During the transfer, the webserver reports to the visitor that a redirect is happening and it's either temporary or permanent.
                          The ability to control the "status" argument in the redirect directive (which sets whether it's a 301 or 302) within Apache is only available in version 1.2 and above. You are best off using version 2 or above for maximum stability, security and usefulness. 

                          301 Redirect
                          A function of a web server that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been permanently moved to the new location. Search engines like this information and will readily transfer link popularity (and PageRank) to the new site quickly and with few issues. They are also not as likely to cause issues with duplication filters. SEOs like 301 redirects, and they are usually the preferred way to deal with multiple domains pointing at one website.
                          302 Redirect
                          A function of a web server that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been temporarily moved to the new location. Search engines will often interpret these as a park, and take their time figuring out how to handle the setup. Try to avoid a 302 redirect on your site if you can (unless it truly is only a temporary redirect), and never use them as some form of click tracking for your outgoing links, as they can result in a "website hijacking" under some circumstances.
                           
                          mod_rewrite
                          Mod_Rewrite is an Apache extension module which will allow URL's to be rewritten on the fly. Often this is used by SEOs to convert dynamic URL's with multiple query strings into static URL's. An example of this would be to convert the dynamic URL domain.com/search.php?day=31&month=may&year=2005 to domain.com/search-31-may-2005.htm
                           
                          htaccess
                          htaccess (Hypertext Access) is the default name of Apache's directory-level configuration file. It provides the ability to customize configuration directives defined in the main configuration file. You can execute a mod_rewrite script using the .htaccess file.
                           
                          httpd.conf
                          Apache is configured by placing directives in plain text configuration files. The main configuration file is usually called httpd.conf. The location of this file is set at compile-time, but may be overridden with the -f command line flag. In addition, other configuration files may be added using the Include directive, and wildcards can be used to include many configuration files. Any directive may be placed in any of these configuration files. Changes to the main configuration files are only recognized by Apache when it is started or restarted.

                          Redirection (302)
                          A default redirection function of IIS that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been temporarily moved to the new location. Search engines will often interpret these as a park, and take their time figuring out how to handle the setup. Try to avoid a 302 redirect on your site if you can (unless it truly is only a temporary redirect), and never use them as some form of click tracking for your outgoing links, as they can result in a "website hijacking" under some circumstances.
                           
                           Permanent Redirection (301)
                          An optional function of IIS that redirects the visitor from the current page or site to another page or site, while returning a response code that says that the original page or site has been permanently moved to the new location. Search engines like this information and will readily transfer link popularity (and PageRank) to the new site quickly and with few issues. They are also not as likely to cause issues with duplication filters. SEOs like 301 redirects, and they are usually the preferred way to deal with multiple domains pointing at one website.

                          Mod_Rewrite and the Apache Redirect

                          If you have the mod_rewrite extension installed (it comes with most Apache installs as a default) you can use it to dynamically change URL's using arguments on the fly - this is NOT a 301 redirect, but rather it's related behavior. For example, if you wanted to redirect .htm files from an old server to their equivalent .php files on a new one using a 301 redirect, you would use a combination of mod_rewrite and the redirect directive to do the redirection + URL change.
                          You could do it on a file by file basis by making a really long list of possible redirects in the .htaccess file by hand without mod_rewrite, but that would be a real pain on a server with a lot of files, or a completely dynamic system. Therefore these 2 functions are often used together.

                          Syntax for a 301 Redirect

                          The syntax for the redirect directive is:
                          Redirect /yourdirectory http://www.newdomain.com/newdirectory
                          If the client requests http://myserver/service/foo.txt, it will be told to access http://www.yourdomain.com/service/foo.txt instead.
                          Note: Redirect directives take precedence over Alias and ScriptAlias directives, irrespective of their ordering in the configuration file. Also, URL-path must be a fully qualified URL, not a relative path, even when used with .htaccess files or inside of <Directory> sections.
                          If you use the redirect without the status argument, it will return a status code of 302 by default. This default behaviour has given me problems over the years as an SEO, so it's important to remember to use it, like this:
                          Redirect permanent /one http://www.newdomain.com/two
                          or
                          Redirect 301 /two http://www.newdomain.com/other
                          Both of which will return the 301 status code. If you wanted to return a 302 you could either not specify anything, or use "302" or "temp" as the status argument above.
                          You can also use 2 other directives - RedirectPermanent URL-path URL (returns a 301 and works the same as Redirect permanent /URL PathURL) and RedirectTemp URL-path URL (same, but for a 302 status).
                          For more global changes, you would use redirectMatch, with the same syntax:
                          RedirectMatch 301 ^(.*)$ http://www.newdomain.com
                          or
                          RedirectMatch permanent ^(.*)$ http://www.newdomain.com
                          These arguments will match any file requested at the old account, change the domain, and redirect it to the file of the same name at the new account.
                          You would use these directives in either the .htaccess file or the httpd file. It's most common to do it in the .htaccess file because it's the easiest and doesn't require a restart, but the httpd method has less overhead and works fine, as well.

                          Simple Domain 301 Redirect Checklist

                          This assumes you just have a new domain (with no working pages under it) and want it to redirect properly to your main domain.
                          1. Ensure that you have 2 accounts - the old site and the new site (they do not have to be on different IP's or different machines).
                          2. Your main (proper or canonical) site should be pointed at the new site using DNS. All your other domains should be pointed at the old site using DNS. Parking them there is fine at this point.
                          3. Find the .htaccess file at the root of your old account. Yes, it starts with a "." We will be working with this file. The new site does not need any changes made to it - the old site does all the redirection work.
                          4. Download the .htaccess file and open it in a text only editor.
                          5a. Add this code:
                          Redirect 301 / http://www.newdomain.com/
                          6. Then upload the file to your root folder and test your new redirect. Make you you also check it using a HTTP Header viewer just to be sure it shows as a 301.

                          Control Panel Method

                          cPanel redirect

                          • Log into your cPanel, and look for "Redirects" under Site Management
                          • Put in the current directory into the first box
                          • Put the new directory in the second box
                          • Choose the type (temporary or permanent) temporary=302 and permanent=301
                          • Click "Add" and you're done
                          You can only do 302 redirects (or frame forwarding - bad!) using the Plesk control panel - use .htaccess for 301's instead.
                          If you use Ensim, the only way to redirect is by using the .htaccess file (no control panel option at this time).

                          Basic Old Website to New Website Redirection

                          This is used when you have an existing website (with pages) and want to move it to a new domain, while keeping all your page names and the links to them.
                          1. Ensure that you have 2 websites - the old site and the new site, and that they are on different accounts (they do not have to be on different IP's or different machines).
                          2. Your main (proper or canonical) site should be pointed at the new site using DNS. All your old domains should be pointed at the old site using DNS.
                          3. Find the .htaccess file at the root of your old account. Yes, it starts with a "."  We will be working with this file. The new site does not need any changes made to it - the old site does all the redirection work.
                          4. Download the .htaccess file and open it in a text only editor.
                          5a. If you have mod_rewrite installed, add this code:
                          Options +FollowSymLinks
                          RewriteEngine on
                          RewriteCond %{HTTP_HOST} !^newdomain\.com
                          RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
                          5b. If you don't have mod_rewrite installed, you really should. If you can't install it, then you can use this code instead:
                          RedirectMatch 301 ^(.*)$ http://www.newdomain.com
                          6. Then upload the file to your root folder and test your new redirect. Make you you also check it using a HTTP Header viewer just to be sure it shows as a 301.

                          FrontPage on Apache

                          After you've done the basic Apache 301 redirection described in this article, you will also need to change the .htaccess files in:  
                          _vti_bin
                          _vti_bin /_vti_adm
                          _vti_bin/ _vti_aut
                          Replace "Options None" to "Options +FollowSymLinks"
                          Those folders are part of your FrontPage extensions on the server, so you will have to use FTP to get to them, since FrontPage hides these folders by default to prevent them from accidentally being messed with by novice users.

                          More Complicated Redirects

                          You can't use a control panel in Apache currently for these - .htaccess only.

                          Redirecting everything to a single page

                          This is common when you are totally changing the new website from the old and you just want all your links and requests form the old site to be directed to a spot on your new site (usually the home page). You actually need to do it on a page by page basis.
                          Redirect 301 /oldfile1.htm http://www.newdomain.com
                          Redirect 301 /oldfile2.htm http://www.newdomain.com
                          Redirect 301 /oldfile3.htm http://www.newdomain.com

                          Redirection while changing the filename

                          This example will redirect all the files on the old account that end in html to the same file on the new account, but with a php extension. You can also use this technique within the same account if you want to change all your extensions but don't want to lose your incoming links to the old pages. This is common when people switch to from static htm files to dynamic ones while keeping the same domain name, for example.
                          Just change the "html" and "php" parts of the below example to your specific situation, if needed.
                          RedirectMatch 301 (.*)\.html$ http://www.newdomain.com$1.php

                          Redirection while changing the filename, but keeping the GET arguments

                          Sometimes, you will want to change to a different CMS, but keep your database the same, or you want to switch everything but you like the arguments and don't want to change them.
                          RedirectMatch 301 /oldcart.php(.*) http://www.newdomain.com/newcart.php$1
                          This will result in "http://www.olddomain.com/oldcart.php?Cat_ID=Blue" being redirected to "http://www.newdomain.com/newcart.php?Cat_ID=Blue"

                          .htaccess Error Documents


                          In Apache, you can set up each directory on your server individually, giving them different properties or requirements for access. And while you can do this through normal Apache configuration, some hosts may wish to give users the ability to set up their own virtual server how they like. And so we have .htaccess files, a way to set Apache directives on a directory by directory basis without the need for direct server access, and without being able to affect other directories on the same server.

                          One up-side of this (amongst many) is that with a few short lines in an .htaccess file, you can tell your server that, for example, when a user asks for a page that doesn't exist, they are shown a customized error page instead of the bog-standard error page they've seen a million times before. If you visit http://www.addedbytes.com/random_made_up_address then you'll see this in action - instead of your browser's default error page, you see an error page sent by my server to you, telling you that the page you asked for doesn't exist.

                          This has a fair few uses. For example, my 404 (page not found) error page also sends me an email whenever somebody ends up there, telling me which page they were trying to find, and where they came from to find it - hopefully, this will help me to fix broken links without needing to trawl through mind-numbing error logs.

                          [Aside: If you set up your custom error page to email you whenever a page isn't found, remember that "/favicon.ico" requests failing doesn't mean that a page is missing. Internet Explorer 5 assumes everyone has a "favicon" and so asks the server for it. It's best to filter error messages about missing "/favicon.ico" files from your error logging, if you plan to do any.]

                          Setting up your htaccess file is a piece of cake. First things first, open notepad (or better yet, [url=http://www.editplus.com/]EditPlus2[/url]), and add the following to a new document:
                          ErrorDocument 404     /404.html

                          Next you need to save the file. You need to save it as ".htaccess". Not ".htaccess.txt", or "mysite.htaccess" - just ".htaccess". I know it sounds strange, but that is what these files are - just .htaccess files. Nothing else. Happy? If not, take a look at this [url=http://wsabstract.com/howto/htaccess.shtml].htaccess guide[/url], which also explains the naming convention of .htaccess in a little more depth. If you do use Notepad, you may need to rename the file after saving it, and you can do this before or after uploading the file to your server.

                          Now, create a page called 404.html, containing whatever you want a visitor to your site to see when they try to visit a page that doesn't exist. Now, upload both to your website, and type in a random, made-up address. You should, with any luck, see your custom error page instead of the traditional "Page Not Found" error message. If you do not see that, then there is a good chance your server does not support .htaccess, or it has been disabled. I suggest the next thing you do is check quickly with your server administrator that you are allowed to use .htaccess to serve custom error pages.

                          If all went well, and you are now viewing a custom 404 (page not found) error page, then you are well on your way to a complete set of error documents to match your web site. There are more errors out there, you know, not just missing pages. Of course, you can also use PHP, ASP or CFML pages as error documents - very useful for keeping track of errors.

                          You can customize these directives a great deal. For example, you can add directives for any of the status codes below, to show custom pages for any error the server may report. You can also, if you want, specify a full URL instead of a relative one. And if you are truly adventurous, you could even use pure HTML in the .htaccess file to be displayed in case of an error, as below. Note that if you want to use HTML, you must start the HTML with a quotation mark, however you should not put one at the other end of the HTML (you can include quotation marks within the HTML itself as normal).
                          ErrorDocument 404 "Ooops, that page was <b>not found</b>. Please try a different one or <a href="mailto:owner@site.com">email the site owner</a> for assistance.
                          Server response codes

                          A server reponse code is a three digit number sent by a server to a user in response to a request for a web page or document. They tell the user whether the request can be completed, or if the server needs more information, or if the server cannot complete the request. Usually, these codes are sent 'silently' - so you never see them, as a user - however, there are some common ones that you may wish to set up error pages for, and they are listed below. Most people will only ever need to set up error pages for server codes 400, 401, 403, 404 and 500, and you would be wise to always have an error document for 404 errors at the very least.

                          It is also relatively important to ensure that any error page is over 512 bytes in size. Internet Explorer 5, when sent an error page of less than 512 bytes, will display its own default error document instead of your one. Feel free to use padding if this is an issue - personally, I'm not going to increase the size of a page because Internet Explorer 5 doesn't behave well.

                          In order to set up an error page for any other error codes, you simply add more lines to your .htaccess file. If you wanted to have error pages for the above five errors, your .htaccess file might look something like this:
                          ErrorDocument 400     /400.html
                          ErrorDocument 401     /401.html
                          ErrorDocument 403     /403.html
                          ErrorDocument 404     /404.html 
                          ErrorDocument 500     /500.html

                          HTTP Status Codes

                          Informational
                              100 - Continue
                              A status code of 100 indicates that (usually the first) part of a request has been received without any problems, and that the rest of the request should now be sent.
                              101 - Switching Protocols
                              HTTP 1.1 is just one type of protocol for transferring data on the web, and a status code of 101 indicates that the server is changing to the protocol it defines in the "Upgrade" header it returns to the client. For example, when requesting a page, a browser might receive a statis code of 101, followed by an "Upgrade" header showing that the server is changing to a different version of HTTP.

                          Successful

                              200 - OK
                              The 200 status code is by far the most common returned. It means, simply, that the request was received and understood and is being processed.
                              201 - Created
                              A 201 status code indicates that a request was successful and as a result, a resource has been created (for example a new page).
                              202 - Accepted
                              The status code 202 indicates that server has received and understood the request, and that it has been accepted for processing, although it may not be processed immediately.
                              203 - Non-Authoritative Information
                              A 203 status code means that the request was received and understood, and that information sent back about the response is from a third party, rather than the original server. This is virtually identical in meaning to a 200 status code.
                              204 - No Content
                              The 204 status code means that the request was received and understood, but that there is no need to send any data back.
                              205 - Reset Content
                              The 205 status code is a request from the server to the client to reset the document from which the original request was sent. For example, if a user fills out a form, and submits it, a status code of 205 means the server is asking the browser to clear the form.
                              206 - Partial Content
                              A status code of 206 is a response to a request for part of a document. This is used by advanced caching tools, when a user agent requests only a small part of a page, and just that section is returned.

                          Redirection

                              300 - Multiple Choices
                              The 300 status code indicates that a resource has moved. The response will also include a list of locations from which the user agent can select the most appropriate.
                              301 - Moved Permanently
                              A status code of 301 tells a client that the resource they asked for has permanently moved to a new location. The response should also include this location. It tells the client to use the new URL the next time it wants to fetch the same resource.
                              302 - Found
                              A status code of 302 tells a client that the resource they asked for has temporarily moved to a new location. The response should also include this location. It tells the client that it should carry on using the same URL to access this resource.
                              303 - See Other
                              A 303 status code indicates that the response to the request can be found at the specified URL, and should be retrieved from there. It does not mean that something has moved - it is simply specifying the address at which the response to the request can be found.
                              304 - Not Modified
                              The 304 status code is sent in response to a request (for a document) that asked for the document only if it was newer than the one the client already had. Normally, when a document is cached, the date it was cached is stored. The next time the document is viewed, the client asks the server if the document has changed. If not, the client just reloads the document from the cache.
                              305 - Use Proxy
                              A 305 status code tells the client that the requested resource has to be reached through a proxy, which will be specified in the response.
                              307 - Temporary Redirect
                              307 is the status code that is sent when a document is temporarily available at a different URL, which is also returned. There is very little difference between a 302 status code and a 307 status code. 307 was created as another, less ambiguous, version of the 302 status code.

                          Client Error

                              400 - Bad Request
                              A status code of 400 indicates that the server did not understand the request due to bad syntax.
                              401 - Unauthorized
                              A 401 status code indicates that before a resource can be accessed, the client must be authorised by the server.
                              402 - Payment Required
                              The 402 status code is not currently in use, being listed as "reserved for future use".
                              403 - Forbidden
                              A 403 status code indicates that the client cannot access the requested resource. That might mean that the wrong username and password were sent in the request, or that the permissions on the server do not allow what was being asked.
                              404 - Not Found
                              The best known of them all, the 404 status code indicates that the requested resource was not found at the URL given, and the server has no idea how long for.
                              405 - Method Not Allowed
                              A 405 status code is returned when the client has tried to use a request method that the server does not allow. Request methods that are allowed should be sent with the response (common request methods are POST and GET).
                              406 - Not Acceptable
                              The 406 status code means that, although the server understood and processed the request, the response is of a form the client cannot understand. A client sends, as part of a request, headers indicating what types of data it can use, and a 406 error is returned when the response is of a type not i that list.
                              407 - Proxy Authentication Required
                              The 407 status code is very similar to the 401 status code, and means that the client must be authorised by the proxy before the request can proceed.
                              408 - Request Timeout
                              A 408 status code means that the client did not produce a request quickly enough. A server is set to only wait a certain amount of time for responses from clients, and a 408 status code indicates that time has passed.
                              409 - Conflict
                              A 409 status code indicates that the server was unable to complete the request, often because a file would need to be editted, created or deleted, and that file cannot be editted, created or deleted.
                              410 - Gone
                              A 410 status code is the 404's lesser known cousin. It indicates that a resource has permanently gone (a 404 status code gives no indication if a resource has gine permanently or temporarily), and no new address is known for it.
                              411 - Length Required
                              The 411 status code occurs when a server refuses to process a request because a content length was not specified.
                              412 - Precondition Failed
                              A 412 status code indicates that one of the conditions the request was made under has failed.
                              413 - Request Entity Too Large
                              The 413 status code indicates that the request was larger than the server is able to handle, either due to physical constraints or to settings. Usually, this occurs when a file is sent using the POST method from a form, and the file is larger than the maximum size allowed in the server settings.
                              414 - Request-URI Too Long
                              The 414 status code indicates the the URL requested by the client was longer than it can process.
                              415 - Unsupported Media Type
                              A 415 status code is returned by a server to indicate that part of the request was in an unsupported format.
                              416 - Requested Range Not Satisfiable
                              A 416 status code indicates that the server was unable to fulfill the request. This may be, for example, because the client asked for the 800th-900th bytes of a document, but the document was only 200 bytes long.
                              417 - Expectation Failed
                              The 417 status code means that the server was unable to properly complete the request. One of the headers sent to the server, the "Expect" header, indicated an expectation the server could not meet.

                          Server Error

                              500 - Internal Server Error
                              A 500 status code (all too often seen by Perl programmers) indicates that the server encountered something it didn't expect and was unable to complete the request.
                              501 - Not Implemented
                              The 501 status code indicates that the server does not support all that is needed for the request to be completed.
                              502 - Bad Gateway
                              A 502 status code indicates that a server, while acting as a proxy, received a response from a server further upstream that it judged invalid.
                              503 - Service Unavailable
                              A 503 status code is most often seen on extremely busy servers, and it indicates that the server was unable to complete the request due to a server overload.
                              504 - Gateway Timeout
                              A 504 status code is returned when a server acting as a proxy has waited too long for a response from a server further upstream.
                              505 - HTTP Version Not Supported
                              A 505 status code is returned when the HTTP version indicated in the request is no supported. The response should indicate which HTTP versions are supported.

                          Apache URL rewriting

                          Best guide around -- http://httpd.apache.org/docs/2.0/misc/rewriteguide.html  
                           
                          What is "URL Rewriting"?


                          Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7.
                          http://www.pets.com/show_a_product.php?product_id=7

                          The problems with this kind of URL structure are that the URL is not at all memorable. It's difficult to read out over the phone (you'd be surprised how many people pass URLs this way). Search engines and users alike get no useful information about the content of a page from that URL. You can't tell from that URL that that page allows you to buy a Norwegian Blue Parrot (lovely plumage). It's a fairly standard URL - the sort you'd get by default from most CMSes. Compare that to this URL:
                          http://www.pets.com/products/7/

                          Clearly a much cleaner and shorter URL. It's much easier to remember, and vastly easier to read out. That said, it doesn't exactly tell anyone what it refers to. But we can do more:
                          http://www.pets.com/parrots/norwegian-blue/

                          Now we're getting somewhere. You can tell from the URL, even when it's taken out of context, what you're likely to find on that page. Search engines can split that URL into words (hyphens in URLs are treated as spaces by search engines, whereas underscores are not), and they can use that information to better determine the content of the page. It's an easy URL to remember and to pass to another person.

                          Unfortunately, the last URL cannot be easily understood by a server without some work on our part. When a request is made for that URL, the server needs to work out how to process that URL so that it knows what to send back to the user. URL rewriting is the technique used to "translate" a URL like the last one into something the server can understand.
                          Platforms and Tools

                          Depending on the software your server is running, you may already have access to URL rewriting modules. If not, most hosts will enable or install the relevant modules for you if you ask them very nicely.

                          Apache is the easiest system to get URL rewriting running on. It usually comes with its own built-in URL rewriting module, mod_rewrite, enabled, and working with mod_rewrite is as simple as uploading correctly formatted and named text files.

                          IIS, Microsoft's server software, doesn't include URL rewriting capability as standard, but there are add-ons out there that can provide this functionality. ISAPI_Rewrite is the one I recommend working with, as I've so far found it to be the closest to mod_rewrite's functionality. Instructions for installing and configuring ISAPI_Rewrite can be found at the end of this article.

                          The code that follows is based on URL rewriting using mod_rewrite.
                          Basic URL Rewriting

                          To begin with, let's consider a simple example. We have a website, and we have a single PHP script that serves a single page. Its URL is:
                          http://www.pets.com/pet_care_info_07_07_2008.php

                          We want to clean up the URL, and our ideal URL would be:
                          http://www.pets.com/pet-care/

                          In order for this to work, we need to tell the server to internally redirect all requests for the URL "pet-care" to "pet_care_info_07_07_2008.php". We want this to happen internally, because we don't want the URL in the browser's address bar to change.

                          To accomplish this, we need to first create a text document called ".htaccess" to contain our rules. It must be named exactly that (not ".htaccess.txt" or "rules.htaccess"). This would be placed in the root directory of the server (the same folder as "pet_care_info_07_07_2008.php" in our example). There may already be an .htaccess file there, in which case we should edit that rather than overwrite it.

                          The .htaccess file is a configuration file for the server. If there are errors in the file, the server will display an error message (usually with an error code of "500"). If you are transferring the file to the server using FTP, you must make sure it is transferred using the ASCII mode, rather than BINARY. We use this file to perform 2 simple tasks in this instance - first, to tell Apache to turn on the rewrite engine, and second, to tell apache what rewriting rule we want it to use. We need to add the following to the file:
                          RewriteEngine On # Turn on the rewriting engine 
                          RewriteRule ^pet-care/?$ pet_care_info_01_02_2008.php [NC,L] # Handle requests for "pet-care"

                          A couple of quick items to note - everything following a hash symbol in an .htaccess file is ignored as a comment, and I'd recommend you use comments liberally; and the "RewriteEngine" line should only be used once per .htaccess file (please note that I've not included this line from here onwards in code example).

                          The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:

                              RewriteRule - Tells Apache that this like refers to a single RewriteRule.
                              ^/pet-care/?$ - The "pattern". The server will check the URL of every request to the site to see if this pattern matches. If it does, then Apache will swap the URL of the request for the "substitution" section that follows.
                              pet_care_info_01_02_2003.php - The "substitution". If the pattern above matches the request, Apache uses this URL instead of the requested URL.
                              [NC,L] - "Flags", that tell Apache how to apply the rule. In this case, we're using two flags. "NC", tells Apache that this rule should be case-insensitive, and "L" tells Apache not to process any more rules if this one is used.
                              # Handle requests for "pet-care" - Comment explaining what the rule does (optional but recommended)

                          The rule above is a simple method for rewriting a single URL, and is the basis for almost all URL rewriting rules.
                          Patterns and Replacements

                          The rule above allows you to redirect requests for a single URL, but the real power of mod_rewrite comes when you start to identify and rewrite groups of URLs based on patterns they contain.

                          Let's say you want to change all of your site URLs as described in the first pair of examples above. Your existing URLs look like this:
                          http://www.pets.com/show_a_product.php?product_id=7

                          And you want to change them to look like this:
                          http://www.pets.com/products/7/

                          Rather than write a rule for every single product ID, you of course would rather write one rule to manage all product IDs. Effectively you want to change URLs of this format:
                          http://www.pets.com/show_a_product.php?product_id={a number}

                          And you want to change them to look like this:
                          http://www.pets.com/products/{a number}/

                          In order to do so, you will need to use "regular expressions". These are patterns, defined in a specific format that the server can understand and handle appropriately. A typical pattern to identify a number would look like this:
                          [0-9]+

                          The square brackets contain a range of characters, and "0-9" indicates all the digits. The plus symbol indicates that the pattern will idenfiy one or more of whatever precedes the plus - so this pattern effectively means "one or more digits" - exactly what we're looking to find in our URL.

                          The entire "pattern" part of the rule is treated as a regular expression by default - you don't need to turn this on or activate it at all.
                          RewriteRule ^products/([0-9]+)/?$ show_a_product.php?product_id=$1 [NC,L] 
                          # Handle product requests

                          The first thing I hope you'll notice is that we've wrapped our pattern in brackets. This allows us to "back-reference" (refer back to) that section of the URL in the following "substitution" section. The "$1" in the substitution tells Apache to put whatever matched the earlier bracketed pattern into the URL at this point. You can have lots of backreferences, and they are numbered in the order they appear.

                          And so, this RewriteRule will now mean that Apache redirects all requests for domain.com/products/{number}/ to show_a_product.php?product_id={same number}.
                          Regular Expressions

                          A complete guide to regular expressions is rather beyond the scope of this article. However, important points to remember are that the entire pattern is treated as a regular expression, so always be careful of characters that are "special" characters in regular expressions.

                          The most instance of this is when people use a period in their pattern. In a pattern, this actually means "any character" rather than a literal period, and so if you want to match a period (and only a period) you will need to "escape" the character - precede it with another special character, a backslash, that tells Apache to take the next character to be literal.

                          For example, this RewriteRule will not just match the URL "rss.xml" as intended - it will also match "rss1xml", "rss-xml" and so on.
                          RewriteRule ^rss.xml$ rss.php [NC,L] # Change feed URL

                          This does not usually present a serious problem, but escaping characters properly is a very good habit to get into early. Here's how it should look:
                          RewriteRule ^rss\.xml$ rss.php [NC,L] # Change feed URL

                          This only applies to the pattern, not to the substitution. Other characters that require escaping (referred to as "metacharacters") follow, with their meaning in brackets afterwards:

                              . (any character)
                              * (zero of more of the preceding)
                              + (one or more of the preceding)
                              {} (minimum to maximum quantifier)
                              ? (ungreedy modifier)
                              ! (at start of string means "negative pattern")
                              ^ (start of string, or "negative" if at the start of a range)
                              $ (end of string)
                              [] (match any of contents)
                              - (range if used between square brackets)
                              () (group, backreferenced group)
                              | (alternative, or)
                              \ (the escape character itself)

                          Using regular expressions, it is possible to search for all sorts of patterns in URLs and rewrite them when they match. Time for another example - we wanted earlier to be able to indentify this URL and rewrite it:

                          http://www.pets.com/parrots/norwegian-blue/


                          And we want to be able to tell the server to interpret this as the following, but for all products:
                          http://www.pets.com/get_product_by_name.php?product_name=norwegian-blue

                          And we can do that relatively simply, with the following rule:
                          RewriteRule ^parrots/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L]
                          # Process parrots
                          With this rule, any URL that starts with "parrots" followed by a slash (parrots/), then one or more (+) of any combination of letters, numbers and hyphens ([A-Za-z0-9-]) (note the hyphen at the end of the selection of characters within square brackets - it must be added there to be treated literally rather than as a range separator). We reference the product name in brackets with $1 in the substitution.

                          We can make it even more generic, if we want, so that it doesn't matter what directory a product appears to be in, it is still sent to the same script, like so:
                          RewriteRule ^[A-Za-z-]+/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L] # Process all products
                          As you can see, we've replaced "parrots" with a pattern that matches letter and hyphens. That rule will now match anything in the parrots directory or any other directory whose name is comprised of at least one or more letters and hyphens.
                          Flags

                          Flags are added to the end of a rewrite rule to tell Apache how to interpret and handle the rule. They can be used to tell apache to treat the rule as case-insensitive, to stop processing rules if the current one matches, or a variety of other options. They are comma-separated, and contained in square brackets. Here's a list of the flags, with their meanings (this information is included on the cheat sheet, so no need to try to learn them all).

                              C (chained with next rule)
                              CO=cookie (set specified cookie)
                              E=var:value (set environment variable var to value)
                              F (forbidden - sends a 403 header to the user)
                              G (gone - no longer exists)
                              H=handler (set handler)
                              L (last - stop processing rules)
                              N (next - continue processing rules)
                              NC (case insensitive)
                              NE (do not escape special URL characters in output)
                              NS (ignore this rule if the request is a subrequest)
                              P (proxy - i.e., apache should grab the remote content specified in the substitution section and return it)
                              PT (pass through - use when processing URLs with additional handlers, e.g., mod_alias)
                              R (temporary redirect to new URL)
                              R=301 (permanent redirect to new URL)
                              QSA (append query string from request to substituted URL)
                              S=x (skip next x rules)
                              T=mime-type (force specified mime type)

                          Moving Content
                          RewriteRule ^article/?$ http://www.new-domain.com/article/ [R,NC,L] # Temporary Move

                          Adding an "R" flag to the flags section changes how a RewriteRule works. Instead of rewriting the URL internally, Apache will send a message back to the browser (an HTTP header) to tell it that the document has moved temporarily to the URL given in the "substitution" section. Either an absolute or a relative URL can be given in the substitution section. The header sent back includea a code - 302 - that indicates the move is temporary.
                          RewriteRule ^article/?$ http://www.new-domain.com/article/ [R=301,NC,L] # Permanent Move

                          If the move is permanent, append "=301" to the "R" flag to have Apache tell the browser the move is considered permanent. Unlike the default "R", "R=301" will also tell the browser to display the new address in the address bar.

                          This is one of the most common methods of rewriting URLs of items that have moved to a new URL (for example, it is in use extensively on this site to forward users to new post URLs whenever they are changed).
                          Conditions

                          Rewrite rules can be preceded by one or more rewrite conditions, and these can be strung together. This can allow you to only apply certain rules to a subset of requests. Personally, I use this most often when applying rules to a subdomain or alternative domain as rewrite conditions can be run against a variety of criteria, not just the URL. Here's an example:
                          RewriteCond %{HTTP_HOST} ^addedbytes\.com [NC] RewriteRule ^(.*)$ http://www.addedbytes.com/$1 [L,R=301]
                          The rewrite rule above redirects all requests, no matter what for, to the same URL at "www.addedbytes.com". Without the condition, this rule would create a loop, with every request matching that rule and being sent back to itself. The rule is intended to only redirect requests missing the "www" URL portion, though, and the condition preceding the rule ensures that this happens.

                          The condition operates in a similar way to the rule. It starts with "RewriteCond" to tell mod_rewrite this line refers to a condition. Following that is what should actually be tested, and then the pattern to test. Finally, the flags in square brackets, the same as with a RewriteRule.

                          The string to test (the second part of the condition) can be a variety of different things. You can test the domain being requested, as with the above example, or you could test the browser being used, the referring URL (commonly used to prevent hotlinking), the user's IP address, or a variety of other things (see the "server variables" section for an outline of how these work).

                          The pattern is almost exactly the same as that used in a RewriteRule, with a couple of small exceptions. The pattern may not be interpreted as a pattern if it starts with specific characters as described in the following "exceptions" section. This means that if you wish to use a regular expression pattern starting with <, >, or a hyphen, you should escape them with the backslash.

                          Rewrite conditions can, like rewrite rules, be followed by flags, and there are only two. "NC", as with rules, tells Apache to treat the condition as case-insensitive. The other available flag is "OR". If you only want to apply a rule if one of two conditions match, rather than repeat the rule, add the "OR" flag to the first condition, and if either match then the following rule will be applied. The default behaviour, if a rule is preceded by multiple conditions, is that it is only applied if all rules match.
                          Exceptions and Special Cases

                          Rewrite conditions can be tested in a few different ways - they do not need to be treated as regular expression patterns, although this is the most common way they are used. Here are the various ways rewrite conditons can be processed:

                              <Pattern (is test string lower than pattern)
                              >Pattern (is test string greater than pattern)
                              =Pattern (is test string equal to pattern)
                              -d (is test string a valid directory)
                              -f (is test string a valid file)
                              -s (is test string a valid file with size greater than zero)
                              -l (is test string a symbolic link)
                              -F (is test string a valid file, and accessible (via subrequest))
                              -U (is test string a valid URL, and accessible (via subrequest))

                          Server Variables

                          Server variables are a selection of items you can test when writing rewrite conditions. This allows you to apply rules based on all sorts of request parameters, including browser identifiers, referring URL or a multitude of other strings. Variables are of the following format:
                          %{VARIABLE_NAME}

                          And "VARIABLE_NAME" can be replaced with any one of the following items:

                              HTTP Headers
                                  HTTP_USER_AGENT
                                  HTTP_REFERER
                                  HTTP_COOKIE
                                  HTTP_FORWARDED
                                  HTTP_HOST
                                  HTTP_PROXY_CONNECTION
                                  HTTP_ACCEPT
                              Connection Variables
                                  REMOTE_ADDR
                                  REMOTE_HOST
                                  REMOTE_USER
                                  REMOTE_IDENT
                                  REQUEST_METHOD
                                  SCRIPT_FILENAME
                                  PATH_INFO
                                  QUERY_STRING
                                  AUTH_TYPE
                              Server Variables
                                  DOCUMENT_ROOT
                                  SERVER_ADMIN
                                  SERVER_NAME
                                  SERVER_ADDR
                                  SERVER_PORT
                                  SERVER_PROTOCOL
                                  SERVER_SOFTWARE
                              Dates and Times
                                  TIME_YEAR
                                  TIME_MON
                                  TIME_DAY
                                  TIME_HOUR
                                  TIME_MIN
                                  TIME_SEC
                                  TIME_WDAY
                                  TIME
                              Special Items
                                  API_VERSION
                                  THE_REQUEST
                                  REQUEST_URI
                                  REQUEST_FILENAME
                                  IS_SUBREQ

                          Working With Multiple Rules

                          The more complicated a site, the more complicated the set of rules governing it can be. This can be problematic when it comes to resolving conflicts between rules. You will find this issue rears its ugly head most often when you add a new rule to a file, and it doesn't work. What you may find, if the rule itself is not at fault, is that an earlier rule in the file is matching the URL and so the URL is not being tested against the new rule you've just added.
                          RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_product_by_name.php?category_name=$1&product_name=$2 [NC,L] # Process product requests                 
                          RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_blog_post_by_title.php?category_name=$1&post_title=$2 [NC,L] # Process blog posts
                          In the example above, the product pages of a site and the blog post pages have identical patterns. The second rule will never match a URL, because anything that would match that pattern will have already been matched by the first rule.

                          There are a few ways to work around this. Several CMSes (including wordpress) handle this by adding an extra portion to the URL to denote the type of request, like so:
                          RewriteRule ^products/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_product_by_name.php?category_name=$1&product_name=$2 [NC,L]  # Process product requests
                          RewriteRule ^blog/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_blog_post_by_title.php?category_name=$1&post_title=$2 [NC,L]# Process blog posts
                          You could also write a single PHP script to process all requests, which checked to see if the second part of the URL matched a blog post or a product. I usually go for this option, as while it may increase the load on the server slightly, it gives much cleaner URLs.
                          RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ get_product_or_blog_post.php?category_name=$1&item_name=$2 [NC,L] # Process product and blog requests

                          There are certain situations where you can work around this issue by writing more precise rules and ordering your rules intelligently. Imagine a blog where there were two archives - one by topic and one by year.
                          RewriteRule ^([A-Za-z0-9-]+)/?$ get_archives_by_topic.php?topic_name=$1 [NC,L] # Get archive by topic 
                          RewriteRule ^([A-Za-z0-9-]+)/?$ get_archives_by_year.php?year=$1 [NC,L] # Get archive by

                          The above rules will conflict. Of course, years are numeric and only 4 digits, so you can make that rule more precise, and by running it first the only type of conflict you cound encounter would be if you had a topic with a 4-digit number for a name.
                          RewriteRule ^([0-9]{4})/?$ get_archives_by_year.php?year=$1 [NC,L] # Get archive by year RewriteRule ^([A-Za-z0-9-]+)/?$ get_archives_by_topic.php?topic_name=$1 [NC,L] # Get archive by topic
                          mod_rewrite

                          Apache's mod_rewrite comes as standard with most Apache hosting accounts, so if you're on shared hosting, you are unlikely to have to do anything. If you're managing your own box, then you most likely just have to turn on mod_rewrite. If you are using Apache1, you will need to edit your httpd.conf file and remove the leading '#' from the following lines:
                          #LoadModule rewrite_module modules/mod_rewrite.so #AddModule mod_rewrite.c

                          If you are using Apache2 on a Debian-based distribution, you need to run the following command and then restart Apache:
                          sudo a2enmod rewrite

                          Other distubutions and platforms differ. If the above instructions are not suitable for your system, then Google is your friend. You may need to edit your apache2 configuration file and add "rewrite" to the "APACHE_MODULES" list, or edit httpd.conf, or even download and compile mod_rewrite yourself. For the majority, however, installation should be simple.
                          ISAPI_Rewrite

                          ISAPI_Rewrite is a URL rewriting plugin for IIS based on mod_rewrite and is not free. It performs most of the same functionality as mod_rewrite, and there is a good quality ISAPI_Rewrite forum where most common questions are answered. As ISAPI_Rewrite works with IIS, installation is relatively simple - there are installation instructions available.

                          ISAPI_Rewrite rules go into a file named httpd.ini. Errors will go into a file named httpd.parse.errors by default.
                          Leading Slashes

                          I have found myself tripped up numerous times by leading slashes in URL rewriting systems. Whether they should be used in the pattern or in the substitution section of a RewriteRule or used in a RewriteCond statement is a constant source of frustration to me. This may be in part because I work with different URL rewriting engines, but I would advise being careful of leading slashes - if a rule is not working, that's often a good place to start looking. I never include leading slashes in mod_rewrite rules and always include them in ISAPI_Rewrite.
                          Sample Rules

                          To redirect an old domain to a new domain:
                          RewriteCond %{HTTP_HOST} old_domain\.com [NC] RewriteRule ^(.*)$ http://www.new_domain.com/$1 [L,R=301]
                          To redirect all requests missing "www" (yes www):
                          RewriteCond %{HTTP_HOST} ^domain\.com [NC] RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

                          To redirect all requests with "www" (no www):
                          RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC] RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

                          Redirect old page to new page:
                          RewriteRule ^old-url\.htm$ http://www.domain.com/new-url.htm [NC,R=301,L]

                          Thursday, 20 June 2013

                          Paking and unpaking weblogic domains

                          Packing a domain

                          [root@localhost bin]# pwd
                          /home/bea/weblogic91/common/bin
                          [root@localhost bin]# ./pack.sh -domain=/home/bea/user_projects/domains/dev_domain -template=/home/bea/user_templates/New_dev_domain.jar -template_name="New_dev_domain"
                          << read domain from "/home/bea/user_projects/domains/dev_domain"
                          >>  succeed: read domain from "/home/bea/user_projects/domains/dev_domain"
                          << write template to "/home/bea/user_templates/New_dev_domain.jar"
                          ....................................................................................................
                          >>  succeed: write template to "/home/bea/user_templates/New_dev_domain.jar"
                          << close template
                          >>  succeed: close template

                          Unpaking domain

                          [root@localhost bin]# ./unpack.sh -template=/home/bea/user_templates/New_dev_domain.jar -domain=/home/bea/user_projects/domains/new_dev_domain
                          << read template from "/home/bea/user_templates/New_dev_domain.jar"
                          >>  succeed: read template from "/home/bea/user_templates/New_dev_domain.jar"
                          << write Domain to "/home/bea/user_projects/domains/new_dev_domain"
                          >>  warning:write Domain to "/home/bea/user_projects/domains/new_dev_domain"
                          >>  The "Servers, Clusters and Machines" configuration in your domain has been found to be invalid. It may be possible to resolve the issue by reviewing your script. The wizard will continue, but you may want to start the server in your domain and review the messages displayed to identify the invalid configuration.
                          ...............................................................................................
                          >>  succeed: write Domain to "/home/bea/user_projects/domains/new_dev_domain"
                          << close template
                          >>  succeed: close template
                           



                          Wednesday, 19 June 2013

                          Shell script for stopping Nodemanger


                          #!/bin/sh
                          #Script name: stopNodeManager.sh
                          #Path: /home/bea/weblogic103/server/bin/
                          #Author: pavankumar
                          PID=`ps -ef | grep weblogic.NodeManager | grep -v grep | awk '{print $2}'`
                          if [ ! -z $PID ]
                          then
                              ps -ef | grep weblogic.NodeManager | grep -v grep
                              echo;echo;echo
                              echo "Stopping NodeManager with pid:$PID ..."
                              kill -9 $PID
                              PID=`ps -ef | grep weblogic.NodeManager | grep -v grep | awk '{print $2}'`
                              if [ -z $PID ]
                              then
                                  echo "DONE."
                              else
                                  echo "FAILED."
                                  exit 1
                              fi
                          else
                              echo "NodeManager is not running"
                          fi