Author: Santhosh Tirunahari

How to optimize PHP code (tips)

How to optimize PHP code (tips)

Introduction –

1. If a method can be static, declare it static. Speed improvement is by a factor of 4.

2. echo is faster than print.

3. Use echo’s multiple parameters instead of string concatenation.

4. Set the max value for your for-loops before and not in the loop.

5. Unset your variables to free memory, especially large arrays.

6. Avoid magic like __get, __set, __autoload

7. require_once() is expensive

8. Use full paths in includes and requires, less time spent on resolving the OS paths.

9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()

10. See if you can use strncasecmp, strpbrk and stripos instead of regex

11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.

13. It’s better to use select statements than multi if, else if, statements.

14. Error suppression with @ is very slow.

15. Turn on apache’s mod_deflate

16. Close your database connections when you’re done with them

17. $row[’id’] is 7 times faster than $row[id]

18. Error messages are expensive

19. Do not use functions inside of for loop, such as for ($x=0; $x <>

20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

21. Incrementing a global variable is 2 times slow than a local var.

22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.

26. Methods in derived classes run faster than ones defined in the base class.

27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

28. Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.

29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.

30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.

31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.

32. Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

Example –

if (strlen($foo) < 5) { echo “Foo is too short”; }


if (!isset($foo{5})) { echo “Foo is too short”; }

** Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.

34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

36. Do not implement every data structure as a class, arrays are useful, too

37. Don’t split methods too much, think, which code you will really re-use

38. You can always split the code of a method later, when needed

39. Make use of the countless predefined functions

40. If you have very time consuming functions in your code, consider writing them as C extensions

41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview.

42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%.



Santhosh T.


PHP – IP address to Country

PHP – IP address to Country

Introduction –

This is not exactly a tutorial, but a small trick, to access demo as a web-service. does provide a nice CSV format of transferring IPs to country. Pretty amazing. But the problem is you need to have a good DB support at your end to use it

For example –


$ip = $_GET[‘ip’];

function get_country($ip)


$f = fsockopen(‘’, 80);

if (!$f)


return false;


$postdata = “ip_address=”.urlencode($ip).”&submit=”.urlencode(‘Find Country’);

$request = ”;

$request .= “POST /node/view/36 HTTP/1.1\r\n”;

$request .= “Host:\r\n”;

$request .= “User-Agent: Its me again\r\n”;

$request .= “Content-Length: “.strlen($postdata).”\r\n”;

$request .= “Content-Type: application/x-www-form-urlencoded\r\n”;

$request .= “\r\n”;

$request .= “$postdata\r\n”;

fwrite($f, $request);

$response = ”;

while (!feof($f))


$response .= fgets($f, 128);


$pos1 = strpos ( $response , ‘</from>’);

$pos2 = strpos ( $response , ‘<br><br><img’ , $pos1 );

$parse_from = substr( $response, $pos1+21, ($pos2-$pos1) );

$pattern = “/<b>([^\/]*)<\/b>/si”;

preg_match_all($pattern, $parse_from, $matches);

return $matches[1][1];


echo (get_country($ip));


Thank you,

Santhosh Tirumahari

How to secure Session in PHP

How to secure Session in PHP

Introduction – 

1) Shared web servers— Anyone else on the server can read your session files (typically in the /tmp directory) if PHP is running as an Apache module (so the session files belong to the web user) and possibly when PHP is used as a CGI (depending on how sessions are implemented).

Someone browsing the session files (probably) won’t know the site the server the sessions apply to (so may not be able to use a username / password combination they found) but you may still be putting sensitive info (like credit card details) somewhere for all to see. Plus they’ve got a list of valid session IDs…

If you’re just storing passwords in the session, you can get away with this by using md5() (preferably twice) to one-way encypt the password. This doesn’t help though if you need to recover the value of a session variable.

Using a custom session handler to store the sessions in a database is probably the best solution. You might consider MySQL HEAP tables if performance is an issue (assuming MySQL running on same machine as Apache). If it gets to very high traffic, it’s time to think about getting your own server…

