Learn More About PHP And The Web Platform!

Struggling with your web server, or to scale your PHP application to meet growing demand?

Whether you're running one server or a whole server farm; whether you're hosting on Windows Server or on Linux.

Learn from Stuart's experience with system design, delivery, support and management to help you do a better job and have an easier time.

Beneath Whitby breakwater

I’ve been working my way through the different solutions available for securing a shared hosting server. So far, I’ve looked at:

The solutions that are left on my todo list are:

Are there any other solutions for securing shared hosting that you know about, and would like me to include? If there are, let me know by leaving a comment below.
Be the first to leave a comment »

The challenge with securing a shared hosting server is how to secure the website from attack both from the outside and from the inside. PHP has built-in features to help, but ultimately it s the wrong place to address the problem. Apache has built-in features too, but the performance cost of these features is prohibitive.

This has created a gap that a number of third-party solutions have attempted to fill. One of the oldest of these is suphp, created by Sebastian Marsching. How well does it work, and how well does it perform?

  • suphp: Running PHP As A Specified User
  • Installing suphp
  • Configuring Apache
  • Some Benchmarks
  • Other Considerations
  • Conclusions

suphp: Running PHP As A Specified User

Like Apache’s own suexec, suphp is a solution that allows PHP to run as the user and group that owns any particular website on a shared hosting server.

suphp consists of two components:

  • mod_suphp, an Apache module that replaces mod_php
  • suphp, a setuid binary that replaces Apache’s suexec

It relies on PHP/CGI having been installed onto the server first.

Installing suphp

suphp is compiled and installed in the same way as any other Apache module. These instructions are for Apache 2.2, but they will work fine for Apache 2.0 as well. (You can run suphp on Apache 1.3 too). (Gentoo Linux and Seed Linux users can skip these instructions; you can install suphp using ‘emerge mod_suphp‘).

Download the suphp source code from the website. Unpack the tarball somewhere, like this:

tar -zxf suphp-0.6.2.tar.gz
cd suphp-0.6.2

Next, run the configure script:

./configure --with-setid-mode=paranoid 

You’ll need to adjust some of these settings to suit your local operating system:

  • –with-min-uid sets the lowest user id that PHP is allowed to run as. Check your /etc/passwd file to see just how low this needs to be set.
  • –with-min-gid sets the lowest group id that PHP is allowed to run as. Check your /etc/group file to see just how low this needs to be set.
  • –with-apache-user tells suphp which user Apache will be running as.
  • –with-logfile tells suphp where to write log messages to. I recommend that you configure suphp to write its logfile in the same directory that Apache would normally write its log files.
  • –with-apxs tells suphp where to find the Apache util that’s used to help build Apache modules.
  • –with-apr tells suphp where to find the Apache Portable Runtime (apr) config util.

It’s worth pointing out that there are several different options to choose from for the –with-setid-mode config. Check out the suphp documentation (included in the source tarball) for the details on what each mode does.

Next, run make to compile the software.

Assuming everything compiles just fine, the next step is to install mod_suphp by copying it to your Apache modules directory:

cp  src/apache2/.libs/mod_suphp.so /usr/lib/apache2/modules/

After that, you need to install the suphp binary:

cp src/suphp /usr/sbin/suphp
chmod 4755 /usr/sbin/suphp

mod_suphp is hard-coded to expect the suphp binary to be installed into /usr/sbin. If you put it anywhere else, mod_suphp won’t be able to run PHP for you!

To finish, download the suphp configuration file from Gentoo’s CVS, and install it as /etc/suphp.conf. Then, edit the file, updating all the settings to match the values you passed to the configure script.

Configuring Apache

The first thing you need to do to your Apache config files is to comment out mod_php. mod_suphp is a replacement for mod_php; you cannot run both at the same time.

Then, in your main httpd.conf file, add the following:

LoadModule suphp_module modules/mod_suphp.so
AddType application/x-httpd-php   .php
AddHandler application/x-httpd-php .php

suPHP_Engine On

<Location />
SuPHP_AddHandler x-httpd-php

DirectoryIndex index.php index.htm index.html default.htm default.html

This tells Apache to load mod_suphp, to associate it with PHP scripts, and to look for index.php et al when a URL only specifies a folder name instead of a file.

The final step is to go into each of your virtual hosts, and tell mod_suphp which user owns the virtual host. This will the user and group that PHP will run as.

