Monday 3 September 2012

Expat Parser

Expat is an parser which is used to read, update, create and manipulate XML data.
Types of XML parsers:
a) Tree based parser - This parser analyzes the whole document and provides tree elements after transforming a XML document. Document Object Model (DOM) is an example of Tree-based parser.
b) Event based parser - XML document views as a series of events. After occuring any event it calls a function to handle it. Expat parser is an exaple of event based parser.
Event based parser focus the content of any XML document not their structure. So this type of parser can access data faster than tree based parsers.

Wednesday 8 August 2012

utf8_encode — This function is used to Encode an ISO-8859-1 string to UTF-8

Above function encodes string data into UTF-8 and returns ecoded version of the string. UTF-8 mechanism is standard and used by Unicode for encoding character values into a byte system. PHP encodes UTF-8 upto 4-bytes.

Sunday 29 July 2012

Cookie in CakePHP

Write Cookie:
$this->Cookie->write('countryName', 'India', false, 0); Argument Description sequence: cookie name, value, encrypted or not if set false means cookie will store as plain text.
Read Cookie:
echo $this->Cookie->read('countryName');
Output: India

Saturday 28 July 2012

strstr() Function

Finds first occurance of any string from a given string.
strstr() function is a case sensitive function to use case insensitive stristr() is used.
e.g
$emailId = 'test@mydomain.com';
$domainName = strstr($emailId, '@');
echo $domainName; // outputp will be: mydomain.com
$firstPart = strstr($email, '@', true); // PHP 5.3 and above
echo $firstPart; // outputp will be: test
?>

Friday 27 July 2012

sprintf() function

function sprintf() returns a formatted string, according to the formatting string format.
$numOfStudent = 50;
$class = 'Class';
$format = 'There are %d Students in the %s';
echo sprintf($format, $numOfStudent, $class);
// output will be: There are 50 Students in the Class
?>

Thursday 26 July 2012

strrpos() function

Finds position of the last occurance from a string.
e.g
$str = 'abcd';
$chkStr = 'b';
echo strpos($str,$chkStr); // output will be: 1
?>

Tuesday 24 July 2012

strstr() Function

Finds first occurance of any string from a given string.
strstr() function is a case sensitive function to use case insensitive stristr() is used.
e.g
$emailId = 'test@mydomain.com';
$domainName = strstr($emailId, '@');
echo $domainName; // outputp will be: mydomain.com
$firstPart = strstr($email, '@', true); // PHP 5.3 and above
echo $firstPart; // outputp will be: test
?>

Monday 23 July 2012

CSS Opacity property

Transparency property of CSS is called opacity.
img
{
opacity:0.5;
filter:alpha(opacity=50); /* Used in IE8 or below version of IE */
}
Opacity range is 0.0 - 1.0, more lower opacity values means more transparent element.
property opacity is used in Firefox, Opera, IE9, Chrome and Safari for transparency. But IE8 or lower version uses filter:alpha(opacity=x). Here value x ranges from 0-100. Lower x value means more transparent element.

Friday 20 July 2012


tabindex property

tabindex attribute is used to set tab order for element.

<input name="first" tabindex="2" type="text" />
<input name="second" tabindex="3" type="text" />
<input name="third" tabindex="1" type="text" />
Above input box will highlight in sequence : third,second,first when we press tab key.

Thursday 19 July 2012

Mysql concat() function

mysql concat() function
This function combines two string into a single string.
uses:
1) SELECT CONCAT('FIRST_NAME', 'LAST_NAME') as concatname;
o/p: FIRST_NAME LAST_NAME
2) concat with separator
SELECT CONCAT_WS('-','FIRST_NAME','LAST_NAME');
o/p: FIRST_NAME-LAST_NAME

Wednesday 18 July 2012

z-index property

z-index specifies stack order of an element. An element which has greater stack order means greater z-index value is always in front of an element which has low stack order.
z-index works only on positioned elements like: position:absolute, position:relative, or position:fixed.
z-index property value:
auto: Stack order equal to its parents stack order value. This is default value.
number: Sets stack order for any element this value can be negative.
inherit: This property specifies that the z-index should be inherited from the parent element.

Tuesday 17 July 2012

Mysql replace() function

REPLACE(str1,fromStr,toStr)
Returns str with all occurrences of the string from the fromStr and replaced by the string toStr. REPLACE() is a case sensitive match when it searches str for the fromStr.
SELECT REPLACE('www.test.com', 'w', 'Ww'); o/p: 'WwWwWw.mysql.com'