2) XSS exploits (and session hijacking) – Using JavaScript users can be fooled into giving away their active session_id…

All someone needs to “hijack” a session is the unique session id. It’s like the key to a railway station locker. The locker doesn’t check you’re the valid owner of the key, before allowing you to open it so anyone with the key can get in.

Research XSS and how to prevent it –

Accept that session hijacking cannot be entirely prevented (checks on IP address, for example, is foiled by AOL, who assign a new client IP on more or less every page request) so double check “critical actions” a user can perform when logged in e.g. when changing password—require the old password, which the session hijacker will (hopefully) not know. Displaying credit card information—do like Amazon and only display the last four digits. Basically limit the damage someone can do if they hijack a session.

3) Session IDs in URL (and hijacking) – If you’re using session IDs in the URL (as opposed to a session cookie), make sure offsite links do not contain the session ID (or the remote site will be able to hijack) – PHP should take care of this. Also your visitors may give away the session ID in the referrer field—ideally pass off site links through a redirect page, to elimate the referrer (although, unfortunately, some browsers keep the last 3 pages viewed I believe—unsure of facts).

** Ideally, don’t pass session ids in the URL—require users to accept a cookie if they need to “log in”.

4) Session Fixation (pre-hijacking) (see

If you assign a session to a visitor to your site, before they are logged in (for example for clickpath analysis), make sure that you assign them a new session id when they do login, so that if someone pre-generated the initial session id for them, they won’t get the new ID.

For PHP 4.2.0+, see session_regenerate_id() (in particular the user submitted comments). For PHP < href=””>session_id() function may also be useful (haven’t explored it in this context myself).

5) Sniffing Packets (use SSL/HTTPS) – a session ID can be “sniffed” between the client and your server. If it’s a site where money is changing hands or other sensitive personal information is involved, SSL is a requirement.

Otherwise, without SSL, you have to live with the risk (just like you do every time you use that FTP client…).

6) Cookies are not for session data – on a related note, don’t use cookies for store sensitive information.

Cookie data, unlike sessions, gets stored on the client site. Apart from the “sniffing risk”, a large majority of Windows users have little idea of security and may be “owned by haxor”.

Otherwise, cookies (aside from session cookie PHP creates for you) are generally meant for long term (i.e. between visits) data persistance (e.g. “Remember Me”) rather than “active session” persistance.

There’s probably more things to watch out for (or facts to correct) – suggestions appreciated.

Thank you,

Santhosh Tirunahari

PHP – Web 2.0 and the AJAX

PHP – Web 2.0 and the AJAX

Introduction –

Web 2.0 is a strange thing in that it doesn’t really exist. You can’t buy Web 2.0; you can’t buy a Web 2.0 programming language, and you can’t buy Web 2.0 hardware. In many ways, the phrase “Web 2.0” is a marketing phrase like “paradigm shift” or “the big picture“. The reason for this vagueness is that Web 2.0 doesn’t have a tightly defined definition. What the phrase Web 2.0 tries to express is, that modern websites are so much better than early websites that they’d better be given a different name. So it is down to marketing.

Web developers need to demonstrate that they may use the same Internet, the same web browsers and the same web servers as their competitors, yet their websites are in fact an order of magnitude better. Our competitors only do websites. We do Web 2.0 websites!

The client is, of course, hugely impressed that his new website will be a Web 2.0 website. But what should he expect to see for his money? What is the client’s view of what Web 2.0 should offer? Is it all smelling of roses or are there some thorny issues too?

I propose that there are in fact three facets to a Web 2.0 website:


2. Social Networking (Building Communities)

3. Broadband

AJAX is technical and can only be performed by a technically skilled developer, social networking is vague, woolly and is based more on marketing models than web skills, and broadband has been popular for a long time. Even stranger is the fact that AJAX has been available to developers for at least 5 years, and social networking has been around even longer. It is simply the re-branding of these things that is causing the rise in the popularity of these old but current “buzzword” technologies.

