Category: PHP


How to Install MongoDB and PHP Mongo extension on Windows 7

MongoDB is one of NO SQL varian. I want to test it on my Windows 7 32 bit machine. The install process isn’t difficult but I want to share it with others that might want to do the same as I do. This post also complement for Home Server series posts :

  1. Step by Step Guide Install Apache on Windows 7
  2. Step by Step Guide Install PHP on Windows 7
  3. Step by Step Guide Install MySQL on Windows 7
  4. Step by Step Guide Install MariaDB on Windows 7
  5. WAMP (Windows 7, Apache, MariaDB or MySQL and PHPMyAdmin)

Lets get start

Install MongoDB on Windows 7

Make sure to download latest version of MongoDB

Get latest version from here

Extract the file and put all file in C:\mongodb

The content of bin folder is as seen on the picture.

Continue reading “How to Install MongoDB and PHP Mongo extension on Windows 7” »

HandlerSocket mySQL’s NoSQL, PHP and Webscale

HandlerSocket is a server plug-in that interfaces with InnoDB directly bypassing for the most part the core mySQL server all together. Using Handler socket you do not connect to the traditional port 3306 or use the mySQL protocol to communicate with the mySQL server, you use 9998 reads, 9999 writes and talks a different protocol (much smaller) to an epoll-based service. This awesome addition means that you can have many many connections with very little overhead. The core mySQL server does a good job, but can do better. I’m sure the reason why epoll is not in the core engine is probably due to licensing issues or some other reason I am not aware of, like it would be a big deal to add it. 

Why bypass the server? Really bypassing the sql parser is what was desired. The sql parser ads a significant amount of slowdown at a huge transaction rate, additionally mutex contention is involved prior to reaching the storage engine with malloc overhead (although Monty has fixed this in MariaDB). Even though you can easily get 45-70K selects a second through the mySQL SQL parser layer for InnoDB primary key lookups, this number falls short of Memcache’s 600K Gets per second or various other NoSQL solutions that keep data in memory. Continue reading “HandlerSocket mySQL’s NoSQL, PHP and Webscale” »

Most of high scale web applications use MySQL + memcached. Many of them use also NoSQL like TokyoCabinet/Tyrant. In some cases people have dropped MySQL and have shifted to NoSQL. One of the biggest reasons for such a movement is that it is said that NoSQL performs better than MySQL for simple access patterns such as primary key lookups. Most of queries from web applications are simple so this seems like a reasonable decision.
Like many other high scale web sites, we at DeNA(*) had similar issues for years. But we reached a different conclusion. We are using “only MySQL”. We still use memcached for front-end caching (i.e. preprocessed HTML, count/summary info), but we do not use memcached for caching rows. We do not use NoSQL, either. Why? Because we could get much better performance from MySQL than from other NoSQL products. In our benchmarks, we could get 750,000+ qps on a commodity MySQL/InnoDB 5.1 server from remote web clients. We also have got excellent performance on production environments.
Maybe you can’t believe the numbers, but this is a real story. In this long blog post, I’d like to share our experiences.
(*) For those who do not know.. I left Oracle in August 2010. Now I work at DeNA, one of the largest social game platform providers in Japan. Continue reading “Using MySQL as a NoSQL – A story for exceeding 750,000 qps on a commodity server” »

improving php performance on apache

Apache is available on both Unix and Windows. It is the most popular web server in the world. Apache 1.3 uses a pre-forking model for web serving. When Apache starts up, it creates multiple child processes that handle HTTP requests. The initial parent process acts like a guardian angel, making sure that all the child processes are working properly and coordinating everything. As more HTTP requests come in, more child processes are spawned to process them. As the HTTP requests slow down, the parent will kill the idle child processes, freeing up resources for other processes. The beauty of this scheme is that it makes Apache extremely robust. Even if a child process crashes, the parent and the other child processes are insulated from the crashing child.
The pre-forking model is not as fast as some other possible designs, but to me that it is “much ado about nothing” on a server serving PHP scripts because other bottlenecks will kick in long before Apache performance issues become significant. The robustness and reliability of Apache is more important.

