Logo Background RSS
  • 40 Tips for optimizing your php codes
    By on December 2nd, 2008 | 1 Comment1 Comment Comments
    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. Set the maxvalue for your for-loops before and not in the loop.
    4. Use echo’s multiple parameters instead of string concatenation.
    5. Avoid magic like __get, __set, __autoload
    6. Unset your variables to free memory, especially large arrays.
    7. require_once() is expensive
    8. See if you can use strncasecmp, strpbrk and stripos instead of regex.
    9. Use full paths in includes and requires, less time spent on resolving the OS paths.
    10. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
    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 switch 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. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
    18. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
    19. Error messages are expensive
    20. $row[’id’] is 7 times faster than $row[id]
    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.Ex.
      if (strlen($foo) < 5) { echo “Foo is too short”; }
      vs.
      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. 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%
    40. If you have very time consuming functions in your code, consider writing them as C extensions.
  • Install Skype API Plugin for Pidgin in Ubuntu
    By on November 1st, 2008 | No Comments Comments

    This is the Skype API Plugin for Pidgin/libpurple/Adium. If you’re already running Skype, you can have your Skype contacts displayed with your Pidgin/libpurple/Adium contacts. It is intended as a complete replacement for the Skype user interface, hopefully everything you can do in Skype you can do with this plugin.

    Install Skype API Plugin for Pidgin in Ubuntu

    First you need to download the plugin using the following command

    wget http://eion.robbmob.com/skype4pidgin.deb

    Now you should have skype4pidgin.deb package.Install this .deb package using the following command

    sudo dpkg -i skype4pidgin.deb

    or you can download the following libskype.so file to the plugins directory, normally /usr/lib/purple-2/ or ~/.purple/plugins

    For 32 bit users download this

    wget http://eion.robbmob.com/libskype.so

    For 64 bit users download this

    wget http://eion.robbmob.com/libskype64.so

    This will complete the installation.After installation you need to restart Pidgin! You will then have a skype option enabled.

  • How to use SSH Via HTTP Proxy using Corkscrew in Ubuntu
    By on October 30th, 2008 | 1 Comment1 Comment Comments

    If you want to ssh your vps server or your home computer from your work place (assuming you are using http proxy).You need to use Corkscrew.

    corkscrew is a simple tool to tunnel TCP connections through an HTTP proxy supporting the CONNECT method. It reads stdin and writes to stdout during the connection, just like netcat.

    It can be used for instance to connect to an SSH server running on a remote 443 port through a strict HTTPS proxy.

    Install corkscrew in ubuntu using the following command

    sudo aptitude install corkscrew

    This will complete the installation.

    Configue corkscrew

    If your HTTP proxy uses authentication, then you’ll need to tell it about the username and password to use This is where the concept of ‘auth-file’ comes into play. All you have to do is put your username & password, separated by a colon, into a textfile. Once you’ve done this, you just have to tell corkscrew where to find the auth-file. Create a file called .corkscrew-auth in your home directory

    $touch .corkscrew-auth

    $gedit .corkscrew-auth

    and place your username and password in the following format

    username:password

    Save and exit the file.

    Configure ssh For Tunneling

    Now we’ll tell ssh what to do when connecting to all or specific hosts. Open up ~/.ssh/config (that’s /home/yourusername/.ssh/config) in your favourite text editor (gedit,nano,vim etc)

    $gedit /home/yourusername/.ssh/config

    and add the following lines

    Host *

    ProxyCommand corkscrew proxyhostname proxyport %h %p /home/username/.corkscrew-auth

    Save and exit the file

    Note: replace proxyhostname and proxyport with the equivalents for your network.

    Note: you won’t need to add the last section, ‘/home/username/.corkscrew-auth’, if your HTTP proxy doesn’t use authentication.

    What we’ve just told ssh to do is for all hostnames (’Host *’), use the following proxy command to route the connection.If you want more secure connections you can also list of hosts.

    Corkscrew Syntax

    corkscrew proxy proxyport targethost targetport [ authfile ]

    proxy – This is the name of the host running the HTTP proxy.

    proxyport – This is the port on which to connect on the proxy.

    target – This is the host to reach through the proxy.

    targetport – This is the port to connect to on the target host.

    Test your SSH connection

    ssh serverip

  • Change MySQL data default directory
    By on October 30th, 2008 | 1 Comment1 Comment Comments

    MySQL is a widely used and fast SQL database server. It is a client/server implementation that consists of a server daemon (mysqld) and many different client programs/libraries.

    If you want to install Mysql Database Server in Ubuntu check this tutorial.

    What is Mysql Data Directory?

    Mysql data directory is important part where all the mysql Databases storage location.By default MySQL data default directory located in /var/lib/mysql.If you are running out of space in /var partition you need to move this to some other location.

    Note:- This is only for advanced users and before moving default directory make a backup of your mysal databases.

    Procedure to follow

    Open the terminal

    First you need to Stop MySql using the following command

    sudo /etc/init.d/mysql stop

    Now Copy the existing data directory (default located in /var/lib/mysql) using the following command

    sudo cp -R -p /var/lib/mysql /path/to/new/datadir

    All you need are the data files, so delete the others with the command

    sudo rm /path/to/new/datadir

    Note:- You will get a message about not being able to delete some directories, but that’s what you want.

    Now edit the MySQL configuration file with the following command

    gksu gedit /etc/mysql/my.cnf

    Look for the entry for “datadir”, and change the path (which should be “/var/lib/mysql”) to the new data directory.

    Important Note:-From Ubuntu 7.10 (Gutsy Gibbon) forward, Ubuntu uses some security software called AppArmor that specifies the areas of your filesystem applications are allowed to access. Unless you modify the AppArmor profile for MySQL, you’ll never be able to restart MySQL with the new datadir location.

    In the terminal, enter the command

    sudo gedit /etc/apparmor.d/usr.sbin.mysqld

    Copy the lines beginning with “/var/lib/mysql”, comment out the originals with hash marks (”#”), and paste the lines below the originals.

    Now change “/var/lib/mysql” in the two new lines with “/path/to/new/datadir”. Save and close the file.

    Restart the AppArmor profiles with the command

    sudo /etc/init.d/apparmor reload

    Restart MySQL with the command

    sudo /etc/init.d/mysql restart

    Now MySQL should start with no errors, and your data will be stored in the new data directory location.

  • Install Mysql Database Server with Phpmyadmin Frontend
    By on October 30th, 2008 | No Comments Comments

    MySQL is a widely used and fast SQL database server. It is a client/server implementation that consists of a server daemon (mysqld) and many different client programs/libraries.

    Installing Mysql database in Ubuntu

    sudo aptitude install mysql-server mysql-client libmysqlclient15-dev

    This will complete the installation of mysql server 5.0.45 in ubuntu gutsy.

    Configuring Mysql in ubuntu

    MySQL initially only allows connections from the localhost (127.0.0.1). We’ll need to remove that restriction if you wish to make it accessible to everyone on the internet. Open the file /etc/mysql/my.cnf

    sudo gedit /etc/mysql/my.cnf

    Find the line bind-address = 127.0.0.1 and comment it out

    #bind-address = 127.0.0.1

    You can check your configuration using the following command

    #netstat -tap

    Output Looks like below

    tcp 0 0 *:mysql *:* LISTEN 4997/mysqld

    MySQL comes with no root password as default. This is a huge security risk. You’ll need to set one. So that the local computer gets root access as well, you’ll need to set a password for that too. The local-machine-name is the name of the computer you’re working on. For more information see here

    sudo mysqladmin -u root password your-new-password

    sudo mysqladmin -h root@local-machine-name -u root -p password your-new-password

    sudo /etc/init.d/mysql restart

    Manage Mysql using Phpmyadmin

    phpMyAdmin is a tool written in PHP intended to handle the administration of MySQL over the Web. Currently it can create and drop databases, create/drop/alter tables, delete/edit/add fields, execute any SQL statement, manage keys on fields, manage privileges,export data into various formats and is available in 54 languages. GPL License information.

    Install phpmyadmin in ubuntu

    sudo aptitude install phpmyadmin

    This will complete the installation.

    Now you need to goto http://serverip/phpmyadmin/

    Login using your mysql root as username and password

  • HTTP download proxy for software packages
    By on October 30th, 2008 | 1 Comment1 Comment Comments

    Apt-Cacher-ng is a software package that keeps a cache, on the disk, of Debian/Ubuntu Packages and Release files.When an apt-get like client issues a request for a file, Apt-Cacher intercepts it and if the file is already cached it serves it to the client immediately, otherwise it fetches the file from the Internet, saves it on the cache, and then serves it to the client. This means that several Debian machines can be upgraded but each package need to be downloaded only once.

    Apt-Cacher-NG does not require neither an interpreter, nor a web server and not even a huge runtime library. It does never fork after server startup, it does not create flag files, flock() files or similar fun. Instead, it uses native system functions (mmap, sendfile) to operate with few overhead.

    Apt-cacher-ng caches the repo’s from the different versions of ubuntu quite nicely. It even nicely supports the different installs of intrepid in my home with different personal package archives (PPA, you know as in ppa.launchpad.net/*).

    Install Apt-Cacher-NG in Ubuntu Intrepid

    First you need to download the latest version of Apt-Cacher-NG from here or using the following command

    wget http://ftp.debian.org/debian/pool/main/a/apt-cacher-ng/apt-cacher-ng_0.3.3-1_i386.deb

    Install .deb package using the following command

    sudo dpkg -i apt-cacher-ng_0.3.3-1_i386.deb

    or you can use the following command to install

    sudo apt-get install apt-cacher-ng

    Now you need to Add a proxy entry to the apt system

    Configure the apt system (apt-get, aptitude, etc.) to use apt-cacher-ng

    $ echo ‘Acquire::http { Proxy “http://localhost:3142″; };’ | sudo tee /etc/apt/apt.conf.d/01proxy

    Run the following command if you need to disable it

    sudo rm /etc/apt/apt.conf.d/01proxy

    Add a proxy entry to the Synaptic system for this go to: Settings->Preferences->Network->Manual Proxy Configuration and enter

    HTTP Proxy: localhost 3142

    FTP Proxy: localhost 3142

    Click OK

    Click Reload

    Dashboard & manual

    For apt-cacher-ng dashboard use the following URL

    http://localhost:3142/acng-report.html

    For apt-cacher-ng manual: (right click &) open with your browser

    file:///usr/share/doc/apt-cacher-ng/html/index.html

    Import .deb files from the local apt cache

    apt-cacher-ng use the .deb files that are already in /var/cache/apt/archives/

    sudo mkdir -p /var/cache/apt-cacher-ng/_import

    sudo chown apt-cacher-ng /var/cache/apt-cacher-ng/_import

    Now open browser using the following URL

    http://localhost:3142/acng-report.html

    and click “Start Import”

    Configure Client Machines

    If you want to use apt-cache-ng in ubuntu or debian clients use the following command to use this proxy

    $ echo ‘Acquire::http { Proxy “http://serverip:3142″; };’ | sudo tee /etc/apt/apt.conf.d/01proxy