Category Archives: php

Coming soon: A handy new application for freelancers, contractors and small businesses

Technical Services 7

Over the last few months, I’ve been working with Webwings to develop a new web application which we hope will save freelancers, contractors and small businesses a lot of time.

Development has been swift and pain-free thus far, due in part to the choice of CodeIgniter as the framework. It’s proven to be an excellent base on which to iterate and incrementally build our product.

We have been alpha testing with a select group of users, and have received very positive feedback. We are aiming to get a beta release out within the next couple of months. If you are interested in participating in this, please leave a comment at the bottom of this page, and I will be in touch.

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

Securing your CodeIgniter passwords with bcrypt

Safe

I’ve applied a small modification to the Portable PHP password hashing framework, so it can be easily used in CodeIgniter projects. An example of using it to authenticate users:

$this->load->library( 'PasswordHash' );

    $query = $this->db->query("
        SELECT
            `user_id`,`password` AS `hash`
        FROM
            `user`
        WHERE   
            `username` = ". $this->db->escape($username) ."
        LIMIT
            1
    ");

    // check to see whether username exists
    if ( $query->num_rows() == 1 ) {
        $row = $query->row();

        if ( $this->passwordhash->CheckPassword( $password, $row->hash ) ) {
            return $row->user_id;
        }
    }

To generate a hashed password:

    $this->load->library( 'PasswordHash' );

    $password = ( isset( $_POST['password'] ) ? $_POST['password'] : '' );

    if ( $password ) {
        $hash = $this->passwordhash->HashPassword( $password );

        if ( strlen( $hash ) < 20 ) {
            exit( "Failed to hash new password" );
        }
    }

For more details, please check out the repository on GitHub: github.com/glenscott/passwordhash-ci

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

Compiling PHP extensions using Xcode 4.3 and above

Prior to version 4.3 of Xcode, Apple bundled a load of command line tools with it that are used to compile native binaries, including PHP extensions. However, as of version 4.3, these tools are not bundled by default. Therefore, if you require these tools you need to take one of two actions:

1. If you already have Xcode 4.3 installed, go into the Components tab of the Download preferences panel and make sure Command Line Tools are selected

Xcode CLI tools installation

OR

2. Download and install the command line tools as an independent package from either;

a. Apple (requires Apple ID)
b. GitHub

Once you have the command line tools installed, you are able to compile native binaries.

If you found this post useful, it would be great if you could Like my Facebook page using the button in the sidebar. Thanks!

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

Refactoring a large PHP codebase – where do you start?

If you are finding a codebase less manageable than it should be, chances are that refactoring could help. But where can you start? I’ve found the following tools are good for focussing on the areas of code that require attention:

PHPMD – http://phpmd.org/

PHPMD (Mess Detector) scans your source code and computes various quality metrics such as cyclomatic and NPath complexity. These metrics can be used to assess which classes in your codebase need refactoring.

phpcpd – https://github.com/sebastianbergmann/phpcpd

phpcd (Copy Paste Detector) scans your source for code clones — identical fragments of code that are usually created by copying and pasting. Source code with high levels of clones may benefit from refactoring.

What are your favourite tools to help in your refactoring efforts?

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

Finding function dependencies in your PHP applications

wide web

A recent post on reddit/PHP asked an interesting question: how can you determine the extension requirements of your PHP application in a programmatic way? And could you add such a check to a continuous integration environment to validate dependencies?

I’ve come up with a relative simple solution, albeit with some caveats (see below). The process requires two distinct stages:

  1. Gather a list of extensions and functions from a PHP environment
  2. Scan PHP source code for function calls and flag up any that are not either a) available in the PHP environment or b) user defined.

I’ve posted some code to Github that demonstrates how this can be done. You can find the source code here: https://github.com/glenscott/php-dependencies.

For stage 1, you must determine the functions that are defined in your PHP environment. This is done by running get-env-functions.php either on the command line, or from within your document root. This will create a config file in the directory defined by CONFIG_PATH. This config file will be used by the second script, scan-dependencies.php.

scan-dependencies.php will scan through PHP source code defined by SOURCE_PATH and use the configuration file generated previously. After it finishes scanning, it will list all function calls made that are not defined in either PHP itself, or within the source directory.

Example Run

Getting details of your PHP environment

$ php get-env-functions.php 
Found 1743 total functions in 61 extensions available in PHP.

Scanning source code for dependencies

$ php scan-dependencies.php 
Found 3 function calls and 1 object instantiations in your script.
Function ps_setgray not defined.

In this example, the function ps_setgray was called in a script but not defined anywhere.

Caveats

  • Your source code and its dependencies must lie under one directory — included/required files outside this directory are not scanned
  • As it stands, only _function_ dependencies are found. This means that class dependencies are not checked.

Final thoughts

This is by no means a complete solution, but I hope it is of some use. Please feel free to comment, or suggest improvements.

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 Alternative PHP Cache (APC) on Mac OS X Lion

The APC extension should be a straightforward PECL install, but sadly it does not work on Mac OS X Lion. Attempting to install will result in make errors similar to the following:

In file included from /private/tmp/APC/apc.c:44:
/usr/include/php/ext/pcre/php_pcre.h:29:18: error: pcre.h: No such file or directory
In file included from /private/tmp/APC/apc.c:44:
/usr/include/php/ext/pcre/php_pcre.h:37: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/include/php/ext/pcre/php_pcre.h:38: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/include/php/ext/pcre/php_pcre.h:44: error: expected specifier-qualifier-list before ‘pcre’
/private/tmp/APC/apc.c:393: error: expected specifier-qualifier-list before ‘pcre’
/private/tmp/APC/apc.c: In function ‘apc_regex_compile_array’:
/private/tmp/APC/apc.c:454: error: ‘apc_regex’ has no member named ‘preg’
/private/tmp/APC/apc.c:454: error: ‘apc_regex’ has no member named ‘preg’
/private/tmp/APC/apc.c:455: error: ‘apc_regex’ has no member named ‘nreg’
/private/tmp/APC/apc.c:455: error: ‘apc_regex’ has no member named ‘nreg’
/private/tmp/APC/apc.c: In function ‘apc_regex_match_array’:
/private/tmp/APC/apc.c:487: error: ‘apc_regex’ has no member named ‘preg’
/private/tmp/APC/apc.c:487: error: ‘apc_regex’ has no member named ‘preg’
/private/tmp/APC/apc.c:488: error: ‘apc_regex’ has no member named ‘nreg’
/private/tmp/APC/apc.c:488: error: ‘apc_regex’ has no member named ‘nreg’
make: *** [apc.lo] Error 1
ERROR: `make' failed

Thankfully, the solution is simple. To being with, make sure you have Xcode installed. If you have xCode 4.3 or above, make sure you have the command line tools installed.

APC requires PCRE libraries and header files to be available, so we can download and install these from source:

./configure
make
sudo make install

Next, we can install the APC extension using the normal PECL route:

sudo pecl install apc

Confirm that you have the following line in your php.ini file:

extension=apc.so

Restart Apache, if required:

sudo apachectl graceful

You should now have APC available, and you can confirm this by looking at your phpinfo output:

APC PHP info


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

SimpleCrypt PHP class for simple cryptography

I have just pushed a simple class called SimpleCrypt to GitHub:

https://github.com/glenscott/simple-crypt

This is an OO wrapper around the most common mcrypt functions. An example of use:

require_once 'SimpleCrypt.php';

// show the algorithms available for use
print_r( SimpleCrypt::get_available_algorithms() );

// encrypt a string using Triple DES (CBC mode)
$crypt = new SimpleCrypt( 'tripledes', 'mysecretkey' );
$encrypted_data = $crypt->encrypt_data( 'stringtoencrypt' );
echo "Encrypted data: " . bin2hex( $encrypted_data ) . "\n";
echo "Decrypted data: " . $crypt->decrypt_data( $encrypted_data ) . "\n";

If you find it useful, please let me know!

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

Mac OS X 10.7.3 upgrades PHP from 5.3.6 to 5.3.8

As described in Apple’s security notes for Mac OS X 10.7.3, PHP is upgraded from 5.3.6 to version 5.3.8 as part of the update.

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

Map invoke errors when using MongoDB MapReduce

When running MapReduce operations on your data, you must make sure that any fields you refer to within your map operation are available for every document in your collection. If you try a map operation and some documents do not have the required field, you will get the following assertion error when running the command:

map invoke failed: JS Error: TypeError: this.fieldname has no properties

fieldname in this case is a field that does not exist in all of the documents.

To prevent this error, you can pass the optional query parameter to the command to make sure that only documents with this field are queried. For example, in PHP, add the following to the command operation:


$db->command(
    'mapreduce' => 'collection',
    'map'       => $map,
    'reduce'    => $reduce,
    'out'       => array( 'inline' => 1 ),
    'query'     => array( "fieldname" => array( '$exists' => true, ) )
);

This makes sure that MapReduce operations are only run on a subset of the collection.

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

Getting started with MongoDB and PHP on Mac OS X

NYみやげのMongo goods貰った!

Introduction

MongoDB is a document-orientated database written with scalability and high-performance in mind. It is one of a growing number of NoSQL systems – a database that does not rely on SQL or relational theory at all.

Getting a MongoDB server working with PHP on Mac OS X is relatively straightforward, and this tutorial shows you how.

Installing the MongoDB Server

The first step requires you to download and install the actual MongoDB system. The example shown below downloads v2.0.0 64 bit binaries for OS X. For other binaries, please check out the MongoDB Downloads page.

cd /tmp
curl -O http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-2.0.0.tgz
tar zxvf mongodb-osx-x86_64-2.0.0.tgz 
sudo mv mongodb-osx-x86_64-2.0.0 /usr/local/mongodb
mkdir /usr/local/mongodb/data

Configuring the MongoDB server

We need to create a small configuration file so that MongoDB knows where its data files reside. Create the file /usr/local/mongodb/mongod.conf and add the following line:

dbpath = /usr/local/mongodb/data

Starting MongoDB

To manually start the MongoDB server, use the following command:

/usr/local/mongodb/bin/mongod --config /usr/local/mongodb/mongod.conf

This will start the server and will by default log all output to STDOUT.

Installing the MongoDB PHP Extension

Installing the PHP extension is simple:

sudo pecl install mongo

Once this has completed, add the following line to your /etc/php.ini file:

extension=mongo.so

Restart apache using sudo apachectl restart, and the extension should be available. This can be verified with the phpinfo call:

MongoDB extension for PHP

Example PHP script

To test your setup, the following simple script can be used to create a new collection and add two new records:

    <?php
    
    // connect
    $m = new Mongo();
    
    // select a database
    $db = $m->comedy;
    
    // select a collection (analogous to a relational database's table)
    $collection = $db->cartoons;
    
    // add a record
    $obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
    $collection->insert($obj);
    
    // add another record, with a different "shape"
    $obj = array( "title" => "XKCD", "online" => true );
    $collection->insert($obj);
    
    // find everything in the collection
    $cursor = $collection->find();
    
    // iterate through the results
    foreach ($cursor as $obj) {
        echo $obj["title"] . "\n";
    }
    
    ?>

The script should output the following:

Calvin and Hobbes
XKCD

And that’s it! You now have a working MongoDB setup on Mac OS X.

For more information on the PHP extension for MongoDB, please see the following pages in the PHP Manual:

PHP: Mongo – Manual

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