Apache 2.0 offers operation in multi-threaded mode. My benchmarks indicate there is little performance advantage in this mode. Also be warned that many PHP extensions are not compatible (e.g. GD and IMAP). Tested with Apache 2.0.47.
Apache is configured using the httpd.conf file. The following parameters are particularly important in configuring child processes:

MaxClients : default: 256
The maximum number of child processes to create. The default means that up to 256 HTTP requests can be handled concurrently. Any further connection requests are queued.

StartServers: default: 5
The number of child processes to create on startup.

MinSpareServers: default:5
The number of idle child processes that should be created. If the number of idle child processes falls to less than this number, 1 child is created initially, then 2 after another second, then 4 after another second, and so forth till 32 children are created per second.

MaxSpareServers: default:10
If more than this number of child processes are alive, then these extra processes will be terminated.

MaxRequestsPerChild: default: 0
Sets the number of HTTP requests a child can handle before terminating. Setting to 0 means never terminate. Set this to a value to between 100 to 10000 if you suspect memory leaks are occurring, or to free under-utilized resources

For large sites, values close to the following might be better:

MinSpareServers 32
MaxSpareServers 64

Apache on Windows behaves differently. Instead of using child processes, Apache uses threads. The above parameters are not used. Instead we have one parameter: ThreadsPerChild which defaults to 50. This parameter sets the number of threads that can be spawned by Apache. As there is only one child process in the Windows version, the default setting of 50 means only 50 concurrent HTTP requests can be handled. For web servers experiencing higher traffic, increase this value to between 256 to 1024.

Other useful performance parameters you can change include:

SendBufferSize: Set to OS default
Determines the size of the output buffer (in bytes) used in TCP/IP connections. This is primarily useful for congested or slow networks when packets need to be buffered; you then set this parameter close to the size of the largest file normally downloaded. One TCP/IP buffer will be created per client connection.

KeepAlive [onoff] default:On
In the original HTTP specification, every HTTP request had to establish a separate connection to the server. To reduce the overhead of frequent connects, the keep-alive header was developed. Keep-alives tells the server to reuse the same socket connection for multiple HTTP requests.

If a separate dedicated web server serves all images, you can disable this option. This technique can substantially improve resource utilization.

KeepAliveTimeout:default:15
The number of seconds to keep the socket connection alive. This time includes the generation of content by the server and acknowledgements by the client. If the client does not respond in time, it must make a new connection.

This value should be kept low as the socket will be idle for extended periods otherwise.

MaxKeepAliveRequests: default:100
Socket connections will be terminated when the number of requests set by MaxKeepAliveRequests is reached. Keep this to a high value below MaxClients or ThreadsPerChild.

TimeOut: default:300
Disconnect when idle time exceeds this value. You can set this value lower if your clients have low latencies.

LimitRequestBody: default:0
Maximum size of a PUT or POST. O means there is no limit.

If you do not require DNS lookups and you are not using the htaccess file to configure Apache settings for individual directories you can set:

# disable DNS lookups: PHP scripts only get the IP address
HostnameLookups off

# disable htaccess checks

<Directory />

AllowOverride none

</Directory>

If you are not worried about the directory security when accessing symbolic links, turn on FollowSymLinks and turn off SymLinksIfOwnerMatch to prevent additional lstat() system calls from being made:

Options FollowSymLinks

#Options SymLinksIfOwnerMatch

php games

The following are a list of free games written in PHP

http://www.heroesmini.com/register.php – Heroes of Might and Magic
http://dragon.se7enet.com/dev.php – Dragon Knight
http://sourceforge.net/projects/blacknova – black nova Traders
http://www.0php.com/reviews/0171.php – hangman
http://www.0php.com/reviews/0172.php – anoi towers
http://www.geocities.com/markoriedelde/life/index.html – Life
http://www.geocities.com/markoriedelde/Minesweeper/index.html – minesweeper
http://www.chipmunk-scripts.com/scripts/riddles.php – chipmunk riddles
http://www.chipmunk-scripts.com/killmonster/login.php – kill monster
http://sportsphool.sourceforge.net/ – sportsPHool
http://www.fightwith.me.uk/ – fightclub

Online Role Playing Games

http://phpolrpg.sourceforge.net/ – PHP online RPG
http://dragon-soldier.net/ – dragon soldier
http://www3.kingdomofloathing.com – kingdom of loathing
http://www.lotgd.net/ – legend of the green dragon
http://www.vendetta1923.com/ – vendetta
http://www.thecrims.com/ – the crims
http://www.travian.com/ – travian