<VirtualHost www.example.com>
SuPHP_UserGroup stuart mybusiness

Now you’re ready to restart Apache and to run some tests to make sure that suphp is up and running.

Some Benchmarks

suphp works the same way as Apache’s suexec. Every time a PHP script is run, suphp has to fork Apache and then execute another copy of the PHP/CGI binary. This approach provides the absolute security benefits that we seek, but is much slower than using mod_php.

To benchmark suphp, I used Apache’s ab benchmark to load a simple phpinfo() page 1,000 times. I ran the benchmark five times, and averaged the results.

  • suphp: average of 164.677 seconds
  • mod_php: average of 6.422 seconds

suphp is some 25 times slower than mod_php. This is a substantial performance hit, but it’s better than suexec, which benchmarked at 36 times slower than mod_php. I admit to being surprised that suphp performs better than suexec; I plan to put all of the alternatives covered here in a “head to head” article soon!

Other Considerations

One neat feature of suphp is that it can support both PHP 4 and PHP 5 running on the same box at the same time. Hopefully, you’ve already made the move to PHP 5 and you don’t need this feature – but it’s there if you do.

The same feature can be used to support both PHP 5 and PHP 6 (when it’s released) at the same time.

Be aware that the last release of suphp was in 2006. There is an active mailing list you can join for community help and support.


suphp is an easy-to-install, easy-to-configure and easy-to-maintain alternative to Apache’s own suexec. If you are running a shared server and the horrific performance penalty doesn’t put you off, then suphp is well worth looking at instead of using suexec.

But the question is – is there anything better out there, something that provides both security and performance? In the next article, I’ll take a look at a third-party Apache mod that attempts to answer that.

This article is part of The Web Platform, an on-going series of blog posts about the environment that you need to create and nurture to run your web-based application in. If you have any topics that you d like to see covered in future articles, please leave them in the comments on this page.


The challenge with securing a shared hosting server is how to secure the website from attack both from the outside and from the inside. PHP has built-in features to help, but ultimately it’s the wrong place to address the problem.

So what can Apache do to help?

It turns out that there are quite a few alternative ways that Apache can help. This article will look at what we can do with stock Apache, and the next few articles will look at what we can do with some interesting third-party Apache modules.

  • suexec: Running CGI Programs As A Specified User
  • Configuring Apache With PHP/CGI
  • Configuring suexec With PHP/CGI
  • Configuring suexec For Shared Servers
  • Some Benchmarks
  • Other Considerations
  • Conclusions

suexec: Running CGI Programs As A Specified User

To secure a shared hosting server, we want to be able to run PHP as the user who owns that particular website. One way to do this with stock Apache is with suexec.

suexec is a standard Apache module which allows you to run a CGI executable as a specified user and group. CGI executables date back to the very early days of the web, back when we all had to use Perl to create dynamic websites. Although PHP is commonly run as an Apache module, it still provides support for CGI.

Check with your Linux vendor to make sure that you have PHP/CGI installed on your box.

Configuring Apache With PHP/CGI

The first step for getting suexec working is to configure Apache to run PHP as a CGI executable, instead of using mod_php. Add the following configuration to your httpd.conf file:

ScriptAlias /php5-cgi /usr/bin/php-cgi
Action php5-cgi /php5-cgi
AddHandler php5-cgi .php
AddDirectoryIndex index.php

… and add the following line to your virtual host:

AddHandler php5-cgi .php

In your httpd.conf file (or in one of the files that httpd.conf includes), there will be a <Directory> entry for the directory on disk where your virtual host is stored. Inside that <Directory> entry, there should be an “Options” line, which might look like this:

Options Indexes FollowSymLinks

Add “ExecCGI” to the end of your Options line.

Make sure to comment out mod_php from Apache. Then, restart Apache, and do some testing to make sure that PHP 5 is working.

For reference, here is the Apache config from my test system:

ScriptAlias /php5-cgi /usr/bin/php-cgi
Action php5-cgi /php5-cgi
AddHandler php5-cgi .php
AddDirectoryIndex index.php index.phtml

<VirtualHost *:80>
        DocumentRoot /var/www/localhost/htdocs
        <Directory /var/www/localhost/htdocs>
                Options Indexes FollowSymLinks ExecCGI
                AllowOverride All
                Order allow,deny
                Allow from all
        AddHandler php5-cgi .php

Configuring suexec For PHP/CGI