AJAX is a mash up of technologies. We’ve had asynchronous JavaScript and XML for many years, but until somebody said “I name this mash up – AJAX it remained out of the mainstream. The same goes with social networking. Forums, blogs, and community-based websites have been around for many years, but giving it a title like “social networking” combined with the success of websites such as and makes it mainstream and popular. And to cap it all, the new names invented to re-brand existing technologies are combined into the all encompassing name of Web 2.0(simply rebranding the rebranded).

In summary, we’ve had the ability to create Web 2.0 websites for years. It is not new technology; it is simply the renaming and repackaging of something we already have and enjoy. Marketing has made buzzwords of what we already knew and the public and developers are lapping it up.

The third facet of Web 2.0 was broadband, or as I prefer to call it, broadband abuse. Many developers believe that Web 2.0 is defined by how long it takes to download a website or the size of the broadband connection required to view the site comfortably. They believe that the bigger the connection required or the longer the website takes to download, the more Web 2.0ish the website must be. In my opinion, however, adding vast images, video footage, badly implemented rounded corners and streaming music does not make a Web 2.0 website. It simply makes a regular website that is bloated and annoying.

Presuming that you understand what makes a Web 2.0 website and you are keen to build one, there is an important area that you should consider before you start. And that is the area of Search Engine Optimization.

So what about search engines? Do Web 2.0 websites perform well on search engines? Do search engines need to change to keep pace with development? If we ignore the broadband abusers and look at the two key facets of Web 2.0, AJAX, and social networking we get two very different answers.

Working somewhat in reverse here, the conclusion is that AJAX is a search engine killer. Adding AJAX functionality to your website is like pulling the plug on your search engine strategy. Social networking sites on the other hand typically perform exceptionally well on search engines due to their vast amount of visitor provided content.

The reason AJAX is a search engine killer is pretty obvious once you know how the technology works, and at the risk of offending all the people who know this already, I’ll recap in a brief paragraph.

Simply put, AJAX removes the need to refresh a page in a browser. Say for example, you are on the product-finding page of a website, you can type in a search phrase for the product you want to find and press the submit button. Without refreshing the page, the asynchronous JavaScript runs off, grabs the results of the search, and inserts the details of the found products into the very same page as you sit and look at it.

For the website user this addition of AJAX to the website feels fantastic. No page reloads, no browser flicker, no click noise, but sheer joy. And so the rush for AJAX websites begins, because the visitors will love it.

But what about the search engines, what will they make of web pages that use AJAX to find content? Importantly, search engines don’t run JavaScript. Oh no, not ever, no way José. So the search engine will never run your AJAX. To the search engine, huge areas of your website content are now hidden, never to be spidered, indexed, or found. This really limits the usefulness of AJAX in many applications.

An ideal application of AJAX is Google Maps, where as you drag the map around the browser window, the newly exposed areas of the map are retrieved and shown on the page without a page refresh—smooth, seamless, and very impressive. Does Google care if the single map page gets found by searching? Certainly not!

A very poor application of AJAX is the product portfolio where you can find and view product details for hundreds of products without ever refreshing the page. Nice to use? Yes. Navigation friendly? No—try hitting the back button when the browser ignores your last 20 clicks because you have remained on the same page! Search engine friendly? Forget it. You are invisible.

So what is the solution to the AJAX invisibility cloak that Master Harry Potter himself would be proud of? There are 5 options –

  1. Build two websites, one using AJAX that is lovely for visitors and another using more traditional techniques for search engine spiders to find. If you can find a client to finance both, you have found a client with too much money!

  2. Drop AJAX. Let the visitors suffer the page refresh.

  3. Run with AJAX anyway and just put up with the fact that your perfectly formed website will receive no search engine visitors.

  4. Lobby the major search engines to rebuild their spidering algorithms to take into account AJAX pages and to run JavaScript on the pages they index. This option might take some time.

  5. Increase your Google Ad words payments and ramp up traditional advertising to counteract the missing website traffic from the search engines.