Mysql DAYOFMONTH() function

DAYOFMONTH(date)
Above function returns day of the month for the date in the range between 1 to 31, or 0 for the dates like '0000-00-00' or '2012-00-00', which have zero in day part.
SELECT DAYOFMONTH('2007-02-03'); o/p: 3

Mysql DAYNAME() function

DAYNAME(date)
Above function returns name of the weekday for date.
SELECT DAYNAME('2007-02-03'); o/p: 'Saturday'

Monday 16 July 2012

Mysql DATEDIFF function

Mysql DATEDIFF(arg1,arg2) function
DATEDIFF() function returns arg1 – arg2. Value is expressed in term of days. arg1 and arg2 are either date or date-and-time expressions. Only date part is used for calculation.
SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
o/p: 1
SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
o/p: -31

MYSQL DAYOFWEEK function

MYSQL DAYOFWEEK(date) function
Returns the weekday index for date (1 = Sun, 2 = Mon,3=Tue,4= Wed, 5=Thu, 6= Fri, 7 = Saturday). index values are ODBC standard.
SELECT DAYOFWEEK('2007-02-03');
o/p: 7

Mysql extract (date) Function

extract() function can be used to extracting date value from any date.
SELECT EXTRACT(YEAR FROM '2009-07-02');
o/p: 2009
SELECT EXTRACT(MONTH FROM '2009-07-02');
o/p: 7
SELECT EXTRACT(DAY FROM '2009-07-02');
o/p: 2
Point to be Noted:
SELECT EXTRACT(MONTH FROM '2009-13-02');
Above Code will o/p NULL, because month exceeded to 12.

Sunday 15 July 2012

Concept of Smarty

A template engine for PHP is Smarty which separates presentation from application logic.
Features of Smarty:
1) It is open source and free available.
2) Smarty used in front end and PHP backend.
3) Compliment PHP, not replace it
4) fast development/deployment for programmers and designers
5) quick and easy to maintain
6) syntax easy to understand, no PHP knowledge required
7) flexibility for custom development
8) security: insulation from PHP
9) clean separation of presentation from application code

User Group Permission set in UBUNTU

sudo adduser www-data (group)
sudo chgrp (group) /var/www
sudo chmod –R 775 /var/www
sudo chmod g+s /var/www

Friday 13 July 2012

File Synchronization with rsync

The magic of synchronization is very helpful for backups, keeping web servers synchronization. It is very fast than copying of files and takes low bandwidth, using one command only.

Installation of rsync