With Apache now running PHP as a CGI executable, we’re ready to get Apache running PHP as the owner of each website.

In your test virtual host, add the following:

SuexecUserGroup stuart users

Replace “stuart” with the user who owns the website, and replace “users” with the group that the user belongs to. This sets the privileges that PHP will run as.

To ensure the security of your server, suexec is very particular about what conditions must be met before it will execute your PHP scripting engine. A full list of conditions can be found in the Apache docs. To make sense of the conditions, you’ll need to know what settings your copy of suexec has been compiled with. Run the command suexec -V to find out your system’s settings. This is the output from my Seed Linux LAMP Server system:

belal vhosts.d # suexec -V
 -D AP_DOC_ROOT="/var/www"
 -D AP_GID_MIN=100
 -D AP_HTTPD_USER="apache"
 -D AP_LOG_EXEC="/var/log/apache2/suexec_log"
 -D AP_SAFE_PATH="/usr/local/bin:/usr/bin:/bin"
 -D AP_UID_MIN=1000
 -D AP_USERDIR_SUFFIX="public_html"

The first condition (and one that isn’t obvious from the Apache manual!) is that the PHP CGI executable must be installed under AP_DOC_ROOT. Chances are that it isn’t installed there at the moment, so go ahead and copy it there.

mkdir /var/www/localhost/cgi-bin
cp /usr/bin/php-cgi /var/www/localhost/cgi-bin

The second condition is that the PHP CGI executable must be owned by the same user and group you listed in the SuexecUserGroup statement earlier. This causes problems for shared hosting; I’ll show you how to fix that later in this article.

chown stuart users /var/www/localhost/cgi-bin/php-cgi

Update your Apache httpd.conf file to use this copy of PHP:

ScriptAlias /php5-cgi /var/www/localhost/cgi-bin/php-cgi

Restart Apache, and test to make sure that PHP 5 is still working. You should also start to see log messages appearing in AP_LOG_EXEC. This is the first place to look if PHP isn’t working (although the log messages can be a little terse and cryptic).

For reference, here is the Apache config from my test system:

ScriptAlias /php5-cgi /var/www/localhost/cgi-bin/php-cgi
Action php5-cgi /php5-cgi
AddHandler php5-cgi .php
AddDirectoryIndex index.php index.phtml

<VirtualHost *:80>
        DocumentRoot /var/www/localhost/htdocs
        <Directory /var/www/localhost/htdocs>
                Options Indexes FollowSymLinks ExecCGI
                AllowOverride All
                Order allow,deny
                Allow from all
        SuexecUserGroup stuart users
        AddHandler php5-cgi .ph

Configuring suexec For Shared Servers

I mentioned earlier that there was a problem with using suexec + PHP/CGI on shared servers – the very environment where suexec is needed the most 🙁 In one of the steps above, we created a copy of the PHP CGI executable, and changed its ownership on disk to match the ownership of the website.

chown stuart users /var/www/localhost/cgi-bin/php-cgi

What happens when we have two websites, each owned by a different user? Or five, or ten, or hundreds? Apache’s suexec will refuse to re-use this copy of the PHP CGI executable for each of the websites, because it isn’t owned by the right user and group.

Each website needs its own copy of the PHP CGI executable, owned by the user and group that owns the website itself. We don’t want to create hundreds of copies of the actual PHP CGI executable (it’s a large waste of space, and a pain for managing PHP upgrades), so instead we can point each website at its own copy of a simple bash script:


/usr/bin/php-cgi "$@"

This script simply executes our central copy of the PHP CGI executable, passing through whatever parameters Apache has called the bash script with.

To configure Apache to use this script, simply move the ScriptAlias statement from outside the VirtualHost config to inside.

Some Benchmarks

Because Apache is having to execute a new suexec process every page hit (and suexec executes a new PHP CGI process every page hit), it’s going to be slower than running mod_php. But how much slower? To find out, I used Apache’s ab benchmarking program to load a phpinfo() page 1000 times. I ran the benchmark five times and averaged out the results.

  • suexec: average of 127.219 seconds
  • suexec + bash script: average of 134.836 seconds
  • mod_php: average of 3.753 seconds

suexec on its own is some 34 times slower than using mod_php; suexec + the bash script needed for shared hosting environments is even worse, at 36 times slower than using mod_php.

This benchmark doesn’t provide the full picture. Once you take into account the extra memory used by the suexec method, and the extra memory and CPU (and process context switches!) required to transfer output from PHP/CGI to Apache to send back to the website’s user, the final cost of using suexec + PHP/CGI will be substantially higher.

