Pages

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, 9 December 2011

Correct Silly HTML Mistakes

For those of you that have read my blog, you will know that I'm a little OCD about website performance - and so should you be.  If your website becomes the source of frustration for an end user, more often than not you will lose your viewer and since the choice on the web is now so vast, you may not ever get them back.
For every mistake that is made in your code, your browser has to interpret what it is that it should be doing.  Not a problem you think?  Well you might be right, but squeezing every ounce of performance should be your key goal.  Just using a handful of my favourite tools will highlight any problems that you have very quickly.  These include:
  • Firefox / Chrome Plugins: Google Page Speed, HTML Validator, Firebug, Web Developer Toolbar and YSlow
  • Smush.it
  • Jcompress.com
  • W3 HTML Validator (bit of a given really!)
These tools are brilliant, but if you can avoid making some mistakes in the first place you have less work to do later on making changes and refinements to your code.  For example, say you have inserted an image into your website and it displays correctly, but is missing the alt, width and height parameters, then your browser will identify three errors with that particular image element, which you then have potentially replicated elsewhere in your page.  One solution to partially get around this is to use some form of dynamic language to call a function that will display your images for you correctly each time.  Below is a quick image function to show you what I mean.

<?php
function show_image($url, $width, $height, $alt) {
     return '<img src="'.$url.'" width="'.$width.'" height="'.$height.'" alt="'.$alt.'" />';
}
?>
You could include this in your header or whatever and then call it each time you need an image on your page.  This way, you are forced to have each parameter so that your image will be displayed properly.  The function could also be expanded to include JavaScript, Class and ID parameters etc. but for a quick and easy solution there isn't much else better.  You could then apply this theory to other elements on your page and you will quickly then get the hang of things.

Always, always run a validate check to see if your code really does validate.  If you are confident in your code being very good, you could think about making your site XHTML 1.0 strict and while this sounds easy, it sometimes isn't and could mean that you have to redesign part of your site to compensate.

Other areas that will offer performance increase are:
  • CSS sprites;
  • Too much JavaScript;
  • Images that are too large for the job, i.e a 16x16 image shouldn't be 10kb;
  • Cache as much of your code that won't be changing, i.e. JavaScript;
  • Minify your HTML, CSS and JavaScript;
  • Avoid DNS lookups;
  • Too many HTTP requests within your page;
Revisit these steps often and you will be surprised about the difference that it makes!

Monday, 5 December 2011

PHP: mysql_fetch_assoc Vs. mysql_fetch_array

Recently I've been doing a lot of work to optimise my work so that pages load more quickly and server load is reduced.  When I was looking through to my database calls, typically I've always used the mysql_fetch_assoc function because it always returned less data than the mysql_fetch array which actually returns two arrays - one which has a numeric index and the other which has an associative key index.
Having a play around and doing some benchmarking between 1,000 and 10,000 iterations of a fairly small amount of data, I found that the mysql_fetch_assoc function was between 24% and 31% faster than the mysql_fetch_array function.  Good news for me really as this is how I typically return data from my MySQL database and so I won't be doing any rewriting any time soon.  This is what I expected really as the size of the data processed and returned is half (well less than that really because it's numeric) so good news here.

Of course there are occasions when the mysql_fetch_array function is needed and I'm not questioning its existence at all, but purely as a benchmarking exercise I would pick mysql_fetch_assoc everyday.

As a side note, it's also important that I mention the mysql_fetch_object function as well which is for those of you who prefer the OO notation.  However, using the same benchmark against the mysql_fetch_assoc function, this is still on average between 8% and 14% slower.

I hope this helps anybody who is currently in the process of performance tuning.  Every little bit saved does help to improve the user experience.

Tuesday, 29 November 2011

PHP 5.4 On The Way

Earlier this month PHP 5.4 RC1 was released to the general public.  No big deal you might be thinking, but actually I noticed a small change in the latest release that could potentially be of massive help.
The note specifies 'Added class member access on instantiation (e.g. (new Foo)->bar())' which could be very handy if you only need quick access to a function from within a class.  OK, not massive I agree but sometimes for some of the smaller classes that I have this would be great.
Other improvements include the usual round of bug fixes and improvements in both the core and extensions.
Anybody considering PHP 5.3 who is on a version of 5.2 or less should hang on for a week or two until the final release.

Wednesday, 16 November 2011

Installing PEAR Packages on Windows

Ok, so now that you've read my previous post about setting PEAR up on Windows, it's time to start installing some packages that will help you on your way.

An absolute must for any sort of database connection is the DB package.  You could argue that the built in database connectivity from the PHP modules is good enough, and you would be right.  There is a certain degree of flexibility in using these packages though, as they are continuously updated throughout the year by a large community (as is PHP), but in some cases it's all about how you interact with your database connectivity as you will see, it's certainly more class driven in how it's all written.  For example, there is support for scalar parameters as shown below (taken from the PEAR documentation):

<?php 
// Create a valid DB object named $db at the beginning of your program...
require_once 'DB.php';
$db =& DB::connect('mysql://usr:pw@localhost/dbnam');
if (
PEAR::isError($db)) {
    die(
$db->getMessage());
}

// Once you have a valid DB object named $db... 
$sql  = 'select * from clients where clientid = ?'; 
$data = 53; 
$res =& $db->query($sql, $data);

// Always check that result is not an error

if (PEAR::isError($res)) {
    die(
$res->getMessage());
}
 

?>
This has certain other benefits including the potential for easy cross-platform availability (bar the changes to the SQL syntax that change between SQL servers).  One thing that PHP 5.x users will need to do is replace the '=&'s that tend to crop up as they are now depreciated because of PHP 5.x; these can just be replaced by a simple '='.  If you have errors switched on (which I would at this point during installation and testing), you will most definitely see these being pointed out as errors.
The full list of functions is available under the documentation for each of the specific packages, and so the many other functions for the DB package are listed here.
So now that you know how to use it, it's time to install it.  Launch a Command Prompt, and browse to your PHP folder.  Once there, type 'pear install DB' and press return.  Congratulations.  You've now installed the DB package, it really is that simple.  To use it, you will need to have either an include or a require (as shown in the example above) to reference the DB package (DB.php).

Other packages within PEAR tend to reference this class in some way so it's always a useful one to install.  At the time of writing, DB has been superseded by MDB2 and so that is something that is also worth a view.

Installing PEAR on Windows

This really is just a short quick guide on how to install PEAR manually on a Windows box.  There are currently multiple ways of setting PEAR up, and I'm going to show you my preferred way, only because it's easy to fault find in case anything goes wrong.

For those who don't know what PEAR is, PEAR is essentially a customisable framework of many components that you can choose to have on your system.  It really takes aim at giving access to functionality that doesn't exist with the standard PHP functions.

First thing first, you will need to have a working copy of PHP installed and working on your system (preferably the latest version), and that is really about it.  You should notice that you already have a PEAR folder in the root of your PHP folder anyway, and so this ready and waiting for you to activate the features.

To do so, open a Command Prompt (go to Start > Run > type 'cmd' and press enter) and navigate to your PHP folder.  Once you've made it there, the command prompt on the left should be showing that you are in the root of your PHP folder.  If not, you are in the wrong place.  It should look something like it does here on the left.

Next, type 'go-pear' and hit return.  You will be asked if you would like to install a system or a local copy, so you will need to type 'system' here.  Once you have done this, you will be presented with 11 options that specify locations of your files and folders.  Normally this is correct straight out of the box, but if you like many people move your PHP folders then you will need to update these locations.  When you are ready, hit enter again, and off it goes.

The next screen will show PEAR installing and when it's ready there will be a small paragraph at the bottom asking you to execute a reg file that has been placed in the root of your PHP folder called 'PEAR_ENV.reg'.  Don't worry, this is completely harmless as this just lets Windows know that PEAR is up and running on your system.

And, well, that's it really.  You've set PEAR up on your system and are nearly ready to go!  All you need now are some packages that are freely available from the PEAR website.

Monday, 22 August 2011

If PHP Were British...

I've just come across this great article from AddedBytes which is quite frankly, brilliant!

It's a bit tongue in cheek but very funny if you read through the article.

Taken from the article:
When Rasmus Lerdorf first put PHP together, he - quite sensibly, despite his heritage - chose not to write it in Greenlandic or Danish. Good job too - that would have been rather unpleasant to work with. He opted instead, being in Canada at the time, for the local tongue. No, not French - that bastard dialect of the Queen's English commonly referred to as "US English".

PHP developers in Britain have been grumpy about this ever since. What was he thinking? And more importantly, how do we undo this travesty? How do we developers ensure the traditions of the British Empire continue to be upheld, even in the digital age?
Enjoy!

Thursday, 28 July 2011

PHP 5.2 ISAPI to PHP 5.3 FastCGI

If like me it took you a little while to move from ISAPI with IIS to using FastCGI then fear not, you aren't alone.  Being honest, ISAPI with IIS went very well together as it was fast and very easy to setup.  Future versions of PHP no longer support ISAPI as of version 5.3, so you may as well make the move sooner rather than later.