And so, a bleak picture of AJAX is painted and by implication of Web 2.0 as well. The good applications of AJAX and Web 2.0 are few and far between, but when you do find them they are fantastic. Do you remember that feeling when you fist used Google Maps? Do you find that all other mapping websites now feel old fashioned? I would go as far as to say that it was Google Maps that single-handedly bought the technology of AJAX to the masses.

The second most impressive application of AJAX is another Google idea, where when typing in the search field on the Google website, AJAX is used to find results even as you type the words—incredibly quick to use, fantastic for the website visitor, and really demonstrating the technology in a great light.

Isn’t it hugely ironic then that the one website that demonstrates so well the very technology that, if used on our own websites, will force us to spend more on Google Ad words, is in fact Google.


Thank you,

Santhosh T.


PHP – How to Filter/validate IP Address?

PHP – How to Filter/validate IP Address?

Introduction –

Many times, we need to validate an IP Address. Of course, and IP address may be of different formats for ipv4 and ipv6. An IP address may also need to be within a range of private or reserved ranges. The filter extension makes it possible to discern these differences and to validate an IP address to fit most needs. In its simplest form the validation of a URL will look like this….

// Valid IP address
$ip = “”;

if(filter_var($ip, FILTER_VALIDATE_IP) === FALSE)
echo “$ip is not a valid IP”;
echo “$ip is valid”;

As we have supplied the above with a valid IP address it validates and all is well. But now we may wish to validate an IPv6 address or an address with a private range. The IP Filter has several flag with which to validate an IP address with.

Flag are for IP Filter –





** Starting at the top we will check to see if an IP is a valid IPv4 address.

// Valid IP address
$ip = “192.168.0”;

// try to validate as IPV4 address
echo “$ip is not a valid IP”;
echo “$ip is valid”;

In the above example the IP address has failed to validate as it is not a complete IPv4 address. It would need to be of the form of the example that preceded it, to validate. This is fine, but growth of the net has seen us run out of IPv4 addresses and so we need to validate against IPv6 addresses also….


Thank you,

Santhosh Tirunahari

PHP4 and PHP5

PHP4 and PHP5

Introductions –

First starts with PHP4 features. PHP4 started up with object-oriented concepts like as c++. PHP4 got almost all the OOPs features. With little difference in functionality…


Below are PHP4 added features –


  1. class

  2. extends

  3. Constructors

  4. Scope Resolution Operator (::)

  5. parent

  6. Serializing objects – objects in sessions

  7. The magic functions __sleep and __wakeup

  8. References inside the constructor

  9. Comparing objects


PHP 5 now came up with new Object Model. Even php4 contains the object model functionalities but PHP5 handling of objects has been completely rewritten, allowing for better performance and more features.

Features Of PHP5 –

  1. Constructors and Destructor

  2. Visibility

  3. Scope Resolution Operator (::)

  4. Static Keyword

  5. Class Constants

  6. Class Abstraction

  7. Object Interfaces

  8. Overloading

  9. Object Iteration

  10. Patterns

  11. Magic Methods

  12. Final Keyword

  13. Object cloning

  14. Comparing objects

  15. Reflection

  16. Type Hinting

  17. Late Static Binding


Some of the above features are in PHP4. But still PHP5 has got improved functionalities on above features. Some of the syntaxes are changed.

Thank you,

Santhosh Tirunahari

PHP – Oracle Connectivity

PHP – Oracle Connectivity

Introductions –

Using PHP we can connect many databases like MySQL, Postgresql, DB2, Oracle and SQL server very easily. Now this article provides the information about database connectivity to Oracle using PHP

PHP Oracle functions allow you to access Oracle 10, Oracle 9, Oracle 8 and Oracle 7 databases using the Oracle Call Interface (OCI). They support binding of PHP variables to Oracle placeholders, have full LOB, FILE and ROWID support, and allow you to use user-supplied define variables.

Configuration part in windows php_oci8.dll is the connectivity dll in windows environment. In Linux we can compile php with oracle module