Other Considerations

Performance isn’t the only thing to think about when evaluating suexec + PHP/CGI.

  • suexec + PHP/CGI does solve the security challenge, without requiring your application to support safe_mode.
  • HTTP authentication is only supported by mod_php, not PHP/CGI. If your application relies on this, then suexec + PHP/CGI is not for you.


Apache’s suexec mechanism does secure a shared hosting server from attack from within. However, this is achieved at a heavy performance cost, which inevitably will translate into needing lots of extra servers – which is expensive.

So, if Apache itself doesn’t come with a solution that’s worth a damn, maybe there are third-party solutions out there that can do a better job? The next article in the series will take a look at what others have done to try and plug this gap.

This article is part of The Web Platform, an on-going series of blog posts about the environment that you need to create and nurture to run your web-based application in. If you have any topics that you d like to see covered in future articles, please leave them in the comments on this page.


I’m still working on the next article in my series looking at PHP on servers, so in the mean time, check out this simple way to emulate Ruby’s nice way of handling separate getter, setter and state query methods in PHP:

[code lang="php"]
class Example
	private $canCache = false;
	private $cacheXml = null;

	function canCache($newState = null)
		// check if we are querying or changing state
                if ($newState === null)
 			// we are querying
 			return $this->canCache;

  	 	// if we get here, we are a traditional getter/setter method
 		if ($newState)
 			$this->canCache = true;
 			$this->cacheXml = $this->_toXml();
 			return true;
 			$this->canCache = false;
 			return false;

$exObj = new Example();
if ($exObj->canCache())
 	// ... do something here

It isn’t as elegant as Ruby, but it does the job, and it means that your classes don’t have to be full of seperate canDoSomething() and isSomethingAllowed() type methods. I think it makes the code that uses the object a little easier to read, and a little more intuitive. YMMV.


Anyone Using Textmate To Work With PHP?

Posted by Stuart Herbert on November 30th, 2007 in Toolbox.

My editor of choice for PHP for the last year or two has been phpEclipse. It’s the best compromise so far between IDE-like features (especially being able to search the entire code base, being able to have multiple projects open at once, and the absolute best class/function inspector in any PHP editor I’ve used so far – I can’t live without these features) and a text editor with acceptable performance (which is where Zend Studio has always lost out; can’t abide an editor that can’t keep up with my typing), syntax highlighting and code layout.

Unfortunately, phpEclipse doesn’t get released all that often (the last official release was 18 months ago now, although there are nightly CVS builds for folks who can afford to risk a broken PHP dev environment, and unfortunately I can’t afford that in my day job). That’s a long time to go without bug fixes and useful new features! It also suffers from that annoying Eclipse-ism of being unable to do anything for 10 minutes or so when you first open a project, whilst the workspace is rebuilt.

So I’m currently auditioning Textmate to see whether it can replace phpEclipse as my environment of choice. First impressions are pretty favourable (it supports projects, its fast, and the syntax highlighting is close enough) but it seems to lack a few useful features that phpEclipse has (like a class inspector – grrr, and being able to use phpdoc to provide context-sensitive help) and the performance seems to suck something awful when working on remote filesystems over 100mbit ethernet.

I was wondering if anyone else who reads Planet PHP has switched to Textmate, and if you’ve got any tips you can share on how to make Textmate a great PHP editing environment. If you do, please leave a comment below.


In my last article, I covered the fundamental security problem that exists when you have multiple websites owned by different people on the same box. The challenge is to secure the box not just from outside attack (something you have to do anyway, and which I’ll cover later in this series), but also to make sure that code running on one website can’t steal confidential data like MySQL passwords from any of the other websites.

This isn’t a problem caused by, or unique to, PHP. It has been a problem with websites ever since the original NCSA httpd was released back in the early nineties with the ability to run Perl scripts via the CGI interface. Over fifteen years later, NCSA httpd has given way to Apache and Perl has given way to mod_php, but the problem is still the same.

(On Windows, the problem is a little different, because Windows handles process permissions differently. I’ll look at that in a later article).

PHP 4 & 5 ship with two features which were designed to tackle this issue – safe_mode, and open_basedir.

Introducing safe_mode

Safe mode is an optional PHP feature aimed at restricting which files any PHP script can access. It works like this:

  • When your PHP script is executed, PHP makes a note of which user owns your PHP script. On a shared hosting server, this will be your user account – the account you log into to FTP files up to the server.
  • Whilst your PHP script is running, if your script wants to access any other files, PHP checks to see who owns those files first. If the file isn’t owned by the same user who owns the running script, PHP refuses to open the file.

Sounds like a great solution to the problem. Your PHP script can open your files – which is what you want – but it cannot open the files of any of the other customers on the box. So how do we switch it on?

Configuring safe_mode

To switch on safe_mode, set “safe_mode=1” in your php.ini file, and restart Apache. Then test your website, and make sure it still works.

If you have PEAR (or a.n.other PHP libraries) installed in a central location on your server and listed in the include_dir setting, you should also add this location to safe_mode_include_dir as well. This tells PHP to skip the owning user test when accessing the PEAR libraries.

There are also other things you can configure, right down to enabling / disabling specific PHP functions and classes. Full details, as always, are in the excellent PHP Manual. I won’t be going into them in any detail in this article.

The Problems With safe_mode

Alas, if it sounds too good to be true, then all too often it is 🙁

Any moderately-complicated PHP application will create files on the server. The obvious example is uploaded images to a blog, but it’s just as likely to be cache files for RSS feeds or to reduce database overhead, or a friendly web-based installer like the one that comes with WordPress. When your script creates these files, the files on disk will be owned by Apache, not by your user account. Remember, Apache doesn’t run with your user account’s privileges; it runs as its own user!

With safe_mode enabled, PHP can’t read any of the files created by Apache. To use safe_mode, your PHP script can never ever write brand new files to disk. (It can write out existing files that you own). You’ll have to store all of your data in the database, which isn’t always convenient or the fastest solution.

It’s also (theoretically) possible to get around safe_mode. safe_mode is a PHP feature, not a security policy enforced by the underlying operating system. A PHP extension (one written in C, not in PHP) could ignore safe_mode and just open any files that it chooses (and that Apache can see). The PHP developers audit the official PHP extensions, to make sure none of them can be abused like this, but when it comes to third-party extensions, you’re on your own.

Sadly, PHP is just the wrong place architecturally to solve this security problem, and as a result safe_mode will not be part of PHP 6. If you currently rely on safe_mode to secure your servers, it’s time to start looking at other ways to secure your shared hosts. I hope you’ll find my next article or two about alternatives both useful and timely 🙂

Restricting Access With open_basedir

The second PHP feature that helps is open_basedir. Although it’s documented as part of the safe_mode section of the PHP Manual, to all intents and purposes it is a separate feature that can be switched on and off without requiring safe_mode.

safe_mode doesn’t care where a file on disk is; all it cares about is who owns the file. open_basedir is the orthogonal feature. It doesn’t care who owns a file, only where the file exists on disk. You tell PHP which directory it is allowed to open files from, and PHP makes sure that all attempts to access files outside that directory will fail.

The idea is to setup each website so that PHP is only allowed to open PHP files installed for that website.

Switching On open_basedir

The open_basedir setting can be edited in php.ini, but to be honest that makes little sense on a shared hosting server. You’re much better off putting this configuration into the httpd.conf entry for each individual website:

	ServerName www.example.com
	DocumentRoot /home/customer1/public_html/www.example.com/

	php_admin_flag open_basedir /home/customer1/public_html/www.example.com/


There’s one gotcha with open_basedir that you need to pay close attention to. Despite the name, PHP doesn’t expect open_basedir to be the name of a directory; it treats it as a prefix. The check PHP uses is something like this:

[code lang="php"]
 function check_open_basedir($file)
    // resolve any symlink
    $file = realpath($file);
    $open_basedir = ini_get("open_basedir");

    // check to ensure file is inside open_basedir
    if (substr($file, 0, strlen($open_basedir)) === $open_basedir)
        return false;
    return true;

To make sure that PHP treats open_basedir as a real directory, always put a slash at the end of the value for open_basedir.

open_basedir and PHP 6

For the moment at least, open_basedir will continue to be supported in PHP 6. There’s a slight change to how it is configured (with PHP 5, you can set open_basedir in .htaccess files; with PHP 6 you have to put it in httpd.conf or php.ini) but the actual functionality stays the same.

open_basedir is vulnerable to the same theoretical circumvention as safe_mode, so be careful when installing third party PHP extensions onto a shared server.

Where Do We Go From Here?

I’ve looked at two solutions implemented by PHP 4 & 5 to help make a shared hosting server more secure.

  • safe_mode stops you opening up files owned by other customers, but it has the side effect that your web application cannot create files of its own. This feature has been removed from PHP 6.
  • open_basedir stops you opening up files outside the specified directory on disk. This feature is still in PHP 6, but can now only be configured from phi.ini and Apache’s httpd.conf.
  • Both features rely on third party extensions supporting them. It’s perfectly possible for a third party extension to choose to bypass both features, thus re-creating the security hole we’re trying to close.

In terms of our challenge, both features come close to solving it, but neither is 100% guaranteed to do so. Data security isn’t just a legal obligation, it’s also a moral one, and you can’t meet your moral obligation using these features alone.

Fundamentally, PHP is the wrong place to solve this problem. PHP is trying to overcome a security weakness that it has inherited from Apache (and all other web servers; this isn’t a problem specific to Apache), and in turn they are constrained by the security model implemented by UNIX systems themselves.

Moving up the stack, if the problem can’t be fixed in PHP, maybe Apache can offer some help? I’ll take a look at that in the next article.

This article is part of The Web Platform, an on-going series of blog posts about the environment that you need to create and nurture to run your web-based application in. If you have any topics that you d like to see covered in future articles, please leave them in the comments on this page.


(Many thanks to everyone for their feedback on my first post in this series.)

Most of us started out hosting our code on shared hosting, whether it was on a box provided by an ISP, something we rented ourselves, or something we built so that we had somewhere to host the websites we built for our customers. Love it or loathe it, shared hosting has some unique security challenges, and understanding those challenges is a good way to learn the fundamentals of how your web server actually works.

This article is looking squarely at Linux systems running Apache, which is by far the most common shared hosting platform, but the principles involved apply to Lighttpd or any other Apache alternative running on Linux.

What Is A Shared Server?

For many web developers, their first experience of hosting code on the Internet comes on a shared server. Shared servers offer cheap hosting, but that’s because there are many different people sharing the same server and therefore sharing the costs.

A shared server is a single server that hosts more than one website. Each website may be owned by a different company, group, or person. Typically, each customer on the box has a user account which they log into to upload new files for the website. Each file that the customer uploads is owned by the customer’s user account:

ls -lh ~thecube/public_html
drw-r--r--  thecube  public   4K     images
-rw-r--r--  thecube  public   1.2K   index.php

Apache Needs Access To Your Files

On your classic shared hosting server, there’s one copy of the Apache web server running, and PHP is installed either as mod_php, or as a CGI executable. That one copy of Apache handles all the incoming HTTP requests for all the websites that are sharing the server. When Apache is running in this way, it runs as a specific user – normally www, or apache (or nobody on badly-configured systems).

In order to serve up your website, Apache needs to be able to read your HTML files, CSS files, images, PHP scripts and so on. Some web applications (blogs, content management systems and so on) also need write access to your website’s directories.

Read and write access is normally granted by setting the group permissions on a file or directory. Each customer’s user account, and Apache, are members of the same group. By default, the FTP daemon will be set up to ensure that the group has read access to all of the files that are uploaded, so that Apache can serve the website.

Apache Has Access To Everyone’s Files

There is one copy of Apache, and it runs as a single user – no matter which website is being served. This single user has read access to every single website on the shared hosting server, and it probably has write access to most (if not all) of the websites too.

An attacker from the outside only needs to break into one website on the server, and that will give him access to every other website hosted on the same box!

But here is the rub. The attacker doesn’t need to break into the box. He can just as easily become a customer, get a legitimate account on the box, and then just upload PHP scripts to access the other websites hosted on the box. Provided he’s careful and doesn’t change anything, he can steal whatever data he wants, and no-one will even notice.

Why does that work? It’s possible because the PHP code is executed by Apache – and Apache has access to all of the files from all the websites on the box. That includes all the PHP scripts that contain the usernames and passwords for all the MySQL databases.

This is the worse-case scenario – but it’s also the default scenario. Slap Apache + mod_php on a box, start putting websites on it, and these security problems will exist, unless you (as the server administrator) take additional steps to prevent them.

The Challenge

The challenge with securing a shared hosting server is this: how do we put as many websites as possible onto the one machine without each customer being able to steal sensitive information, or interfere with, any of the other customers that they are sharing with?

There are a few ways to tackle this, which I’ll cover in the next article or two.

