Seven PHP performance rules you should be aware of
Wednesday, 21 October 2009
Here is a quick list of practices for faster PHP code.
Last Updated ( Thursday, 05 November 2009 )
Use single quotes instead of double quotes While this can be trivial, it might save some time especially if you code handles lots of string variables. Using single quotes makes PHP to treat string as they are without trying to parse them to replace variables.
Use PHP accelerator extension Saves compilation time by.. saving scripts in compiled state (memory or disk). There are several alternatives: you can use APC, eAccelerator or something more fancy. APC is going to be standard as of PHP 6 and produces great performance results. eAccelerator on the other hand, can work together with Zend Optimizer on a single PHP installation. Which APC, afaik cannot.
Optimize your code to make it error-free Make sure your code does not produce PHP notices. Always develop your code with error_reporting set to E_ALL or E_ALL & E_STRICT
Try to enable sessions only when necessary If you don't need to record user activity or data, till say, when they login to your site, there is no need to session_start () which is expensive for performance. Call it when handling posted login data in your login page.
High traffic website and "remember me" feature I've been working on a high traffic website where session files really cluttered the web server because users were able to use "remember me" feature which resulted in lots of session files in temp directory. A good approach for this case is the following scenario:
Now it's safe to clear the session files in temp dir, the auto login will still work, here is how:
- User logs in to your site with a remember me checkbox enabled
- You login the user, send the usual session cookie which expires after browser is closed, but...
- You also send special cookie with 1 month expiration time which hold md5 of user's login
- once user open browser again, the special cookie is sent
- your server code searches user table for rows with md5(user_login) = cookie value. when found it auto logins user
use realpath () for included files (include directories). PHP accelerators benefit from the absolute paths for include files. Change
<?php require_once '../some.php'; ?> to
<?php require_once(realpath('../some.php')); ?>
Note on PHP functions language constructs Optimize your code and user functions to return values only if they really need to. Use language constructs like "echo" instead of "print".