Once the configuration completes you will be able to see this configuration when you execure –

URL = http://localhost/phpinfo.php





** Basic example to connect ORACLE database and execute query –

root@arunbagul:~# cat /var/www/php_oracle.php

$conn = oci_connect(‘hr’, ‘hr’, ‘orcl’);
if (!$conn) {
$e = oci_error();
print htmlentities($e[‘message’]);


$stid = oci_parse($conn, $query);
if (!$stid) {
$e = oci_error($conn);
print htmlentities($e[‘message’]);

$r = oci_execute($stid, OCI_DEFAULT);
if (!$r) {
$e = oci_error($stid);
echo htmlentities($e[‘message’]);

Other way to connect to oracle using simple Oracle functions. But these functions are deprecated. Now a day’s oci8 functions are in used.

Santhosh Tirunahari



Introductions –

PHP provides FTP library to connect to file server using File Transfer Protocol. No external libraries are needed to build this extension. In order to use FTP functions with your PHP configuration, you should add the –enable-ftp or –with-ftp option when installing PHP 5 and other versions. The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions…

** Once the installation is done you can check by executing the below script –

URL – http://localhost/phpinfo.php


phpinfo(); // show the information of php.ini



Using PHP we can make web interface which will do the entire file upload, download and execute shell commands on remote server. We can make Web FTP client using PHP FTP library.

examples –

How to upload file using PHP-FTP function –

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
echo “FTP connection has failed!”;
echo “Attempted to connect to $ftp_server for user $ftp_user_name”;
} else {
echo “Connected to $ftp_server, for user $ftp_user_name”;

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
echo “FTP upload has failed!”;
} else {
echo “Uploaded $source_file to $ftp_server as $destination_file”;

// close the FTP stream

Thank you,
Santhosh Tirunahari

ORACLE Application Express

ORACLE Application Express

ORACLE Application Express –

Application Express is the open source product by ORACLE. Every one knows HTMLDB, which is used for web representation of oracle database data. Now HTMLDB renamed as Application Express. We can use Oracle forms and reports for data representation. But application express got many good features, which makes web interface very user friendly. Now Apex 3.1 is released.

Features of Apex 3.1 –
1) Web 2.0 functionalities are used.
2) Ajax, Javascript, CSS, DOM used extensily when showing the reports in effective manner. Now the reports are user friendly.
3) Improved PDF document reports downloads and printing.
4) Mailing with Attachments features made effectivly.
5) Customization is possible in reports.

Thank you,
Santhosh Tirunahari

Working with PHP and Excel

Working with PHP and Excel

Introductions –

PHP got libraries through which we can create or access the excel data. There are two possible ways of creating or accessing the excel data in PHP

1) PHP – Excel library provided by PEAR.
2) PHP using Excel COM component functions and libraries.

** In PHP – Excel libraries, Spreadsheet_Excel_Reader is the class through which we can read the data from excel file. Online documentation is available on following url …

Spreadsheet_Excel_Writer is the class to write the data in a excel file. Online documentation is available on following url …

** Using Excel – COM components we can create, read the data from excel file easily. Here is
The small code which uses COM components to read the excel data….


$exlObj = new COM(“Excel.Application”) or Die (“Did not connect”);
$exlBook = $exlObj->ActiveWorkBook;
$exlSheets = $exlBook->Sheets;
$exlSheet = $exlBook->WorkSheets(1);
echo $exlSheets->Count;
echo $sheetName = $exlSheet->Name;
$cell = $exlSheet->Cells(1, 1);
echo $cell->Value;


Using both libraries writing excel with all formatting is available. And comparatively PHP-Excel COM components function provides a lot of functionalities to work with excel sheet on the fly.

I have tried to modify the existing excel sheet but it is not happened with both PEAR excel library and Excel COM libraries. I think it is not possible to modify the excel on the fly with out disturbing any color combinations. If any one got the solution looking for their comments….

Thank you,
Santhosh Tirunahari