This article is part of The Web Platform, an on-going series of blog posts about the environment that you need to create and nurture to run your web-based application in. If you have any topics that you d like to see covered in future articles, please leave them in the comments on this page.


The folks at Packt Publishing sent me a copy of Dennis Popel’sLearning PHP Data Objects” to review. I’d never heard of Packt before, and was intrigued. They’re a relatively new publisher, with a growing range of books on PHP-related topics, and they remind me of what O’Reilly was like when they first started out. According to their About Us page, they also pay a royalty direct to open source projects – so sales from Dennis’ book should result in money coming the PHP Group’s way.

What Does The Book Claim To Do?

The jacket of the book says that, by reading the book, you’ll learn:

  • An overview of the technology
  • Getting started with PDO
  • Creating sample databases
  • Different methods of creating connection strings
  • Error handling, prepared statements, and handling rowsets
  • Getting column metadata
  • Setting connection parameters with examples
  • Handling rowsets and different ways to retrieve multiple rows

The book also includes a helpful appendix on PHP object-oriented programming for readers who aren’t familiar with using PHP this way.

My copy of the book doesn’t include a CD with the code listings on, and I wasn’t able to find the code listings online to download. That’s something I’d like to see Packt change in the next edition; I thought we’d stopped having to type in code examples with the demise of the good ol’ ZX Spectrum 🙂 I haven’t tested the example code in the books as a result, and given Lukas’s concerns about errors in the code found in another of Packt’s books, don’t be surprised if there are issues here. But don’t be put off by it either.

Does It Do What It Says On The Tin?


If you’ve never used PHP’s PDO before, and you’re looking for a book to get you up and running, then you should take a look at Learning PHP Data Objects. The book covers all the basics, plus error handling (something I personally heartily approve of 🙂 ), and also topics like streaming BLOB objects from the database out to the browser.

This isn’t a book that aims to teach you SQL, nor the differences between the different SQL dialects supported by your favourite database platforms; it’s totally focused on the PDO side of things. This is a good thing; it ensures that the examples and text aren’t constantly full of tony tangents distracting you from the main reason for buying this book: to learn PDO.

Is This A Book You Will Go Back To In The Future?

I’m not sure. From start to finish, the book is written as a tutorial rather than a reference, staying true to the book’s title and mission. I feel that the book’s index is incredibly weak, which is a shame, but not unexpected in a tutorial book. It’s the sort of book that you’d like to have on the company’s bookshelf to help new starters get up to speed with PDO, but it’s likely to stay on the shelf afterwards.


If you’re new to PHP, or haven’t yet made the move from PHP 4 to PHP 5, then this book can help you get started with one of the important new features of PHP 5. It’s a book that does exactly what it says on the tin, which is a refreshing change 🙂

Whilst there’s plenty of online tutorials about PDO out there, for the folks who prefer to read a real book, as far as I can tell after a quick bit of Googling this is the only book out there to date that’s dedicated solely to covering PDO (if you know of any such books, please leave a link to them in the comments below).

If you’ve bought this book and have an opinion on it, please leave a comment.

Be the first to leave a comment »

I’ve just seen Wez’s post about Microsoft’s new Community Technology Preview for their SQL Server 2005 extension for PHP.

Why Is It Important For Microsoft To Support PHP On Windows?

I can’t speak for the rest of the world, but Windows is an important platform here in the UK. About half the customers I work with run their websites on Windows Server. Every customer who prefers Windows Server over Linux automatically wants to use the full Microsoft stack, and that means IIS and Microsoft SQL Server.

Starting with Windows Server 2003 Service Pack 1, IIS became a viable platform for running production PHP sites on. SP1 has a fix for a nasty problem in the Windows kernel which stopped PHP working well as a CGI program under IIS. It’s true, IIS has serious limitations compared to Apache which cost time and money to overcome – chiefly no out-the-box equivalent to mod_rewrite – but it performs well and is simple enough for many folks to admin more easily than Apache (although the new IIS7 admin interface might be a step backwards there). With the new FastCGI support recently released, it’s now possible to further optimise an IIS setup too.

SQL Server is a true heavyweight database server. The most commonly deployed version that I come across is SQL Server 2000, although SQL Server 2005 is starting to appear in various enterprises. It is fast, scalable (in the old-fashioned way unfortunately, which is expensive), and when it comes to old-fashioned replication (as opposed to scale-out) I think that it leaves MySQL for dead. Although expensive to buy outright, if you buy your hosting boxes from places like Rackspace, the cost tends to be much more reasonable.

PHP comes with an MSSQL extension that’s based on the old TDS data protocol, which I believe is a legacy protocol from the old Sybase days (SQL Server is based on Sybase). TDS is also supported on Linux through the FreeTDS project, which allows PHP running on Linux boxes to connect to Microsoft SQL Server running on Windows.

What’s Wrong With The Existing MSSQL Extension For PHP?

… or, why do we need an improved SQL Server extension for PHP? 🙂

The existing MSSQL extension works well, but has a few practical limitations that have to be worked around.

  • Limited to varchar(255) support. SQL Server 2000 and later support varchar columns longer than 255 bytes in size, but unfortunately the old TDS-based MSSQL extension can only support up to varchar(255).
  • No support for unicode columns like nvarchar. The size of a varchar column is specified in bytes, not characters. If you’re working with UTF8 or UTF16 encoded data, one non-ASCII character takes up multiple bytes of space. This cuts down on the amount of characters you can store in a varchar field, and it makes things like HTML form validation – er – interesting. nvarchar, by contrast, is advertised as a variable-size datatype for storing multi-byte characters. nvarchar(255) holds 255 characters, not 255 bytes.
  • No PDO drivers. Although there’s some debate about the performance merits of PDO, PDO’s prepared statement support is a real boon when it comes to preventing SQL injection attacks.
  • Poor error reporting. The MSSQL extension doesn’t provide an equivalent to mysql_error() et al, which is a bit of a pain.

At the moment, I’ve no idea whether Microsoft’s extension addresses any of these issues. There’s no documentation online, just a .exe file that isn’t going to run under OS X 🙂 I’ll have a look at it when I get to my Windows PC at work, and see what it can – and can’t – do.


Many thanks to everyone who commented on my recent article and said they’d be interested in a series of posts about more server-oriented PHP topics. There were quite a few requests for a “ten point”-type article introducing the subject, so that seems to be a good place to kick things off.

Building Blocks

There are six classic ways to group and organise the servers that your web-based application runs on.

Shared Hosting

Shared hosting, like the name implies, is where you cram many different websites (normally owned by many different people) onto the same physical box. The upside is that they’re very cheap (because you’re not paying for an entire server, only a slice of one), but the downsides are that you can quickly outgrow a shared hosting server, and shared hosting servers are difficult to make really secure. Use them when you have to, but do your best to trade up to something that you can have all to yourself whenever you can.

Dedicated Server

A dedicated server is a box all to yourself. So long as you can keep the bad guys outside, you have more peace of mind when it comes to security. They cost a bit more than shared hosting, but there are many affordable solutions both in Europe and the US.

A PHP application normally needs no changes at all to move from shared hosting to a dedicated server.

What might need to change is the way you look after the installed application. Unless you go for a managed server, or you are using a server looked after by your customer, it will become your responsibility to look after the operating system installed on the server. You will be responsible for ensuring the server is patched with the latest security fixes. This can eat up quite a bit of time every week, so make sure your customer is paying for this time one way or another!

Two-Tier Architecture

When you outgrow a single server, the next step is to consider moving to a separate database server and web server, also known as a two-tier architecture. This is a popular choice because it’s quick and very painless (just order an additional box, and then move your database onto it), and it buys you the time you need to prepare for scaling up to the next architecture. Even on commodity Intel/AMD servers (I’m talking Xeons and Opterons here, not desktop CPUs!), a two-tier architecture is often enough to handle a public website for a medium-to-large organisation.

The only change a PHP application should need is to update the hostname passed to mysql_connect() et al. Consider moving any background batch jobs you have onto the database server, to further reduce the load on the web server.

It’s a good idea at this point to split your PHP application into separate publishing and admin components, so that you can move the admin website onto the database server. Splitting these up allows the admin site to function well when the main website is being hit hard, but to make it work you’ve got to start thinking about how to share data between the publisher and admin components – the data that your website publishes, and your sessions too.

Once you’ve outgrown the two tier architecture, you can add more capacity on the publishing side by moving to a web farm, and you can make your database server more resilient by upgrading to a cluster. If you don’t mind the extra complexity and the reworking involved, you can also scale further by moving to an n-tier architecture.


Be the first to leave a comment »
Page 17 of 18« First...10...1415161718

This Month

January 2018
« Jul