Mostly linux flavours contains pre installed rsync. If this service is not installed we can install with package manager. In the case of ubuntu below command is used:
aptitude -y install rsync
Below command is used to copy local to server:
local /home/kevin/source to /home/kevin/destination which resides on the server: server.mysite.com:
rsync -az --progress --size-only /home/kevin/source/* server.mysite.com:/home/kevin/destination/
prefix with sync explained:
1) -r
recursive
2) a
archive, preserves all attributes like ownership, timestamps, etc
3) z
compress, saves bandwidth but is harder on your CPU so use it for slow/expensive connections only
4) --progress
shows you the progress of all the files that are being synced
5) --size-only
compare files based on their size instead of hashes (less CPU, so faster)

Thursday 12 July 2012

to_days() function in mysql

SELECT TO_DAYS(950501); output: 728779
SELECT TO_DAYS('2007-10-07'); output: 733321
to_days(date) function will give output to number of days since year 0 of the passing argument date.

Wednesday 11 July 2012

Delete duplicate rows from Database

DELETE ta FROM tablename t1, tablename t2 WHERE t1.id > t2.id AND t1.fieldname = t2.fieldname
Above query will keep rows with lowest id of the table tablename.
DELETE ta FROM tablename t1, tablename t2 WHERE t1.id < t2.id AND t1.fieldname = t2.fieldname
And above query will keep rows with highest id of the table tablename.
Note: Above id is a field of integer type.

Tuesday 10 July 2012

set chmod for directory/files

Recursively chmod only for directory
find . -type d -exec chmod 755 {} \;
Recursively setting chmod on every directory for execting
chmod -R a+X *
Above +X flag is used to set execute bit for directories only.
Recursively chmod setting only for files.
find . -type f -exec chmod 644 {} \;
Recursively set chmod only for PHP files which have extensions (.php)
find . -type f -name '*.php' -exec chmod 644 {} \;

Monday 9 July 2012

Concept of REST

REpresentational State Transfer or REST is asoftware architecture which is used for distributed system like world wide web (www). REST is used as a web services which displaced other design models like SOAP and WSDL due to its simpler style

Sunday 8 July 2012

HTTP Methods

Below are the set of methods defined in HTTP/1.0:
1) GET -: This method retrieve information in the form of entity which are identified by the request URI.
2) POST -: Post method is used to send data to the server to process it by some way like by the CGI Script.
3) HEAD -: Like GET method HEAD request do same except this message asks to server only to return response headers no body of the message. This method is useful to saving bandwidth because it check characteristics of resource without downloading it.

Saturday 7 July 2012

SOAP or Simple Object Access Protocol is a protocal which is used for exchanging structured information in the web service implementation in the computer networs. For message formats it relies on XML (Extensible Markup Language) and for message negotiation and transmission it relies on Application Layer Protocols (like HTTP) and Simple Mial Transfer Protocol (SMTP).
Features of SOAP:
  1. It is a communication protocol
  2. It is used for communication between applications
  3. It is a format which is used for sending messages
  4. It communicates via Internet
  5. It is platform independent
  6. It is language independent
  7. It is based on XML
  8. It is simple and extensible
  9. It allows to get around firewalls
  10. It is a W3C recommendation

Builiding Blocks of SOAP:
SOAP message is a a simple XML document which includes below elements:
  1. An Envelope element that identifies the XML document as a SOAP message
  2. A Header element that contains header information
  3. A Body element that contains call and response information
  4. A Fault element containing errors and status information
SOAP Syntax Rule: Below are some important syntax rule:
  1. A SOAP message MUST be encoded using XML
  2. A SOAP message MUST use the SOAP Envelope namespace
  3. A SOAP message MUST use the SOAP Encoding namespace
  4. A SOAP message must NOT contain a DTD reference
  5. A SOAP message must NOT contain XML Processing Instructions
SOAP Document example ... ... ...

Friday 6 July 2012

Create CakePHP Component

When we require any code for many controllers or different parts of application we can create component in CakePHP Framework. Suppose we need a complex mathematics calculation in every controller or different parts of application we create a math component to share in different controllers. Let we create a Sum component to return sum of two numbers, we can create this component in the path /app/controllers/components/math.php with below code:
class SumComponent extends Object {
function sumTwoNums($amount1, $amount2) {
return $amount1 + $amount2;
}
}
?>

Above Sum component is extending Object class not Component, because if we extend Component which can create infinite redirect issues when component is combined with another Components.
Include Component in Controller where we need it.
var $components = array('Sum');
Calling Component functions inside Controller by below code:
$this->Sum->sumTwoNums(4,8);

Thursday 5 July 2012

Concept about JSON

JSON or Javascript Object Notation is a way to storing data or information in organized manner. These information can access easily. These stored information is human readable so we can access it logical manner.
Example of JSON:
var jsonobj = { "name":"John", "age":"25 years", "sex":"Male" };
Above jsonobj variable is used to access the values. Property and values are kept inside curly braces like "property name":"property value" pair. Multiple vales can be kept using comma separation. We can access values stored in jsonobj by refering the name ofproperty like:
document.write(jsonobj.name+' is '+jsonobj.age+' old.');
Above code will output: John is 25 years old.

Tuesday 3 July 2012

Redirecting sub domains according to Country

To redirecting any sub domain according to country, install mod_geoip module (GeoIp Extentsion) inside server if it not installed. Write below code in .htaccess file:
GeoIPEnable On
GeoIPDBFile /GeoIp path/GeoIP.dat
#Redirection according to country
# For USA
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^USA$
RewriteRule ^(.*)$ http://us.mysite.com$1 [L]
# For India
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
RewriteRule ^(.*)$ http://in.mysite.com$1 [L]
# For Canada
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$
RewriteRule ^(.*)$ http://ca.mysite.com$1 [L]

Types of Software Testing

Black Box Testing – This tests are based on requirements and functionality. Internal system design not considered in this testing.
White Box Testing – This testing is also called Glass Box Testing. This test is based on knowledge of the internal logic of any application. In this testing knowledge of code statements, branches, paths conditions should known.
Unit Testing – This type of testing is based on individual components or modules of any software. Because this testing requires detailed knowledge of the flow (design and code of software) of software test is done by programmer not by tester..
Incremental integration testing – In this type of testing functionality of application or modules should be independent to test it separately done by programmers or testers. So it is called bottom up approach for testing.
Integration testing – This testing is used when all modules are tested in integrated form. Modules may be application, code, client server functionality, distributed systems.
Functional testing – This test checks funtional requirements of any application like black box testing. It ignores internal parts of application.
System testing – This test is based on entire system testing as per the requirements. It checks overall requiremetns of any application in combined form.
End-to-end testing – This type of testing is used for complete application environment. In this test real-world use of software is tested like database interaction, network communications, interaction with hardware or applications or any other systems.

Sunday 1 July 2012

Enable Disable root account in ubuntu

In Ubuntu Linux distribution root account not enable. But if user want to do some command with root permission on the terminal sudo command should be written before command. sudo stands for super user do. sudo command require password. Below command can be used to enable root account:
$sudo yourpassword root
Above command will prompt for new root password after confirming root account can be logged in.
To disable root account in ubuntu have to lock root account by using below command:
$sudo password -l root
Better way to work on a root console below command is used:
$sudo -i

Friday 29 June 2012

Hard Disk Serial Number Ubuntu Command

To get Hard Disk Serial Number below command can be used. Open terminal and type below command (system login should by admin). hdparm -I /dev/sda|grep "Serial Number"

Sunday 24 June 2012

What is hardware virtualization

virtualization of hardware is the Virtualization of hardware or operating systems. This concept hides physical characteristics of platform used for computing from users. It shows another abstract computer platforms to users. The software which is used to virtualization is called control program nowadays hypervisor or virtual machine monitor are also used.

Saturday 23 June 2012

CAKEPHP Auth Component

This CAKEPHP  component gives user authentication and authorization in very simple manner.

Auth Component for Authentication.


This is very useful component for user authetication. This requires some configuration which can best done by setting AppController::beforeFilter(). Below line should be added in AppController: var $components = array('Acl', 'Auth'); To avoid error (Fatal error: Call to a member function check() on a non-object in /var/www/geoff/cake/cake/libs/controller/components/acl.php on line x, where x is line number) it should be noted down that Acl Component should add before Auth Component.

Monday 18 June 2012

Apache Maximum number of conncetions processed simultaneously

Apache directive MaxClients is responsible to handle maximum number of connections processed simultaneously. When any new connection is created over than MaxClients limit it will be on queued upto the number based on ListenBacklog directive. After completion of any child process new process will be served from queue.

In the case of non-threaded server (e.g. prefork), MaxClients will translate into the maximum number of child processes that will be launched to serve requests. Default value is 256 we can increase it after raising ServerLimit.

But in the case of threaded and hybrid servers (like beos or worker) MaxClients restricts the total number of threads available to serve clients. Default value for beos is 50.

Saturday 16 June 2012

CAKEPHP Route Concept.

Rotes in CAKEPHP is used to map for exact Controller and Action. It is not redirecting.

Default Routes:

Some default routes come with CAKEPHP inside the file routes.php (app/config/routes.php).
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
The first parameter '/' is the root of the domain. The second parameter sets PagesController::display() action with first parameter as home.

Wildcard in Routes:

Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
In above route setting maps with controller pages and action display. All things after /pages/ will be passed as parameter to action display.

Routes with named elements:

Router::connect('/namedelement/:action/*', array('controller' => 'pages'));
Here named element called 'action' in this route. Named elements are prefixed with ':'. These named elements are automatically passed to controller with Controller::$params and in same way to the view class.

Friday 15 June 2012

CSS Overflow Property

When content overflows any container box "overflow"  property can be used.

e.g.
div
{
 overflow:scroll;
}

Other Values of overflow:

i)   hidden    : This value clipps overflow, rest of content will be hidden.
ii)  visible    : This is default value. It renders outside of element box.
iii) inherit    : It specifies that the value of overflow property should be inherited from the parrent element.
iv)  auto    : A scroll bar will automatically added to the rest of contents, if overflow is clipped.
v)   scroll    : This value adds a scroll bar for extra contents.

Wednesday 13 June 2012

MySQL Engine Types

ISAM:   
It is old version of MyISAM which is deprecated. This is original mySQL engine.


MyISAM:
This is non-transactional storage engine which provides full-text indeding. It is default for mysql.

MERGE:
This is a non-transactional storage engine which allows a collection of MYISAM tables with identical column and index information as one.

MEMORY (HEAP): 
This engine stores data in memory. It is a non-transactional storage engine.

BDB (Berkeley DB):
This is first transactional-safe storage engine.   

InnoDB:
This is a transactional-safe, row-level locking storage engine. This engine is designed for maximum performance for large volume of data.   

FEDERATED:
This engine accesses data in tables of remote databases rather than in local tables.

ARCHIVE:
This engine stores large amount of data without indexes.   

CSV:
This engine stores data in text file using comma-separated-values format.

BLACKHOLE: 
This engine acts as black-hole which accepts data and throws it away and doesn't store.

EXAMPLE:
A stub engine which serve as an example that illustrates how to begin writing new engines.   

Tuesday 12 June 2012

Jasper and JSP

Jasper is a JSP Engine of Tomcat. Jasper converts JSP files into servlet to compile them into Java Code. Jasper recompiles JSP files for every changes detects at run time.
Tomcat 5.x uses Jasper 2. Below are the important features added in Jasper 2:

1) Java Compiler for JDT (Java Development Tools): Eclipse JDT use into Jasper 2 instead of Ant and java.
2) On page changes JSP recompiled: At runtime pages can be inserted and included, also jasper will recompile page changes and included page changes.
3) Background compilation of JSP files: During the recompilation of JSP code older version of JSP code will also available for server request. After the finishing of new JSP servlet recompiling older JSP servelet will be deleted.

Monday 11 June 2012

ubuntu command to show shared files

Open termial and write below command:

shares-admin

SSH Concept

What is SSH?
Simply SSH stands for Secured Shell. SSH is a network protocol which is used for sucure data communication.This protocol is used between two networked computers which are connected via a secure channel over an insecure network. Two computers are distinguish as client(runs SSH client) and server(runs SSH server).

History behind the SSH: Tatu Ylönen (Country:Finland) a researcher from Helsinki University of Technology designed the first version of SSH which is now called SSH-1.

SSH Features:

    1) SSH is a Command line terminal connection tool.
 
     2) SSH Replaces rsh, rcp, telnet, and others

     3) All traffic encrypted in SSH protocol.

     4) Both client and server side authenticate.

     5) SSH is able to carry and encrypt non-terminal traffic.

SSH Installation in Ubuntu Environment: The Ubuntu flavour of SSH is called openSSH, which is a free open source SSH implementation.This SSH contains two components an openssh-client and an openssh-server. To check SSH in both client and server side below command can be used.

sudo apt-get install openssh-client openssh-server


Sunday 10 June 2012

Added and Removed Elements in HTml 5

Added: Following new elements are added in HTML 5.

<article>     Used to Define an article.
<aside>     Used to Define content aside from the page content.
<bdi>         Used to Isolate a part of text that might be formatted in a different direction from other text outside it.
<command>     Used to Define a command button that a user can invoke.
<details>     Used to Define additional details that the user can view or hide.
<figure>     Used to Specify self-contained content, like illustrations, diagrams, photos, code listings, etc.
<figcaption>     Used to Define a caption for a <figure> element.
<footer>     Used to Define a footer for a document or section.
<header>     Used to Define a header for a document or section.
<hgroup>     Used to Making a Group of a set of <h1> to <h6> elements when a heading has multiple levels.
<mark>         Used to Define marked/highlighted text.
<meter>     Used to Define a scalar measurement within a known range.
<nav>         Used to making navigation links.
<progress>     Shows progress of a task.
<ruby>         Used to ruby annotation (Used in Asian typography).
<section>     Used to define a section in a document.
<summary>     Used to Define a visible heading for a <details> element.
<time>         Displays Date/Time.
<wbr>         Used to possible line break.

<audio>     Used to sound content.
<video>     Used to video or movie.
<source>     Used to multiple media resources like <video> and <audio>
<embed>     Used to external application or interactive content (plug-in) in a container. 
<track>     Used to <video> and <audio> text tracks.

<canvas>     Using scripting (usually javascript) drawing graphics on the fly.

<datalist>     Includes list of pre-defined options for input controls.
<keygen>     Used to Define a key-pair generator field (for form element.)
<output>     Result of a calculation.

Removed: Below elements are removed from HTML 5.

<acronym>
    <applet>
    <basefont>
    <big>
    <center>
    <dir>
    <font>
    <frame>
    <frameset>
    <noframes>
    <strike>
    <tt>

Friday 8 June 2012

Basics Concept of SEO

Simply SEO stands for Search Engine Optimization OR Search Engine Optimizer.

There are two parts of SEO:
i) On Page Optimization.
ii) Off Page Optimization.

On Page Optimization: This ensures that website pages are optimized properly so that search engine know that for what purpose pages are created.
 Off Page Optimization: Off page optimization calculates all back links for any website from another website. Because search engine treat backlinks as vote, so backlinks are very important for ranking.

Thursday 7 June 2012

What is Subdomain?

Subdomains are second level of domains or its substiture. If main domain is www.mymaindomain.com, then subdomain can be http://subdomain.mymaindomain.com.

Merits:
1) Cost Saving: If any organization want to buy 100 domains for different subject it will cost (100*perdomain cost). But subdomain cost free. So it will cost 0 for 1-10000 (depending upon provider how many subdomains they provide.) subjects.

2) Since all search engines treat subdomains as different for indexing. Like www.mymaindomain.com AND http://subdomain.mymaindomain.com are two different domains for search engines. So website owner get all the benefits of keyword rich website without registering extra domain and hosting cost.


Wednesday 6 June 2012

Introduction of MySql Cursor

 Mysql supports curosr inside stored programs. This is an embedded SQL. Cursors have  some  properties:

i) Asensitive - Server may or may not make a copy of its result table.

ii) Its read only. It means it can't update.

iii) Nonscrollable: It can traversed only one direction, and rows can't skip.

To be noted: Cursor should must appear before handler declarations and after variable and condition declarations.

Example:


CREATE PROCEDURE myCurDemo()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE a CHAR(16);
  DECLARE b, c INT;
  DECLARE mycur1 CURSOR FOR SELECT id,data FROM test.table1;
  DECLARE mycur2 CURSOR FOR SELECT id FROM test.table2;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN mycur1;
  OPEN mycur2;

  read_loop: LOOP
    FETCH mycur1 INTO a, b;
    FETCH mycur2 INTO c;
    IF done THEN
      LEAVE read_loop;
    END IF;
    IF b < c THEN
      INSERT INTO test.table3 VALUES (a,b);
    ELSE
      INSERT INTO test.table3 VALUES (a,c);
    END IF;
  END LOOP;

  CLOSE mycur1;
  CLOSE mycur2;
END;

Tuesday 5 June 2012

URL Rewriting and SEO

What is URL rewriting?

Most dynamic websites uses variables in the URLs to pass values like: http://www.mywebsite.com/myproducts.php?id=1, which is not SEO friendly. But in the sense of SEO this URL can be change to http://www.mywebsite.com/products/7. This can be done by URL rewriting on .htaccess on Apache environement. To achieve this mod_rewrite module should be ON. IIS (Microsoft server) doesn't include this functionality but using add-ons it can be used. ISAPI_Rewrite can be used to mod_rewrite functionality in IIS environment.

1) Simple replacement:

http://www.mywebsite.com/product_details_and_info.php

RewriteEngine On # Turn on the rewriting engine
RewriteRule ^product-details/?$ product_detals_and_info.php [NC,L]

The above code will change URL below:

http://www.mywebsite.com/product-details/

2) Match pattern and replacement:

http://www.mywebsite.com/product_lists.php?pid=10

RewriteRule ^products/([0-9]+)/?$ product_lists.php?pid=$1 [NC,L]

http://www.mywebsite.com/products/10/

Here $1 will replace all number in pid (like pid=10) with pid number after products (like /products/10).

3) Regular Expression match:

Because this pattern match with regular expression(RE) so be careful with special characters of RE.

RewriteRule ^rssfeed.xml$ rssfeed.php [NC,L]

Above example will not only match rssfeed.xml but also will match rssfeed1xml, rssfeed-xml. So to avoid this use below code.

RewriteRule ^rssfeed\.xml$ rssfeed.php [NC,L]

Other escaping character lists are:

     . => Any character
     * => Zero or more of the preceding
     + => One or more of the preceding
     {} => Minimum to maximum quantifier
     ? => Ungreedy modifier
     ! => Negative Pattern OR At start of string
     ^ => 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

4) Content Moved

RewriteRule ^articles/?$ http://www.mywebsite.com/articles/ [R,NC,L]

Here R flag denotes that articles is moved temporarily. Either a substitution URL can be given or header will sent back a code 302, it means moved temporarily.

RewriteRule ^article/?$ http://www.new-domain.com/article/ [R=301,NC,L]

Here R=301 shows that content is moved permanentaly.

Other Flags:
     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 means 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
     PT => Pass through ( 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


What is $_SERVER ??

$_SERVER is a superglobal array in PHP. It contains following values:

    $_SERVER['UNIQUE_ID']
    $_SERVER['HTTP_HOST']
    $_SERVER['HTTP_USER_AGENT']
    $_SERVER['HTTP_ACCEPT']
    $_SERVER['HTTP_ACCEPT_LANGUAGE']
    $_SERVER['HTTP_ACCEPT_ENCODING']
    $_SERVER['HTTP_ACCEPT_CHARSET']
    $_SERVER['HTTP_KEEP_ALIVE']
    $_SERVER['HTTP_CONNECTION']
    $_SERVER['HTTP_CACHE_CONTROL']
    $_SERVER['PATH']
    $_SERVER['SERVER_SIGNATURE']
    $_SERVER['SERVER_SOFTWARE']
    $_SERVER['SERVER_NAME']
    $_SERVER['SERVER_ADDR']
    $_SERVER['SERVER_PORT']
    $_SERVER['REMOTE_ADDR']
    $_SERVER['DOCUMENT_ROOT']
    $_SERVER['SERVER_ADMIN']
    $_SERVER['SCRIPT_FILENAME']
    $_SERVER['REMOTE_PORT']
    $_SERVER['GATEWAY_INTERFACE']
    $_SERVER['SERVER_PROTOCOL']
    $_SERVER['REQUEST_METHOD']
    $_SERVER['QUERY_STRING']
    $_SERVER['REQUEST_URI']
    $_SERVER['SCRIPT_NAME']
    $_SERVER['PHP_SELF']
    $_SERVER['REQUEST_TIME']

Sunday 3 June 2012

File Location in LAMP Environment.

1) php.ini
      It depends upon Linux distribution and PHP Version , but some common locations may be:

a) /etc/php.ini
b) /etc/php/php.ini
c) /etc/php5/php.ini
d) /usr/bin/php5/bin/php.ini
 OR

find by command: find / -name php.ini   

Saturday 2 June 2012

Benefits of Stored Procedures.

Advantages of Stored Procedures:

1) Stored porcedures separates database access logic from the application logic.

2) SQL can be pre-compiled which increases the speed of the application.

3) More processing can be done on database server due to stored procedures contain program logic, which reduces bandwidth consumed to sending data back to the application.

4) On the implementation of n-tier application, stored procedures separates the data layer from the server layer.

5) Applications can be grant execute privileges to the stored procedures, while being unable to access the tables directly. It enables security feature of stored procedure.

Wednesday 30 May 2012

Memcached ?????

Distributed object caching system, generic in nature is Memcached. It is free and open source, speeding up dynamic web applications by allevaiating database load. Memcached is an in-memory key-value store for small chunks of arbitrary data from results of database calls, API calls, or page rendering.

e.g.

function getMemCached(memid)
    mem = memcached_get("mem:" . memid
)
    return mem
 if defined 
mem

    mem = fetch_foo_from_database(memid)
    memcached_set("mem:" . memid, mem)
    return mem
end

Disadvantage of index

Remember some disadvantages of index


Each index  occupy some extra space on the disk, which means that as the data increases it need some extra space not to store data but to maintain index data also.

Indexes  Slow down the insertion and updation of the table- because index has to maintain the details about the original data , when data is inserted or updated the index will have to updated as well . In case of multiple indexes ,  these multiple indexes will have to be updated on insert and update operation and hence the operations will become slow.

Set file size limit using .htaccess file

Write below code into your .htaccess file to upload file size limit.

php_value upload_max_filesize 50M
php_value post_max_size 5M
php_value max_execution_time 300
php_value max_input_time 100

Tuesday 29 May 2012

Benefits of Mysql Query Cache

Mysql Query Cache

Query cache stores both the query SELECT text and result fetched by the query which was sent to the client. For second time it check same query if it matches it don't send query to DB engine, shows data from cache.....Its time saving.

Caching in Cakephp

Element Caching in Cakephp

Cakephp view can be cached if set to true (1 day by default but can be set alternate time).

<?php echo $this->element('elementname', array('cache' => true)); ?>

Create Slave User to Mysql

Mysql Slave User


mysql> CREATE USER 'repl'@'%.domainname.com' IDENTIFIED BY 'yourpassword';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%.domainname.com';