Tag Archives: php

Fix PHP timezone warnings in OS X Snow Leopard

The standard Mac install of PHP has always been somewhat quirky, and 10.6 is no exception. One of the most obvious issues occurs when attempting to use date/time functions. PHP 5.3 requires that the date.timezone setting is available. Without this, you will receive a warning similar to the following:

Warning: getdate() [function.getdate]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/London' for 'BST/1.0/DST' instead in /Users/gscott/Sites/hello-world.php on line 9

The solution is to edit (or create, if it doesn’t exist) /private/etc/php.ini and make sure a setting exists for date.timezone. For example:

date.timezone = Europe/London

After making the change, restart Apache

sudo apachectl restart

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

PHP 5.3: The Good, the Bad and the Ugly

PHP 5.3 was released today; here are my positive and negatives:

The Good: Closures

Anonymous functions created with create_function have always been a bit messy. With 5.3 comes support for closures with a much cleaner syntax:

    $greet = function($name)
    {
        printf("Hello %s\r\n", $name);
    };

    $greet('World');
    $greet('PHP');

The Bad: Backwards incompatible changes

Although not a massive change from 5.2, there are enough differences to break existing code.

The Ugly: Namespaces

There has been quite a discussion about PHP’s new namespace syntax.

$c = new \my\name\MyClass;

It’s just damn ugly. The more sensible choice, :: is already used as the scope resolution operator and was therefore dismissed.

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

mcrypt support for PHP on 64 bit Mac OS X 10.5

Please note: The article below refers to installing mcrypt on Mac OS X 10.5. If you have 10.6 Snow Leopard, please see my updated guide: Install mcrypt PHP extension on OS X Snow Leopard

Adding additional functionality to the standard Apple-supplied PHP on Mac OS X 10.5 is a little tricky if you are running a 64 bit processor such as the Intel Core 2 Duo. The reason is that any dynamic extensions that you add will need to be 64 bit, and many shared libraries by default will compile as 32 bit binaries. Trying to use a 32 bit extension with a 64 bit PHP results in the following unfriendly error message:

PHP Warning: PHP Startup: Unable to load dynamic library './mcrypt.so' - (null) in Unknown on line 0

mcrypt is a good example of a useful extension that can be added to PHP with a little bit of effort:

  • Open up your Terminal.app
  • To explicitly build for 64 bit architecture export CFLAGS="-arch x86_64"
  • Download libmcrypt from sourceforge http://sourceforge.net/projects/mcrypt
  • Unpack the archive
  • cd libmcrypt
  • ./configure --disable-shared
  • make
  • sudo make install
  • download PHP 5.2.6 source from http://www.php.net/get/php-5.2.6.tar.bz2/from/a/mirror
  • unpack the archive and go into the php-5.2.6/ext/mcrypt/ dir
  • phpize
  • ./configure
  • make
  • sudo make install
  • verify the extension is 64 bit: file /usr/lib/php/extensions/no-debug-non-zts-20060613/mcrypt.so

/usr/lib/php/extensions/no-debug-non-zts-20060613/mcrypt.so: Mach-O 64-bit bundle x86_64

To actually use the extension, you can simply create a symbolic link to it. For example:

  • cd ~/Sites
  • ln -s /usr/lib/php/extensions/no-debug-non-zts-20060613/mcrypt.so

Example code: mcrypt.php

Drop the following code into your ~/Sites directory to verify everything is working:

    <?php
    
    if ( ! extension_loaded('mcrypt') ) {
        dl('mcrypt.so');
    }
    
    $key   = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";
    
    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    
    print_r($encrypted_data);
    
    ?>

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

PHP Best Practices #2: Strictures

Make sure PHP is reporting all errors and warnings.

Warnings and notices are PHP’s way of letting you know that you are utilising features in a non-standard way. If your code is omitting errors, then it should be fixed as soon as possible. Strict warnings are a class of errors that are turned off by default in most PHP installations. Turning on strict warnings gives you another level of error reporting, which is helpful to prevent you from using misusing functions, making sure your code is compatible with future PHP versions.

In the example here, using date() without explicitly setting a timezone will result in an E_STRICT warning. In this case, we are using a function called strictErrors to tell PHP to report all error types.

Example

    <?php
    
    function strictErrors() {
        $reporting_level = E_ALL;
        
        // if version of PHP < 6, explicity report E_STRICT
        if ( version_compare( PHP_VERSION, '6.0.0', '<' ) ) {
            $reporting_level = E_ALL | E_STRICT;
        }
        
        return error_reporting( $reporting_level );
    }
    

    // turn on strict error and warnings
    strictErrors();
    
    // produces strict warning
    echo date( "d-M-Y" );
    
    // no warning
    date_default_timezone_set( 'Europe/London' );
    echo date( "d-M-Y" );
    
    ?>

Further information

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

PHP Best Practices #1: Regular expressions

preg not ereg

This is the first in what I hope will be a regular series of posts on PHP best practices, inspired in part by Damian Conway’s Perl Best Practices book.

Historically, PHP has had two incompatible regular expression engines available, POSIX Extended and PCRE (Perl Compatible Regular Expressions). Arguably, Perl-compatible regular expressions are more powerful since they support non-greedy matching, assertions, conditional subpatterns and a number of other features not supported by POSIX Extended. More importantly, the POSIX Extended extension is deprecated as of PHP 5.3, meaning that a call to any of its functions, such as `ereg`, will emit a `E_DEPRECATED` notice. Therefore, for any regular expression functionality in your scripts, use the PCRE set of functions which are prefixed with `preg_`.