Strategy

http://www.blacknova.net – black nova
http://www.aatraders.com – aatraders
http://www.quantum-star.com – quantum-star

Other

http://deepdungeons.sourceforge.net/ – This is a desktop app written in PHP+GTK it is called Deep Dungeons.
http://www.32cards.com – 2006 world cup game based on the PECL extension winbinder.
http://www.ogame.org/ – strategic space simulation game

Optimizing PHP objects

The following tips can help in optimizing object-orientated PHP.

1. Initialise all variables before use.

2. Dereference all global/property variables that are frequently used in a method and put the values in local variables if you plan to access the value more than twice.

3. Try placing frequently used methods in the derived classes.

Warning: as PHP is going through a continuous improvement process, things might change in the future.

More Details

I have found that calling object methods (functions defined in a class) are about twice as slow as a normal function calls. To me that’s quite acceptable and comparable to other OOP languages.

Inside a method (the following ratios are approximate only):

1. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
2. Incrementing a global variable is 2 times slow than a local var.
3. Incrementing a object property (eg. $this->prop++) is 3 times slower than a local variable.
4. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
5. 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.
6. 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.
7. Methods in derived classes run faster than ones defined in the base class.
8. 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.

Debugging PHP scripts

Debugging PHP scripts can be a difficult task, so I have written this simple php debugger class.  It will display all GET and POST variables and all the properties on a currently defined object.

The code

(copy this in debug.php)

function DebugClass($class)
{
$class_vars = get_object_vars($class);
echo "<b><u>Class contents</b></u><br><br>";
foreach ($class_vars as $key => $value)
echo "<b>Property Name: </b>".$key." <b>Property Value: </b>".$value."<br>";
}
//this displays all get and post variables
function DebugIncoming()
{
echo "<b><u>GET and POST contents</b></u><br><br>";
echo "<b><font color=\"red\">GET contents</b></font><br><br>";
foreach ($_GET as $key=> $value)
echo "<b>Variable Name: </b>".$key." <b>Variable Value: </b>".$value."<br>";

echo "<br><br>";

echo "<b><font color=\"red\">POST contents</b></font><br><br>";
foreach ($_POST as $key=> $value)
echo "<b>Variable Name: </b>".$key." <b>Variable Value: </b>".$value."<br>";
echo "<br><br>";
}
//display all current POST and GET values
DebugIncoming();

Usage

Include the above file from a script you would like to debug.  Also, to print out all of the currently defined properties of a class instance, use the following function:

DebugClass($objectInstance);

5 tips for creating high performance web apps

The following are five tips that can help with peformance when writing php (some can be applied to other languages) applications.

1) use multi resultset queries to your database rather than many small ones

Look through your database code to see if you have requests that go to the database more than once. Each of these will decrease the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can not only cut the total time spent communicating with the database but also make your app more scalable by cutting down on the work the database server is doing to manage requests.

2) page/object caching

Templates caching (a previous article I wrote describes some template engineshere)

PHP Object caching

  • ion cube (commercial) – This one is unique because you don’t have to have server extensions installed.
  • Alternative PHP cache (free) – will be included with PHP 6.
  • Turck MMCache (free) – includes an encoder and loader, so you can distribute your scripts without the source

Database object caching

memcached – used by livejournal and slashdot.org.

3) gzip compression

Enabling this may increase CPU utilization (because it takes more processing power to gzip a file) but it will decrease the number bytes sent from you server, save your bandwidth, and generally make you site faster to your visitors.

to enable gzip compression, add the following to your php.ini:

zlib.output_compression = 1 (requires php 4.0.5 or above)
zlib.output_compression_level = X (X=0 through 7. The higher the number, the more the output will be compressed. Be careful when choosing higher numbers as it will take much more processing power) (requires PHP 4.3.0 or above)

4) tune your web server

A large list of apache (version 2.0) performance tips can be found here

5) Don’t save performance testing for the end of the project

If you save performance testing until the end of the project, it may already be too late and take too much time to make the necessary architectural changes. Tests can be performed on individual pieces of your application or the application as a whole.

Top 5 free content management systems

By Justin Silverton

After looking though many free content management sytems (CMS) over the past month or so, I have come up with a list of the top five.

These are also all written in PHP.

1) CMS made simple

Features

  • Easy User and group management
  • Group-based permission system
  • Admin panel with multiple language support
  • RSS module
  • Module API for easy extendability

Front-end Demo here
Admin Demo here

username: admin
password: demo

2) DragonFly CMS

Features

  • Built-in photo gallery
  • BBcode support
  • MMCache and eAccelerator support
  • Site-wide cache-based template system
  • Debugging system and page query list

Front page demo here
Admin Demo here

Username: admin
Password: Demo123 (Case Sensitive)

3) Bitweaver

Features

  • SEO friendly urls
  • Content spam protection (automatic no-follows)
  • Many formats supported (TikiWiki, HTML, BBCode, Wikipedia (aka MediaWik))
  • Hotwords – allow you to specify particular words that can be associated with a URL
  • Generate PDF documents from all Content

Front-page demo here
Admin demo here

Username: admin
Password: demo

4) Drupal

Features

  • SEO Friendly URLs
  • Many community modules
  • Role based permission system
  • External authentication source support with Jabber, Blogger, and LiveJournal
  • Blogger API support

Front-end demo here
Admin demo here

Username: admin
Password: demo

5) Joomla

This is one of the most mature, free (did I mention open source), content management systems available. Also a fork of a CMS called Mambo. How are they different?

Joomla version 1.0 is derived from Mambo 4.5.2.3 but includes many additional bug fixes and security patches. Joomla version 1.5 is an extensive refactoring of the API as is Mambo version 4.6 to its codebase. Both applications continue maintain a similar user inferface (look and feel), similar default component and module sets. Both Joomla 1.5 and Mambo 4.6 will include internationisation support. Joomla will use an easy-to-use ‘ini’ format for their translation files while Mambo uses the ‘gettext’ format. Joomla 1.5 will correctly support the UTF-8 character set. Joomla 1.5 also includes many new features such as additional authentication models (LDAP, Gmail, etc), xml-rpc client-server support. It also natively supports database drivers for MySQL 4.1+ (on PHP 5) and has improved support for MySQL 5 as well as the groundings to support other database engines.

Demo here

Is your website secure?

By Justin Silverton

March is the month of PHP bugs. The following are five of the latest bugs found within PHP.

  • PHP header() Space Trimming Buffer Underflow Vulnerability When the header() function is called with an all whitespace string a buffer underflow can be triggered that allows code execution on big endian systems (e.g. MacOS X on PPC, Solaris on SPARC) MOPB-25-2007.php
  • PHP array_user_key_compare() Double DTOR Vulnerability (U) When the userspace key comparison function returns its parameters are destructed even if there are references left. Therefore an exploitable double DTOR can be triggered. MOPB-24-2007.php
  • PHP 5 Rejected Session Identifier Double Free Vulnerability (U) When a session storage module rejects a session id the session code fails to clear an already freed pointer before calling an interruptible function. This can lead to an exploitable double free. MOPB-23-2007.php
  • PHP session_regenerate_id() Double Free Vulnerability (U) session_regenerate_id() fails to clear an already freed pointer before calling an interruptible function. This can lead to an exploitable double free. MOPB-22-2007.php
  • PHP compress.bzip2:// URL Wrapper safemode and open_basedir Bypass Vulnerability (U) The compress.bzip2:// URL Wrapper does not perform safemode or open_basedir checks and therefore allows access to archives outside the allowed area Not needed.

More security issues can be found here

It is important to update your PHP installation when new versions and bug fixes are released. There is also a project called Suhosin (which is part of hardened PHP), which can help against known and unknown security risks.

More about suhosin:

it is an advanced protection system for PHP installations. It was designed to protect servers and users from known and unknown flaws in PHP applications and the PHP core. Suhosin comes in two independent parts, that can be used separately or in combination. The first part is a small patch against the PHP core, that implements a few low-level protections against bufferoverflows or format string vulnerabilities and the second part is a powerful PHP extension that implements all the other protections.

Information and download of this can be found here

Powered by WordPress | Theme: by 85ideas. Editor by Khoanguyen