So what do you need to do?  Well, firstly, download the latest build of PHP for your system (download the NTS version, which is the non-thread safe version).  Extract it somewhere on your system i.e. c:\PHP or wherever you mostly feel comfortable.  Next, assuming that you are using either Windows Server 2008 or 2008 r2, go to your Server Manager console, and then click 'Roles' on the right.  Next, click the link on the left named 'Add role services' under the Web Server (IIS) heading. This is assuming that you have IIS already setup on your server, otherwise you will need to add this as a role to your server. Drop down the 'Application Development' box and check the 'CGI' box as shown below.

As you can see, I still have my ISAPI extensions still in there but we can remove those later as we won't be needing them.  Click 'Next' and then let Windows go off and do its own thing.

Ok, your PHP config.  Do what you would normally do here.  In addition to your normal PHP config which can mostly be copied from your old PHP 5.2 config you will need to change the following:
  • cgi.fix_pathinfo=1
  • fastcgi.impersonate = 1
  • cgi.force_redirect = 0
  • extension_dir = 'c:\PHP\ext' *or where you have your PHP extension folder*
  • open_basedir = *location of your wwwroot folder typically*
Don't forget to change those asterisk comments to real values!  Ok, next back over to IIS, so open your IIS Manager.

Click on your server on the left hand side.  In the central pane will be an icon called 'Handler Mappings'.  Click on that, and then go to 'Add module mapping' in the right hand pane.  Fill in the following details and click 'OK', and then 'Yes' in the popup box when you are finished:
  • Request path: *.php
  • Module: FastCgiModule
  • Executable: *Link this to your PHP folder and then your php-cgi.exe file*
  • Name: PHP FastCGI
Next, you will need to do is go back to your server on the left hand side and then click 'FastCGI settings'.  When you get there, click the PHP entry in the middle, and then click 'Edit...' on the right.  Change the InstanceMaxRequests to 10000, and then click on the '...' button under 'EnvironmentVariables'.  Add an entry of PHP_FCGI_MAX_REQUESTS with a value of 10000, and then click 'OK'.  If you don't do these steps, IIS uses its default settings of 200 instanceMaxRequests and 500 PHP_FCGI_MAX_REQUESTS.

Nearly there now.  Make yourself that old PHP test file with the following information: <?php phpinfo(); ?> and see if it runs.  Chances are if you are on a 64 bit system this will have failed unless you tell IIS to use 32-bit applications.  To change this, go to the Application Pools, and then go to your website in the central pane.  Click 'Advanced settings' and then a popup box will appear.  Change the 'Enable 32-bit applications' entry to 'True'.

Assuming that you have set up the rest of your php.ini correctly, it's a case of job done for now!

Saturday, 5 March 2011

The return of Service Unavailable HTTP Error 503

For those of you that have read my first article in this blog, one of the reasons for the migration to a new server was because I was plagued with Service Unavailable HTTP Error 503, which would forever get under my skin and just 'error' for no real reason at all.  Nothing in the error logs, no software errors, nothing.  I was aware of the IMAP PHP module being faulty, whereby if the headers of an email were over a certain length, this would result in the 'Error 503'.  I could replicate this just fine, but the server would still fall over for no reason, even if I disabled the IMAP module.

This started on Server 2003r2 with IIS6.  Some time ago, after Googling around for a little while, I eventually found that other people experiencing the same issues with some people were saying this was down to a corrupt IIS configuration.  I had never experienced this before so it eventually started to turn into a bit of a headache trying to pin this down.  It had been on the cards for some time to move the server to a new box so for me to waste time reinstalling IIS was pointless.

Moving forward a year or so, and the problem had gradually been getting more frequent.  In the end, I just made a small VB Script as a workaround that would run every few hours to restart IIS in case this had happened which always cured the problem.  This had worked fine and my hope was that a planned server upgrade would solve this issue along with an updated version of PHP.  Wrong.  A few days into the new server being in production, what happens?  Yep, you got it.  Error 503.  Great.

Only this time there was a log entry in the Windows application log.  The shortened error looked like:
Faulting application name: w3wp.exe, Faulting module name: php_imap.dll
Google again came to the rescue, with the top result pointing at this PHP bug article about IMAP headers being too long - the same bug that was present before.  It looks as though the old problem had not been cured and it seemed that the only way to fix this would be to go up a major point release of PHP to PHP 5.3.5 (current release as of now).  ISAPI was always my favourite method for PHP use on Windows, but since this has now been retired as of the last branch of 5.2, FastCGI was now my only option.

FastCGI wasn't a problem though and it does work just as well as ISAPI although it does require a bit more of a tweak to get it set up out of the box.  So far so good though.  No more 503s.  I do think that originally the 503s were the result of the faulty IMAP module, but there still must have been a massive fault with IIS6 which is now now present in 7.5.

I would just like to say thanks to everybody who has been clicking on the sponsored adverts on this page.  It's very much appreciated.

Wednesday, 23 February 2011

Moving on, onwards and upwards!

Following on where I left off really from my last post!

I briefly mentioned in my last post that I had an upgrade path in place (after testing of course!) for 'Connect'.  The time was approaching to move on with the technology, whereby Connect had been in place for three years and in that time it had only ever had a couple of PHP / MySQL point release updates.  Not that this was a problem of course, but you can never be left standing still.

Anyway, after doing a bit of research and some testing on my machine at work I ended up drawing up a plan for the migration.  Not only would I be migrating the software from the old server to a new one, I would be taking advantage of certain in-house server developments.  Our new server cluster which runs Microsoft Hyper-V, has now been patched to SP1 by Microsoft to support dynamic memory - which means lots of nice resources for any server sitting within that cluster.  Not only this, I drew up plans to upgrade the core functionality of Moodle to version 1.9.10, as well as move to 64-bit MySQL and also move to the latest PHP 5.2.x release (I don't particularly like running Fast CGI on IIS as it has odd behaviour issues sometimes, which left me with ISAPI).

Testing of all of this was done successfully, very successfully!  With nearly everything running in native 64-bit mode on the server (except PHP), the performance boost was clear to be seen.  Pages instantly loaded quicker, reports were much faster to be dynamically generated and most of all, there would be peace of mind that it should, (famous last words!) be a lot more reliable and ready for the future.

To get started with the migration, one of our library server images of Server 2008 r2 was set up, and immediately patched with the freshly released Service Pack 1 from Microsoft.  MySQL, PHP and IIS were also set up, before copying the code across, setting security permissions and restoring the database from the old server.  The Moodle upgrade and module upgrades then took place, whilst downing the old server to ensure that there would only be one database in use.

And that was it really, how to migrate your Moodle!  Downtime was minimal, and first impressions are that everything seems very fast which I think in part is a little to do with everything.  The contributing factors in my opinion are:
  • (The obvious) Much more powerful server, with lots of resources
  • Move to 64-bit MySQL
  • New PHP release
  • Newer Moodle release
  • Move to Microsoft Server 2008 r2 SP1
I'll be adding more posts soon, so please follow this blog if it will help you in your day to day duties!

Monday, 14 February 2011

From the start...

Hi everybody, just to introduce myself and my blog firstly!

I'll start by saying that this isn't my first blog, but it is my first one for quite some time - about four years to be precise.  The reason for a re-start of my blog is to work more closely with other developers in the web development field, and hopefully to help anyone in need.

Next, I'll mention what by background is.  I've been a developer in education now for about six years now, and in that time I've worked closely on new ideas, more recently working and developing a highly customised version of Moodle, which has now been branded 'Connect'.

I've worked with various different languages on different operating systems using different databases, but most of my daily work and expertise involves Windows Server 2003r2/08r2, MySQL v5.x and PHP 5.x.  For me, I would say this is now my preferred environment after working with various different combinations of the above, and for many different reasons that I won't go into just now - but I'm sure that they will be apparent in the future as this blog develops.

The current, but soon to be retired server platform that I'm running is an old HP Proliant server, with the following specification:
  • Intel Xeon 3065 2.33Ghz processor
  • 4Gb DDR2 Memory
  • Microsoft Windows Server 2003r2
  • PHP 5.2.10 (Upgraded from 5.1.9)
  • MySQL 5.1.34 (Upgraded from 5.0.37)
  • Microsoft IIS 6
  • Moodle 1.9.0+
The server was originally bought to be a 'stop-gap' but has actually performed brilliantly during the time that it has been in service.  Personally, I believe that for 2000 users, the above specification is more than adequate.  What does let the server down especially, is IIS 6 which has increasingly become unreliable which, after doing some research, I believe is down to a corrupt IIS configuration.  Since there have been plans in the pipeline to migrate Connect to a Server 2008r2 environment for quite some time, I have left this alone for the time being.  Other than this, the server is extremely fast and has been very reliable with near enough 100% server uptime (excluding restarts for Windows updates).

Some of the posts that I will be writing shortly will be looking at:
  • Move of Connect to a new Windows Server 2008r2
  • Upgrading PHP 5.x
  • Possible up/downgrade of MySQL
  • IIS 6 deep rooted problems
  • Upgrading Moodle
  • Is Moodle 2.0 worth it?
The issues above are what I believe are current issues affecting my environment, and at some point I hope to have addressed all of the above.

Anyway - thanks for taking the time to read my blog, I hope that you have found this informative.  Please take the time to click on a sponsored link for me (even if you just open it and then close it!), and even follow this blog.