Example

    $pattern = '/Hello/x';
    $subject = 'Wake up and say Hello.';
    $matches = array();
    
    if ( preg_match( $pattern, $subject, $matches ) ) {
        print_r( $matches );
    }

Output:

    Array ( [0] => Hello )

Further information

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

PhpDocumentor in 5 minutes

Help Point

Introduction

This is a quick and dirty guide to the absolute minimum you need to get up and running with PhpDocumentor.

One of the slightly off-putting aspects of PhpDocumentor is the amount of tags (`@`) that are available, which can initially be overwhelming. e.g. see PEAR example:

PEAR sample file

This guide shows you the most important tags that you need to have in your documentation by means of an actual example: `Accumulator.php`.

Assumptions

  • You are on a UNIX based machine, which includes Linux and Mac OS X.
  • You are documenting object oriented rather than procedural code

Install

PhpDocumentor is part of PEAR. Install is easy:

sudo pear install phpdocumentor

Documenting your source code

The rules:

  • One class per file
  • One docbook block for the class, not for the file
  • Filename is `.php`

For the class:

  • short description
  • code example
  • @author

For each attribute:

  • short description
  • @var

For each method:

  • short description
  • @param
  • @return
  • @see

Example class with documentation

Accumulator.php

    <?php
    
    /**
     * An instance of this class represents a counting machine
     *
     * <code>
     * require_once 'Accumulator.php';
     * 
     * $acc = new Accumulator( 10 );
     * 
     * $acc->addNum( 20 );
     * 
     * echo $acc->getTotal();
     * </code>
     *
     * @author Glen Scott <glen @ glenscott.co.uk>
     */
    class Accumulator {
        /**
         * The running total
         *
         * @var int
         */
        private $_number;
        
        /**
         * Create an instance, optionally setting a starting point
         *
         * @param int $initial an integer that represents the number 
         *                     to start counting from
         * @access public
         */
        public function __construct( $initial = 0 ) {
            $this->_number = $initial;
        }
        
        /**
         * Adds a number to the running total
         *
         * @param int an integer to add to the running total
         */
        public function addNum( $num ) {
            $this->_number += $num;
        }
        
        /**
         * Returns the current total
         *
         * @return int returns the current running total
         * @see Accumulator::$number
         */
        public function getTotal() {
            return $this->_number;
        }
    }

Creating your documentation

phpdoc --filename Accumulator.php --target docs

The docs directory is created and some HTML files are generated. Load docs/index.html into your browser to read your documentation.

PhpDoc sample page

Possible issues

phpdoc: command not found. This means that the documentation generator script is not in your path. Run pear config-get bin_dir and add this directory to your shell’s $PATH environment variable.

Links


Want advice on building better software? Join my mailing list…


Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Closures in PHP 5.3

A good article from IBM’s developerWorks on the new functional programming features in the upcoming release of PHP 5.3:

What’s new in PHP V5.3, Part 2: Closures and lambda functions

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Closing PHP tag considered harmful

A good tip from Zend, who recommend omitting the closing PHP tag (?>) when your files contain pure PHP code. This can prevent additional whitespace being inserted into the script output. Extra whitespace can cause problems, for example, if you are trying to set your own custom HTTP headers: nothing should be output before the call to the header function. Otherwise, this classic error will occur:


Cannot modify header information - headers already sent by (output started at myinclude.php:16) in myscript.php on line 15

Zend Framework: Documentation

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Cal Henderson on Django

Very entertaining talk from Flickr’s Cal Henderson on Django’s shortcomings.

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Installing PEAR on Mac OS X 10.5 Leopard

PEAR was removed by Apple from 10.5 for one reason or another. Here’s how to get it back:

Pre-requisties

Make sure you have a php.ini file in /etc/. This isn’t available by default. To create one enter the following:

sudo cp /etc/php.ini.default /etc/php.ini

PEAR Install

  • cd
  • curl -O http://pear.php.net/go-pear
  • sudo php go-pear

This starts the interactive install script.

  • Press Enter to start install
  • Press Enter to use no HTTP proxy
  • Type 1 and press Enter
  • Enter /usr/local/pear as the path and press Enter
  • Press Enter to confirm the install directories
  • Press Enter to install PEAR_Frontend_Web-beta,
    PEAR_Frontend_Gtk2, MDB2 by default

The installer will also alter the include_path in your php.ini file to include the new installation directory, so just press Enter when prompted

The PEAR Package Manager

To make using the command line tool easier, we are going to modify our shell path. Add the following line to the end of your ~/.profile file:

export PATH="$PATH:/usr/local/pear/bin"

After saving your .profile file, log into a new terminal and type the following to confirm that everything is working

pear version

If all is well, you should see the following output (or similar):

PEAR Version: 1.7.2
PHP Version: 5.2.5
Zend Engine Version: 2.2.0
Running on: Darwin glen-scotts-macbook.local 9.3.0 Darwin Kernel Version 9.3.0: Fri May 23 00:49:16 PDT 2008; root:xnu-1228.5.18~1/RELEASE_I386 i386

For more information on using the manager to install and maintain packages, see the PEAR manual for the command line installer.

Clean up

rm go-pear

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn