Archive for the ‘PHP’ category

Redirect to www

March 1st, 2011

Create a .htaccess file with the below code, it will ensure that all requests coming in to domain.com will get redirected to www.manoj.com

The .htaccess file needs to be placed in the root directory of your old website (i.e the same directory where your index file is placed)

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^manoj.com [nc]
rewriterule ^(.*)$ http://www.manoj.com/$1 [r=301,nc]

Please REPLACE  manoj.com with your actual domain name.

Note* This .htaccess method of redirection works ONLY on Linux servers having the Apache Mod-Rewrite moduled enabled.

Redirect Old domain to New domain

March 1st, 2011

Create a .htaccess file with the below code, it will ensure that all your directories and pages of your old domain will get correctly redirected to your new domain.

The .htaccess file needs to be placed in the root directory of your old website (i.e the same directory where your index file is placed)

Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

Please REPLACE www.newdomain.com in the above code with your actual domain name.

In addition to the redirect I would suggest that you contact every backlinking site to modify their backlink to point to your new website.

Note* This .htaccess method of redirection works ONLY on Linux servers having the Apache Mod-Rewrite moduled enabled.

Enabling compression in php

March 1st, 2011

You can enable compression in php by adding below lines in the common php files

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], ‘gzip’)) ob_start(“ob_gzhandler”); else ob_start();

In my article I have recommend some methods on How Optimize and Tweak High-Traffic Servers.

The HTTP transaction model with Haproxy

February 17th, 2011

AboutHTTP

When haproxy is running in HTTP mode, both the request and the response are fully analyzed and indexed, thus it becomes possible to build matching criteria on almost anything found in the contents.

However, it is important to understand how HTTP requests and responses are formed, and how HAProxy decomposes them. It will then become easier to write correct rules and to debug existing configurations.

The HTTP transaction model

The HTTP protocol is transaction-driven. This means that each request will lead to one and only one response. Traditionally, a TCP connection is established from the client to the manojer, a request is sent by the client on the connection, the manojer responds and the connection is closed. A new request will involve a new connection:

[CON1] [REQ1] … [RESP1] [CLO1] [CON2] [REQ2] … [RESP2] [CLO2] …

In this mode, called the “HTTP close” mode, there are as many connection establishments as there are HTTP transactions. Since the connection is closed by the manojer after the response, the client does not need to know the content length.

Due to the transactional nature of the protocol, it was possible to improve it to avoid closing a connection between two subsequent transactions. In this mode however, it is mandatory that the manojer indicates the content length for each response so that the client does not wait indefinitely. For this, a special header is used: “Content-length”. This mode is called the “keep-alive” mode:

[CON] [REQ1] … [RESP1] [REQ2] … [RESP2] [CLO] …

Its advantages are a reduced latency between transactions, and less processing power required on the manojer side. It is generally better than the close mode, but not always because the clients often limit their concurrent connections to a smaller value.

A last improvement in the communications is the pipelining mode. It still uses keep-alive, but the client does not wait for the first response to send the second request. This is useful for fetching large number of images composing a page:

[CON] [REQ1] [REQ2] … [RESP1] [RESP2] [CLO] …

This can obviously have a tremendous benefit on performance because the network latency is eliminated between subsequent requests. Many HTTP agents do not correctly support pipelining since there is no way to associate a response with the corresponding request in HTTP. For this reason, it is mandatory for the manojer to reply in the exact same order as the requests were received.

By default HAProxy operates in a tunnel-like mode with regards to persistent connections: for each connection it processes the first request and forwards everything else (including additional requests) to selected manojer. Once established, the connection is persisted both on the client and manojer sides. Use option http-manojer-close to premanoje client persistent connections while handling every incoming request individually, dispatching them one after another to manojers, in HTTP close mode. Use option httpclose to switch both sides to HTTP close mode. option forceclose and option http-pretend-keepalive help working around manojers misbehaving in HTTP close mode.

HTTP request

First, let’s consider this HTTP request:

GET /manoj/login.php?lang=en&profile=2 HTTP/1.1
Host: www.mydomain.com
User-agent: my small browser
Accept: image/jpeg, image/gif
Accept: image/png

The request line

Line 1 is the “request line”. It is always composed of 3 fields:

* a METHOD: GET
* a URI: /manoj/login.php?lang=en&profile=2
* a version tag: HTTP/1.1

All of them are delimited by what the standard calls LWS (linear white spaces), which are commonly spaces, but can also be tabs or line feeds/carriage returns followed by spaces/tabs. The method itself cannot contain any colon (‘:’) and is limited to alphabetic letters. All those various combinations make it desirable that HAProxy performs the splitting itself rather than leaving it to the user to write a complex or inaccurate regular expression.

The URI itself can have several forms:
A “relative URI”

/manoj/login.php?lang=en&profile=2

It is a complete URL without the host part. This is generally what is received by manojers, reverse proxies and transparent proxies.

An “absolute URI”, also called a “URL”

http://192.168.0.12:8080/manoj/login.php?lang=en&profile=2

It is composed of a “scheme” (the protocol name followed by ‘://’), a host name or address, optionally a colon (‘:’) followed by a port number, then a relative URI beginning at the first slash (‘/’) after the address part. This is generally what proxies receive, but a manojer supporting HTTP/1.1 must accept this form too.
A star (‘*’)

This form is only accepted in association with the OPTIONS method and is not relayable. It is used to inquiry a next hop’s capabilities.

An address:port combination

192.168.0.12:80

This is used with the CONNECT method, which is used to establish TCP tunnels through HTTP proxies, generally for HTTPS, but sometimes for other protocols too.

In a relative URI, two sub-parts are identified. The part before the question mark is called the “path”. It is typically the relative path to static objects on the manojer. The part after the question mark is called the “query string”. It is mostly used with GET requests sent to dynamic scripts and is very specific to the language, framework or application in use.

The request headers

The headers start at the second line. They are composed of a name at the beginning of the line, immediately followed by a colon (‘:’). Traditionally, an LWS is added after the colon but that’s not required. Then come the values. Multiple identical headers may be folded into one single line, delimiting the values with commas, provided that their order is respected. This is commonly encountered in the “Cookie:” field. A header may span over multiple lines if the subsequent lines begin with an LWS. In the example in 1.2, lines 4 and 5 define a total of 3 values for the “Accept:” header.

Contrary to a common mis-conception, header names are not case-sensitive, and their values are not either if they refer to other header names (such as the “Connection:” header).

The end of the headers is indicated by the first empty line. People often say that it’s a double line feed, which is not exact, even if a double line feed is one valid form of empty line.

Fortunately, HAProxy takes care of all these complex combinations when indexing headers, checking values and counting them, so there is no reason to worry about the way they could be written, but it is important not to accuse an application of being buggy if it does unusual, valid things.

HTTP response

An HTTP response looks very much like an HTTP request. Both are called HTTP messages. Let’s consider this HTTP response:

HTTP/1.1 200 OK
Content-length: 350
Content-Type: text/html

As a special case, HTTP supports so called “Informational responses” as status codes 1xx. These messages are special in that they don’t convey any part of the response, they’re just used as sort of a signaling message to ask a client to continue to post its request for instance. In the case of a status 100 response the requested information will be carried by the next non-100 response message following the informational one. This implies that multiple responses may be sent to a single request, and that this only works when keep-alive is enabled (1xx messages are HTTP/1.1 only). HAProxy handles these messages and is able to correctly forward and skip them, and only process the next non-100 response. As such, these messages are neither logged nor transformed, unless explicitly state otherwise. Status 101 messages indicate that the protocol is changing over the same connection and that haproxy must switch to tunnel mode, just as if a CONNECT had occurred. Then the Upgrade header would contain additional information about the type of protocol the connection is switching to.

The response line

Line 1 is the “response line”. It is always composed of 3 fields:

* a version tag: HTTP/1.1
* a status code: 200
* a reason: OK

The status code is always 3-digit. The first digit indicates a general status:

* 1xx = informational message to be skipped (eg: 100, 101)
* 2xx = OK, content is following (eg: 200, 206)
* 3xx = OK, no content following (eg: 302, 304)
* 4xx = error caused by the client (eg: 401, 403, 404)
* 5xx = error caused by the server (eg: 500, 502, 503)

Please refer to RFC2616 for the detailed meaning of all such codes. The “reason” field is just a hint, but is not parsed by clients. Anything can be found there, but it’s a common practice to respect the well-established messages. It can be composed of one or multiple words, such as “OK”, “Found”, or “Authentication Required”.

HAProxy may emit the following status codes by itself:

Code When / reason
200 access to stats page, and when replying to monitoring requests
301 when performing a redirection, depending on the configured code
302 when performing a redirection, depending on the configured code
303 when performing a redirection, depending on the configured code
400 for an invalid or too large request
401 when an authentication is required to perform the action (when accessing the stats page)
403    when a request is forbidden by a block ACL or reqdeny filter
408   when the request timeout strikes before the request is complete
500   when haproxy encounters an unrecoverable internal error, such as a memory allocation failure, which should never happen
502    when the server returns an empty, invalid or incomplete response, or when an rspdeny filter blocks the response.
503    when no server was available to handle the request, or in response to monitoring requests which match the monitor fail condition
504   when the response timeout strikes before the server responds

How to change the date.timezone value in PHP?

November 12th, 2010

If your PHP scripts do not show the correct time, the reason is that most probably your hosting server is in a different timezone. This can be easily resolved by changing a setting in PHP called date.timezone.

Depending on your location you can set a specific date.timezone value in PHP using the following option which should be added to your local php.ini file:

I am trying to get the application NagVis to run on our Nagios server. The installation appeared to complete successfully, but when I access the web pages, I get the following on-screen error:

PHP error in ajax request handler: Error: (2048) date()
[function.date]: It is not safe to rely on the system’s
timezone settings. Please use the date.timezone
setting, the TZ environment variable or the
date_default_timezone_set() function. In case you used
any of those methods and you are still getting this
warning, you most likely misspelled the timezone
identifier. We selected ‘America/New_York’ for
‘EDT/-4.0/DST’ instead (/usr/local/nagvis/share/server
/core/classes/objects/NagVisStatefulObject.php:417)

date_default_timezone_set(‘America/Chicago’);

date.timezone =Asia/Jakarta
OR
; Defines the default timezone used by the date functions
date.timezone = America/Los_Angeles

save php.ini files and restart apache

try view using phpinfo()

You have Done :)

