Press "Enter" to skip to content

Tag: php

e-Commerce: Changing the VAT Rate in ClickCartPro (UK Edition)

If you are using the UK edition of Kryptonic’s ClickCartPro ecommerce system (sold by Greenbarn Web) and you still haven’t updated the VAT rates in it to take into account the reduction in UK VAT on the 1st of December from 17.5% to 15%, then here’s how to do it.

To change the VAT rate in ClickCartPro from 17.5% to 15% (or vice versa), just login to the admin panel (normally via http://www.example.com/admin.php ) and select from the left hand menu “Commerce: Orders and Checkout” (it should be the third option down) and then “Manage EU Tax Rates”. You’ll probably see three rates “High Rate”, “Low Rate” and “Zero Rate”. If you select “Update” next to “High Rate”. In the “EU Tax Rate” box, you should see the current rate of VAT being shown and be able to adjust it to 15%. Click “Submit” and it should take immediate effect.

PHP: Difference in Dates Using Zend_Date

I’ve had to write some code recently that handles peoples ages based on their date of births… Something simple you expect, until you realise that PHP can’t really deal with years before 1970 (due to UNIX date time restrictions). Luckily Zend_Date (in the Zend Framework) comes to hand to help!

But how do you actually turn a date in the format YYYY-MM-DD into a difference in years? Well, here’s how! We’re relying on the date to be consistently 10 characters long in the format YYYY-MM-DD with any unused date “zerod” out (for example, if we are using OpenID which allows people to “hide” parts of their DOB):

if (preg_match('/^([1-2][0-9][0-9][0-9])\-([0-1][0-9])\-([0-3][0-9])$/',$sDob,$aMatches)) {
    $iYear=$aMatches[1];
    $iMonth=$aMatches[2];
    if ($iMonth<1 || $iMonth>12) {
        // Set a minimum/standard month for this calculation
        $iMonth=1;
    }//end if ($iMonth<1 || $iMonth>12) {
    $iDay=$aMatches[3];
    if ($iDay<1 || $iDay>31) {
        // Set a minimum/standard day of the month for this calculation
        $iDay=1;
    }//end if ($iDay<1 || $iDay>31) {
    // If anybody was born before 1850 or after 3,000 (say they have a time machine)
    // then, sorry, they'll have to check their date of birth elsewhere!
    if ($iYear>1850 && $iYear<3000) {         if (checkdate($iMonth,$iDay,$iYear)) {             $cNowDate=new Zend_Date();             $cUserDate=new Zend_Date(Array('year'=>$iYear,'month'=>$iMonth,'day'=>$iDay));
            // Sanity check that the date the user entered is actually in the past!
            // No future time travellers welcome here!
            if ($cNowDate->isLater($cUserDate)) {
                $cDifference=$cNowDate->subDate($cUserDate);
                $aDifference=$cDifference->toArray();
                print 'Year difference is:'.$aDifference['year'];
            }//end if ($cNowDate->isLater($cUserDate)) {
        }//end if (checkdate($iMonth,$iDay,$iYear)) {
    }//end if ($iYear>1850 && $iYear<3000) {  }//end if (preg_match

PHP: Zend Framework, MVC, Cookies and 4096 byte oddities

A little word of warning which has puzzled me for over 3 hours in debugging…

If you use Zend_Controller_Front::getInstance()->dispatch(); in your Zend Framework index.php file for firing off the MVC system, and the returned page is over 4096 bytes (4 kilobytes) in size you cannot set a cookie afterwards without causing the “fun” error “Cannot modify header information – headers already sent by (output started at …/library/Zend/Controller/Response/Abstract.php:546) in …”

To work around this, you’ll need to change the code from just:

Zend_Controller_Front::getInstance()->dispatch();
setcookie(. . .);

to:

$front=Zend_Controller_Front::getInstance();
$front->returnResponse(true);
$response=$front->dispatch();
#Zend_Controller_Front::getInstance()->dispatch();
setcookie(. . .);
$response->sendResponse();

I’m sure there is a slightly better way of setting Cookies in the Zend Framework, but that’s a work around for the normal way I’ve found.

If you’ve got any “better idea” suggestions, just let me know.

(I found this “buglet” because a drop down select menu I was making with Zend Form Element was causing the “Cannot modify header information – headers already sent by” error once a number of items were listed: it took 3 hours+ of detection work to narrow it down to a content size issue, then it was a process of elimination ruling out Zend_Form_Element, Zend_Form, Zend_View and Zend_View_Abstract (which helped a bit with the debugging on the issue) and then to Zend_Controller_Front to Zend_Controller_Response_Http and finally to Zend_Controller_Response_Abstract)

Work: 10 Principles of the PHP Masters

I’ve just come across 10 Principles Of The PHP Masters which has the following points (with my commentry added):

1. Use PHP Only When You Need It (Rasmus Lerdorf, creator of PHP)
PHP, like Perl, Javascript, ASP, C, Ruby, Python, C++, C# etc has it’s limitations and is more suitable for some jobs than others. Whilst it’s possibly to run PHP in the web browser, you wouldn’t really want to (as you’ll need to get your visitors to install a PHP interpreter on your machine) – likewise, you wouldn’t use PHP on embedded systems due to its size. However, if you are writing a big web application, you’ll be a masochist if you were to use Perl nowadays (back when I was a Perl web developer creating web applications in Perl – PHP was still in its very early stages) and you’ll be hitting a large performance penalty if you were to get the server to interpret Javascript for each page.
2. Use Many Tables With PHP and MYSQL for Scalability (Matt Mullenweg, creator of WordPress)
If you store a lot of data in a single MySQL (or PostgreSQL) table, then it’s going to take a long time for the server to search through the data to pull up a single row: if you have multiple tables, it’s got a smaller data set to scan
3. Never, ever trust your users (Dave Child, the brains behind Added Bytes – previously ilovejackdaniels)
This isn’t just a PHP issue – never ever trust user input more than you really really need to: otherwise, that way leads to security exploits and it’s best to write secure code. If you’re expecting digits, use preg_replace to remove anything that isn’t a digit, if you’re only expecting letters A-z, then again strip out anything that isn’t a letter. Work on the premise “what do I want to keep” and disregard the rest: I’ve seen people go down the “what do I want to get rid of” route instead and then get most upset when I say “well, what about this character?” and they have to add it to the “get rid of” list
4. Invest in PHP Caching (Ben Balbo, writer on Site Point)
Database calls are more processor/hard drive “expensive” than reading flat files off the hard drive, fetching remote pages is more processor/network intensive than reading them out of a local database (or a hard drive), counting database rows is slow: but reading a “row count” table or flat file isn’t, parsing templates (especially using regular expressions) are slow – reading prepared/precompiled files isn’t. Spot a pattern?
5. Speed up PHP Development with an IDE, Templates and Snippets (Chad Kieffer, author 2 tablespoons)
Personally, I prefer hand coding than using IDEs (Integrated Development Environments) as most of them get in my way: things like auto-closing brackets (I’ve been programming so long that I automatically close them myself – and I don’t want two sets of closing brackets) and within editor debugging usually doesn’t take into account the different environments in use (it’s often I’m developing on Windows XP/Vista, saving the file which is then picked up by a Virtual Machine for testing running Linux and all the appropriate PHP modules before been sent live to a physical Linux machine). However, I may just read his getting started with Eclipse guide.
6. Make Better Use of PHP’s Filter Functions (Joey Sochacki, author Devolio)
Filters (as detailed by Joey) are new on PHP5: so if you’re still writing for PHP4 environments or you can’t guarantee that the server administrator has installed the necessary PECL module – then you’re a bit stuck. I prefer to “roll-my-own” validation/filtering routines anyway – at least I’ll know how they work and not be shocked when bugs in the filter affect my code.
7. Use a PHP Framework (Josh Sharp)
See point 8
8. Don’t use a PHP Framework (Rasmus Lerdorf, creator of PHP)
I prefer not using a framework myself as they tend to be overkill for most tasks, don’t do exactly what’s needed: and, over the years, I’ve got a collection of routines on my hard drives (and memorised!) which do most of the common options. As Rasmus shows in an article, frameworks are also quite slow compared to “pure PHP” – because, of course, it’s a “generic tool” and isn’t optimised for “this” particular scenario.
9. Use Batch Processing (Jack D. Herrington, author of PHP Hacks book)

Why process building stats and things “on the fly” which slows down the user experience – why not run them automatically at 2am? In my previous work, I had to produce a sales commission report of 60+ sales personnel out of a months sales figures (which was several hundred thousand “items” per month) and work out which items attract what commission and what each sales person should receive. Doing that sort of processing and data extraction is slooow (even with a perfectly tuned optimised database) – however, running a batch process overnight which just extracted the sales made in the last 24 hours by each sales person (ignoring ones sold online for example) and store that information in a separate table meant sales reports could be produced within a minute or two instead of an hour or two (it still took a little time as some of the commission data was “dynamic” and had to take certain other things into account).
10. Turn on Error Reporting Immediately (David Cummings, HannonHll)
If you have PHP error reporting turned to the maximum during development (so you get the tiniest little issues highlighted immediately), it’s a lot easier and quicker to find potential issues and resolve them – before it’s deployed to a client. Turning error reporting to just “ERRORS” means you’ll miss the vital warnings which could save your code!

Freelancing/Consulting: What are the options?

Well, I did mention that I’ve become a freelance PHP consultant (although currently I’m more working in ASP/ASPscript) and that I’d write my finding/experiences up on this ‘er blog: but I’ve just been so busy recently, I haven’t even really had the time to keep up with my other projects. However, a question by an ex-colleague prompted me to write about the options there are if you are considering going freelancing/consulting. As per usual, this is not legal/accounting advice yadda yadda – if you want proper formal advise, find somebody you can pay to give you advice.

There’s three ways (as far as I’m concerned/aware of) you can go freelancing:

Work as a sole trader
Less paperwork, slightly less taxes than other methods, but some companies won’t allow you to work for them due to the fear of IR35 (where the tax man could later claim you were technically an employee for them and cause them to pay more taxes – not so much of a worry if you “work from home” though).
Work as a Limited company (this is the route I’ve taken)
Lots of paperwork (as the company and you are technically different legal entities and all monies etc need to be kept separate and accounted for), but has a higher rate of return on your money. You do need to keep an eye on the tax front (as you’ll need to file a return for yourself and your company). Also, as from April this year, you can operate a Private Limited company (Ltd) in the UK on your own: you no longer need somebody to act as a company seceteray or secondary director.
Work under an “umbrella company”
You are technically an employee of the umbrella company [so I believe] (so they sort out all the paperwork), but obviously they take their cut. I regret not considering this option a bit more (as just keeping tracking of my expenses such as mileage, food etc takes up time), but unfortunately my other business interest meant I needed to have things all under one label.

The accountancy company I use has a handy calculator on their site at http://www.sjdaccountancy.com/contractor_calculator/index.html and some other resources at http://www.sjdaccountancy.com/about/ourservices/recruiter_resources.html which may help you decide what to do (if you do decide to use them, please enter me as a referral on their site as I’ll get £50 – however, in the interests of fairness, I have to admit that whilst SJD is doing a good enough job, my partner (not business) is considering http://www.nixonwilliams.com/ for her books and they are cheaper (£75 per month compared with £95 for SJD). You don’t technically need an accountant (there’s no legal obligation), but they’ll be able to advice you on what can be counted as an expense, what can’t, what you can claim VAT back on (and advice you whether to become VAT registered, VAT flat-rate registered or not registered) and help ensure your tax forms (corporate and personal) are filed in time.

We both registered our Limited companies via http://www.uk-plc.net/companyformation/ and we both currently use Freshbooks for invoicing although I’m trying FreeAgent as it’s a lot more UK orientated and can deal a lot better with UK tax and even provides you with a profit/loss statement: it is more expensive though…

Well, that’s it for now – not a lot of information I admit, but hopefully enough for you to think about and to consider…