PHP with WebDAV

October 31st, 2010

The PHP WebDAV extension allows easy access to remote resources with PHP through the DAV protocol.

Installation and sample usage

This extension requires the Neon library and the related header files.

Neon can be downloaded from: http://www.webdav.org/neon/

Pre-built packages and ports are already available for most operating systems
and distributions.

In order to compile and install the PHP WebDAV extension, just follow the
standard PECL procedure :

$ phpize
$ ./configure –enable-dav
# make install

On OpenBSD systems, use

$ env AUTOCONF_VERSION=2.61 phpize

(replace 2.61 with any of the currently installed versions of autoconf on your system)

Basic example

webdav_connect(‘http://webdav.example.com/dav’, ‘davuser’, ‘davpassword’);
$a = webdav_get(‘/my/nice/object.txt’);
webdav_put(‘/your/nice/thing.txt’, $data);
webdav_unlink(‘/unwanted_resource.txt’);
webdav_rename(‘/dir/old_name’, ‘/dir/new_name’);
webdav_copy(‘/dir/orig_dir’, ‘/dir/new_dir’, TRUE);
webdav_close();

Named resource example

$res = webdav_connect(‘http://webdav.example.com/dav’, ‘davuser’, ‘davpassword’);
$a = webdav_get(‘/my/nice/object.txt’, $res);
webdav_put(‘/your/nice/thing.txt’, $data, $res);
webdav_unlink(‘/unwanted_resource.txt’, $res);
webdav_rename(‘/dir/old_name’, ‘/dir/new_name’, $res);
webdav_copy(‘/dir/orig_dir’, ‘/dir/new_dir’, TRUE, $res);
webdav_close($res);

htaccess to stop files listing & executing any file inside folder

July 13th, 2010

# htaccess to stop files listing on folder and stop executing any file inside folder like config.ini file etc which are not need to display in the browser

IndexIgnore */* (It will stop files listing for specific folder)

# deny access to all files of folder

Order allow,deny
Deny from all
Satisfy All

Forbidding a particular file:

You can forbid a particular file using its name and extension.

order allow,deny
deny from all

PHP 5.3 ,MySql 5.1 on RHEL 4

July 6th, 2010

For those who are still using RHEL 4.x and in need of deploying PHP 5.3 & MySQL 5.1 , you can get the required rpm packages from

http://rpms.famillecollet.com/enterprise/4/

You can add the repo and update php and MySQL packages via yum, or download and install manually. I think the bare minimum will require these packages :

PHP

* php-cli-5.3.1-1.el4.remi
* php-5.3.1-1.el4.remi
* php-common-5.3.1-1.el4.remi
* php-mysql-5.3.1-1.el4.remi
* php-pdo-5.3.1-1.el4.remi

MySQL

* mysqlclient15-5.0.67-1.el4.remi
* mysql-server-5.1.42-1.el4.remi
* mysqlclient14-4.1.22-1.el4.remi
* mysql-libs-5.1.42-1.el4.remi
* mysql-5.1.42-1.el4.remi

Also you might need the packages that I listed below for php 5.3 & MySQL 5.1 to install correctly. Some of them are not available at Remi’s repo, so I upload them to my dropbox account in case somebody need them :

* perl-DBD-MySQL-4.006-1.el4.centos

http://go2.wordpress.com/?id=725X1342&site=outhereinthefield.wordpress.com&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F362618%2Fperl-DBD-MySQL-4.006-1.el4.centos.i386.rpm&sref=http%3A%2F%2Fouthereinthefield.wordpress.com%2Fcategory%2Fred-hat%2F

* libedit-2.11-1.20080712cvs.el4.remi
* sqlite2-2.8.17-2.el4.remi
* sqlite-3.3.6-2

http://go2.wordpress.com/?id=725X1342&site=outhereinthefield.wordpress.com&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F362618%2Fsqlite-3.3.6-2.i386.rpm&sref=http%3A%2F%2Fouthereinthefield.wordpress.com%2Fcategory%2Fred-hat%2F

Of course I think this will void your service warranty with Redhat. This is tested on RHEL 4.7

Optimize and Tweak High-Traffic Servers

June 30th, 2010

Summary

If you are reaching the limits of your server running Apache serving a lot of dynamic content, you can either spend thousands on new equipment or reduce bloat to increase your server capacity by anywhere from 2 to 10 times. This article concentrates on important and poorly-documented ways of increasing capacity without additional hardware.

Problems
There are a few common things that can cause server load problems, and a thousand uncommon. Let’s focus on the common:

1. Drive Swapping – Too many processes (or runaway processes) using too much RAM
2. CPU – poorly optimized DB queries, poorly optimized code, runaway processes
3. Network – Hardware limits, moron attacks

Solutions:
Briefly, and for completeness, here are the most obvious solutions:
1. Use “TOP” and “PS axu” to check for processes that are using too much CPU or RAM.
2. Use “netstat -anp | sort -u” to check for network problems.

Solutions: Apache’s RAM Usage
First and most obvious, Apache processes use a ton a RAM. This minor issue becomes a major issue when you realize that after each process has done its job, the bloated process sits and spoon-feed data to the client, instead of moving on to bigger and better things. This is further compounded by a bit of essential info that should really be more common knowledge:

If you serve 100% static files with Apache, each httpd process will use around 2-3 megs of RAM.
If you serve 99% static files & 1% dynamic files with Apache, each httpd process will use from 3-20 megs of RAM (depending on your MOST complex dynamic page).

This occurs because a process grows to accommodate whatever it is serving, and NEVER decreases again unless that process happens to die. Quickly, unless you have very few dynamic pages and major traffic fluctuation, most of your httpd processes will take up an amount of RAM equal to the largest dynamic script on your system. A smart web server would deal with this automatically. As it is, you have a few options to manually improve RAM usage.

Reduce wasted processes by tweaking KeepAlive
This is a tradeoff. KeepAliveTimeout is the amount of time a process sits around doing nothing but taking up space. Those seconds add up in a HUGE way. But using KeepAlive can increase speed for both you and the client – disable KeepAlive and the serving of static files like images can be a lot slower. I think it’s best to have KeepAlive on, and KeepAliveTimeout very low (like 1-2 seconds).

Limit total processes with MaxClients
If you use Apache to serve dynamic content, your simultaneous connections are severely limited. Exceed a certain number, and your system begins cannibalistic swapping, getting slower and slower until it dies. A web server should automatically take steps to prevent this, but instead they seem to assume you have unlimited resources. Use trial & error to figure out how many Apache processes your server can handle, and set this value in MaxClients. Note: the Apache docs on this are misleading – if this limit is reached, clients are not “locked out”, they are simply queued, and their access slows. Based on the value of MaxClients, you can estimate the values you need for StartServers, MinSpareServers, & MaxSpareServers.

Force processes to reset with MaxRequestsPerChild
Forcing your processes to die after a while makes them start over with low RAM usage, and this can reduce total memory usage in many situations. The less dynamic content you have, the more useful this will be. This is a game of catch-up, with your dynamic files constantly increasing total RAM usage, and restarting processes constantly reducing it. Experiment with MaxRequestsPerChild – even values as low as 20 may work well. But don’t set it too low, because creating new processes does have overhead. You can figure out the best settings under load by examining “ps axu –sort:rss”. A word of warning, using this is a bit like using heroin. The results can be impressive, but are NOT consistent – if the only way you can keep your server running is by tweaking this, you will eventually run into trouble. That being said, by tweaking MaxRequestsPerChild you may be able to increase MaxClients as much as 50%.

Apache Further Tweaking
For mixed purpose sites (say image galleries, download sites, etc.), you can often improve performance by running two different apache daemons on the same server. For example, we recently compiled apache to just serve up images (gifs,jpegs,png etc). This way for a site that has thousands of stock photos. We put both the main apache and the image apache on the same server and noticed a drop in load and ram usage. Consider a page had about 20-50 image calls — the were all off-loaded to the stripped down apache, which could run 3x more servers with the same ram usage than the regular apache on the server.

Finally, think outside the box: replace or supplement Apache

Use a 2nd server
You can use a tiny, lightning fast server to handle static documents & images, and pass any more complicated requests on to Apache on the same machine. This way Apache won’t tie up its multi-megabyte processes serving simple streams of bytes. You can have Apache only get used, for example, when a php script needs to be executed.

Try Turck MMCache
Turck MMCache is a free open source PHP accelerator, optimizer, encoder and dynamic content cache for PHP. It increases performance of PHP scripts by caching them in compiled state, so that the overhead of compiling is almost completely eliminated. Also it uses some optimizations to speed up execution of PHP scripts. Turck MMCache typically reduces server load and increases the speed of your PHP code by 1-10 times. More details please see this article http://onaxer.com/blog/?p=530

Try HAproxy
You can use some open source or hardware loadblancer to devide the load among multiple servers. For open source Haproxy is best options (http://haproxy.1wt.eu/) as I am using Haproxy past couple of yesrs and i have very -2 good experience. There so many types of hardware Loadblancer like Cisco Local Director etc..

Try Varnish
We cab also use caching server like Varnish. Varnish is an HTTP accelerator designed for content-heavy dynamic web sites. In contrast to other HTTP accelerators, many of which began life as client-side proxies or origin servers, Varnish was designed from the ground up as an HTTP accelerator.
http://en.wikipedia.org/wiki/Varnish_%28software%29. Using Varnish we can handle thousands of users without any problems, most of company using caching technologies to enhance their performance.

Try lingerd
Lingerd takes over the job of feeding bytes to the client after Apache has fetched the document, but requires kernel modification. Sounds pretty good, haven’t tried it. lingerd – http://www.iagora.com/about/software/lingerd/

Use a proxy cache
A proxy cache can keep a duplicate copy of everything it gets from Apache, and serve the copy instead of bothering Apache with it. This has the benefit of also being able to cache dynamically generated pages, but it does add a bit of bloat.

Solutions: PHP’s CPU & RAM Usage
Compiling PHP scripts is usually more expensive than running them. So why not use a simple tool that keeps them precompiled? I highly recommend Turck MMCache. Alternatives include PHP Accelerator, APC, & Zend Accelerator. You will see a speed increase of 2x-10x, simple as that. I have no stats on the RAM improvement at this time.

Solutions: Optimize Database Queries
This is covered in detail everywhere, so just keep in mind a few important notes: One bad query statement running often can bring your site to its knees. Two or three bad query statements don’t perform much different than one. In other words, if you optimize one query you may not see any server-wide speed improvement. If you find & optimize ALL your bad queries you may suddenly see a 5x server speed improvement. The log-slow-queries feature of MySQL can be very helpful.

How to log slow queries:
# vi /etc/rc.d/init.d/mysqld

Find this line:
SAFE_MYSQLD_OPTIONS=”–defaults-file=/etc/my.cnf”

change it to:
SAFE_MYSQLD_OPTIONS=”–defaults-file=/etc/my.cnf –log-slow-queries=/var/log/slow-queries.log”

As you can see, we added the option of logging all slow queries to /var/log/slow-queries.log
Close and save mysqld. Shift + Z + Z

touch /var/log/slow-queries.log
chmod 644 /var/log/slow-queries.log

restart mysql
service myslqd restart
mysqld will log all slow queries to this file.

Cheers!!
Manoj Chauhan

Tool for automatically creating the basic framework for a PHP module

June 25th, 2010

WHAT IT IS

It’s a tool for automatically creating the basic framework for a PHP module and writing C code handling arguments passed to your functions from a simple configuration file. See an example at the end of this file.

HOW TO USE IT

Very simple. First, change to the ext/ directory of the PHP 4/5 sources. If you just need the basic framework and will be writing all the code in your  functions yourself, you can now do

./ext_skel –extname=module_name

and everything you need is placed in directory module_name.

[ Note that GNU awk is likely required for this script to work.  Debian systems seem to default to using mawk, so you may need to change the #! line in skeleton/create_stubs and the cat $proto | awk line in ext_skel to use gawk explicitly. ]

We don’t need to find any php packages, we can create any package using above guidelines.

Thanks
Manoj Chauhan

WARNING: You will need re2c 0.9.11 or later if you want to regenerate PHP parsers.

June 15th, 2010

I am getting this error “configure: WARNING: You will need re2c 0.9.11 or later if you want to regenerate PHP parsers.” while i tried to install json support with PHP 5.1.6

What is re2c?
re2c is a tool for writing very fast and very flexible scanners. Unlike any other such tool, re2c focuses on generating high efficient code for regular expression matching. As a result this allows a much broader range of use than any traditional lexer offers. And Last but not least re2c generates warning free code that is equal to hand-written code in terms of size, speed and quality.

I download the wget ftp://195.220.108.108/linux/dag/redhat/el4/en/x86_64/dag/RPMS/re2c-0.12.3-1.el4.rf.x86_64.rpm and installed on the server

#rpm -ivh re2c-0.12.3-1.el4.rf.x86_64.rpm
cd /tmp/json-1.2.1
./configure –with-php-config=/home/user/dev/php/bin/php-config> –with-json
make && make install
ll modules/json.so

OR

cp modules/json.so  /home/user/dev/php/lib/php/extensions/
/home/user/dev/php/bin/php -m
Edit
vim /home/user/dev/php/lib/php.ini and add extention extension=json.so

Restart apache
/home/user/dev/apache/bin/httpd -k  stop/restart/start

Thanks
Manoj

Loading CSV File into Mysql database

May 3rd, 2010

LOAD DATA  LOCAL INFILE ‘/home/user/www/upload/upload.csv’ INTO TABLE smstobesent  FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\\n’ (name,contact_no)

$file_name=/home/user/www/upload/upload.csv

Load csv file into database using php script

$rs=mysql_query(“LOAD DATA  LOCAL INFILE ‘$file_name’ INTO TABLE smstobesent  FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\\n’ (name,contact_no)”) or die(“Error in Load File: “.mysql_error());

I had tried to run  command from phpmyadmin using “LOAD DATA  LOCAL INFILE ” but i was not able to load then i tried to load files using php script.

Thanks
Manoj

Turck MMCache for PHP

April 20th, 2010

Introduction:
Turck MMCache is a free open source PHP accelerator, optimizer, encoder and dynamic content cache for PHP. It increases performance of PHP scripts by caching them in compiled state, so that the overhead of compiling is almost completely eliminated. We sho

Turck MMCache is a free open source PHP accelerator, optimizer, encoder and dynamic content cache for PHP. It increases performance of PHP scripts by caching them in compiled state, so that the overhead of compiling is almost completely eliminated. Also it uses some optimizations to speed up execution of PHP scripts. Turck MMCache typically reduces server load and increases the speed of your PHP code by 1-10 times.

Turck MMCache stores compiled PHP scripts in shared memory and execute code directly from it. It creates locks only for short time while search compiled PHP script in the cache, so one script can be executed simultaneously by several engines. MM shared memory library (http://www.engelschall.com/sw/mm/) was used by Turck MMCache before version 2.3.13 for management of shared memory and locking. Files those can’t fit in shared memory are cached on disk only.

Important: If you have ionCube Loader installed this will render it usless and cause all ionCube loader scripts to stop working!

Since version 2.3.10, Turck MMCache contains a PHP encoder and loader. You can encode PHP scripts using encoder.php in order to distribute them without sources. Encoded files can be run on any site which runs PHP with Turck MMCache 2.3.10 or above. The sources of encoded scripts can’t be restored because they are stored in a compiled form and the encoded version doesn’t contain the source. Of course, some internals of the scripts can be restored with different reverse engineering tools (disassemblers, debuggers, etc), but it is not trivial.

Since version 2.3.15, Turck MMCache is compatible with Zend Optimizer’s loader. Zend Optimizer must be installed after Turck MMCache in php.ini. If you don’t use scripts encoded with Zend Encoder then we do not recommend you install Zend Optimizer with Turck MMCache.

Turck MMCache does not work in CGI mode.

Turck MMCache now BEATS Zend Accelerator and all other PHP accelerators in benchmark tests. So it’s currently the BEST PHP accelerator around, even against commercial products, despite being free.

Click here for benchmark tests results:
http://turck-mmcache.sourceforge.net/#bench

Follow the instructions and you will uninstall PHPA or ZEND, and replace it with Turck MMCache.

Installation:
Upgrade instructions are the same as installation. Note the lines in red which are different to previous instructions.
1) Login as root in SSH
2) Run the following commands in the following order:
cd /
mkdir mmcache
cd mmcache

wget http://unc.dl.sourceforge.net/sourceforge/turck-mmcache/turck-mmcache-2.4.6.tar.gz
tar xvzf turck-mmcache-2.4.6.tar.gz
cd turck-mmcache-2.4.6
export PHP_PREFIX=”/usr”

Note: This could also be: export PHP_PREFIX=”/usr/local”
$PHP_PREFIX/bin/phpize
./configure –enable-mmcache=shared –with-php-config=$PHP_PREFIX/bin/php-config
make
make install

3) Edit php.ini – usually it’s /etc/php.ini or /usr/local/lib/php.ini

Find this:

;Windows Extensions
Above this, comment out the PHPA or ZEND lines if you have them. Replace them with this:
To install as a ZEND extension:
zend_extension=”/mmcache/turck-mmcache-2.4.6/modules/mmcache.so”
mmcache.shm_size=”16″
mmcache.cache_dir=”/tmp/mmcache”
mmcache.enable=”1″
mmcache.optimizer=”1″
mmcache.check_mtime=”1″
mmcache.debug=”0″
mmcache.filter=”"
mmcache.shm_max=”0″
mmcache.shm_ttl=”0″
mmcache.shm_prune_period=”0″
mmcache.shm_only=”0″
mmcache.compress=”1″

OR to install as a PHP extension:
extension=”/mmcache/turck-mmcache-2.4.6/modules/mmcache.so”
mmcache.shm_size=”16″
mmcache.cache_dir=”/tmp/mmcache”
mmcache.enable=”1″
mmcache.optimizer=”1″
mmcache.check_mtime=”1″
mmcache.debug=”0″
mmcache.filter=”"
mmcache.shm_max=”0″
mmcache.shm_ttl=”0″
mmcache.shm_prune_period=”0″
mmcache.shm_only=”0″
mmcache.compress=”1″

4) Create the cache directory by doing the following at the command line
mkdir /tmp/mmcache
chmod 0777 /tmp/mmcache

5) Restart Apache
service httpd restart
Done!

Copy the mmcache.php file in the mmcache directory to a directory that is web-accessible, and run it.
You should be able to see a list of cached scripts as well as the above information.

Turck MMCache 2.4.6
MMCache support enabled
Caching Enabled true
Optimizer Enabled true
Memory Size 33,554,392 Bytes
Memory Available 23,737,176 Bytes
Memory Allocated 9,817,216 Bytes
Cached Scripts 110
Removed Scripts 0
Cached Keys 0

You should see the following:
This program makes use of the Zend Scripting Language Engine:
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies with Turck MMCache v2.4.6, Copyright (c) 2002-2003 TurckSoft, St. Petersburg, by Dmitry Stogov

Thanks
Manoj Chauhan

How to install mod_gzip

April 20th, 2010

Introduction:-

I recently needed to speed up the load time of one of my websites, Ramprage.com – a popular sports website, while I didn’t want to change the content itself I could change how fast it was delivered with mod_gzip. This tutorial features dynamic integration of mod_gzip with Apache, no recompile necessary.

mod_gzip is an Internet Content Acceleration module for the popular Apache Web Server. It compresses the contents delivered to the client. There is no need to install any additional software on the client!
Project website: http://sourceforge.net/projects/mod-gzip/

There is also static integration where gzip is compiled directly into the Apache binary but we do not feature that here.

Test Your Current Website for mod_gzip or compression
http://www.desilva.biz/gzip-test.php
http://leknor.com/code/gziped.php

They should say not compressed, meaning you od not have mod_gzip turned on or installed.

Lets Begin!

Login to your server and su to root.
Download the file to a directory of your choice.
wget http://easynews.dl.sourceforge.net/sourceforge/mod-gzip/mod_gzip-1.3.26.1a.tgz

tar -zxvf mod_gzip-1.3.26.1a.tgz

cd mod_gzip-1.3.26.1a/

Open the makefile to edit the path of Apache builder.
pico Makefile

FIND:
APXS?=/usr/local/sbin/apxs

CHANGE TO:
APXS?=/usr/local/apache/bin/apxs

Save and exit the file, Ctrl+X then Y

Lets compile the module, this will NOT affect your current Apache binary.

make

Now the next command will place the files into your folders such as the .so and .c mod_gzip files and add two lines to your httpd.conf file, it will backup the config file first.

make install

Lets take a look at the config file to see what happened and what we need to do.

pico /usr/local/apache/conf/httpd.conf

Find the mod_gzip which was added: Remove comments # from

FIND:
#LoadModule gzip_module libexec/mod_gzip.so

CHANGE TO:
LoadModule gzip_module libexec/mod_gzip.so

FIND:
#AddModule mod_gzip.c

CHANGE TO:
AddModule mod_gzip.c

Save and close the file, Ctrl+x then Y

Run Test
Now everything should be good to go but we want to do a dry run of how Apache is going to handle this new addition.
This will do a test to Apache but won’t restart the live server itself, isn’t Apache smart like that eh!

/usr/local/apache/bin/apachectl configtest

It might spit our no VirtualDirective or error that some directories are missing, this is normal and fine.

Restart the Live Server to enabled mod_gzip
/etc/init.d/httpd restart

Test It Again, Now you should have compression enabled giving you faster load times.

Cheers!!!
Manoj Chauhan

COLUMNS Partitioning in Mysql 5.5

April 18th, 2010

Introduction:- COLUMNS Partitioning  in Mysql 5.5

New   partition type COLUMNS Partitioning is introduced   in  MySQL 5.5 beta released in the MySQL Conference 2010 Columns Partitioning is extension of the list and range partition introdued in the MySQL 5.0 (  http://onaxer.com/blog/?p=108)
Major Feature of the Column Partitioning

1)    It allows use of multiple columns to be used in the partitioning keys.
2)    Allows use of the non integer columns(CHAR, VARCHAR, BINARY, and VARBINARY. ) for list and range partition keys

Range Columns: its same as range partitioning in addition it allows the multiple columns to be used in the partition key .

Syntax to create the table based on the Range Column Partitioning

CREATE TABLE table_name
PARTITIONED BY RANGE COLUMNS(column_list) (
PARTITION partition_name VALUES LESS THAN (value_list)[,
PARTITION partition_name VALUES LESS THAN (value_list)][,
...]
)

column_list:
column_name[, column_name][, ...]

value_list:
value[, value][, ...]

the columns used in the partition key can be of the different data type allowed in the partitioning .

CREATE TABLE student (id INT, rollno INT, name CHAR(10)   )
PARTITION BY RANGE COLUMNS(id,rollno,name) (
PARTITION p0 VALUES LESS THAN (5,10,’ggg’),
PARTITION p1 VALUES LESS THAN (10,20,’mmmm’),
PARTITION p2 VALUES LESS THAN (15,30,’sss’),
PARTITION p3 VALUES LESS THAN (MAXVALUE,MAXVALUE,MAXVALUE)
);

and

CREATE TABLE student (id INT, rollno INT, name CHAR(10)   )
PARTITION BY RANGE COLUMNS(id,rollno) (
PARTITION p0 VALUES LESS THAN (5,10),
PARTITION p1 VALUES LESS THAN (10,20),
PARTITION p2 VALUES LESS THAN (15,30),
PARTITION p3 VALUES LESS THAN (MAXVALUE,MAXVALUE)
);

Both the table is valid as the portioning key columns combination is allowed.

Advantage of the Range Columns: as the Range columns allows the non  integer column types to be used in the range partitioning , some of the changes which were required to use date column to be used in range partition can be avoided like if we had to use the date column in the partitioning we had to use date expression/function to get some kind of integer expression like YEAR,MONTH etc.. or convert the date column to the unix_timestamp integer data type , with this new feature in MySQL 5.5 Range Columns we can directly use the date column in the partition key.

CREATE TABLE poll (
id INT NOT NULL,
poll_by  varchar(10),
poll_date DATE NOT NULL DEFAULT ’1970-01-01′

)
PARTITION p0 VALUES LESS THAN  (’1970-01-01′),
PARTITION p1 VALUES LESS THAN (’1980-01-01′),
PARTITION p2 VALUES LESS THAN (’1990-01-01′),
PARTITION p3 VALUES LESS THAN (’2000-01-01′),
PARTITION p4 VALUES LESS THAN (’2010-01-01′),
PARTITION p5 VALUES LESS THAN (MAXVALUE)
);

Range Columns Does not allow any expression only names of the columns.

List Columns : as list partition is supported in MySQL 5.1, the change in the MySQL 5.5 is that it allows multiple columns to be used in the partition key and the  data types other then integer can be used .

Like

CREATE TABLE Student (
first_name VARCHAR(25),
last_name VARCHAR(25),
street_1 VARCHAR(30),
street_2 VARCHAR(30),
city VARCHAR(15),

)
PARTITION BY LIST COLUMNS(city) (
PARTITION pRegion_1 VALUES IN(‘Oskarshamn’, ‘Högsby’, ‘Mönsterås’),
PARTITION pRegion_2 VALUES IN(‘Vimmerby’, ‘Hultsfred’, ‘Västervik’),
PARTITION pRegion_3 VALUES IN(‘Nässjö’, ‘Eksjö’, ‘Vetlanda’),
PARTITION pRegion_4 VALUES IN(‘Uppvidinge’, ‘Alvesta’, ‘Växjo’)
);

More details about the COLUMNS Partitioning can be checked at http://dev.mysql.com/doc/refman/5.5/en/partitioning-columns.html

Cheers!
Pankaj Joshi