Category Archives: php

Simple development hosts on Mac

This tutorial will show you how you can easily set up new virtual hosts on the stock Mac Apache install, perfect for testing and developing small PHP projects. Once you have done this, new projects can be set up by just creating new directories -- no adding hosts to /etc/hosts or adding new Apache configuration will be required.

We are going to use ~/Sites/ as the base directory, and we'll be able to dynamically serve from any directories under this. The name of the directory that you use will form part of the URL that you will use.

So, for example, if you created the following under ~/Sites/

mkdir -p ~/Sites/siteone/htdocs
mkdir -p ~/Sites/sitetwo/htdocs
mkdir -p ~/Sites/anothersite/htdocs

Then you will be able to access content from htdocs under the following URL's

Notice how we are using the .localhost TLD for this. RFC 2606 specifies that .localhost is reserved for local testing purposes.

So, how do we get to this setup? There are two parts:

1. Set up .localhost proxying

First of all, we need to make sure that any requests to a .localhost domain are routed to the local loopback device. For this, we will use the Automatic Proxy Configuration facilities of OS X.

We need to create the following Proxy Configuration File:

function FindProxyForURL(url, host)
{
	if (dnsDomainIs(host, ".localhost")) {
		return "PROXY localhost";
	}
 
	return "DIRECT";
}

Save the file as localhost.pac and place it in your ~/Sites/ directory.

Now, open up your System Preferences and go into Network. Select your network in the left hand pane, and click the 'Advanced...' button on right. Click the 'Proxies' tab and check 'Automatic Proxy Configuration'. In the 'Proxy Configuration File', enter the URL to your file, for example http://localhost/~username/localhost.pac.

Click on 'OK' and then 'Apply'.

2. Set up Apache VirtualHost

Edit the Apache configuration file for your user which is stored under /etc/apache2/users/.conf, and add the following:

<VirtualHost *:80>
    VirtualDocumentRoot "/Users/<username>/Sites/%1/htdocs"
    ServerName subdomains.localhost
    ServerAlias *.localhost
</VirtualHost>

Restart Apache with sudo apachectl restart

3. Test!

mkdir -p ~/Sites/mysite/htdocs
echo 'Hello World!' > ~/Sites/mysite/htdocs/index.html

Visit http://mysite.localhost/ in your browser, and you should see "Hello World!"

Find this useful? You may be interested in my e-book, which is about creating the perfect PHP development environment on your Mac. Sign up to my mailing list to get more information:


References

Glen Scott

I’m a freelance software developer with more than 10 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

Setting up a perfect PHP development environment on your Mac

generations

One of my most popular blog posts has been the instructions on installing the PHP mcrypt extension on Mac OS X. I recall needing mcrypt for a phpMyAdmin installation, and thought the install instructions would be useful for others. It was: to date, the page has had 19,174 views!

The popularity of this post got me thinking -- how exactly are people using Mac OS X for PHP development?

I've been using OS X for development for many years now, and I've built up a lot of knowledge about how to create an environment that's a pleasure, rather than a chore, to use. A lot of this knowledge I am taking for granted, but I am sure it will be of use to others.

I'm putting this knowledge into my first e-book.

Here's an example of what topics I'll be covering:

Part I - Native

Where I look at options for working on smaller projects, or projects where your deployment environment is unknown.

  1. Configuring Apache
  2. Adding PHP modules
  3. Adding PECL modules
  4. Installing and running MySQL, PostGreSQL and MongoDB
  5. Installing and configuring phpMyAdmin
  6. Installing and configuring MAMP

Part II - Virtualization

For working with medium - large projects where your deployment environment is known.

  1. Installing Vagrant
  2. Setting up your first virtualized PHP environment
  3. Puppet provisioning
  4. Vital development tools
  5. Part III - Specific environments

    If you are developing for a specific framework or tool, this chapter will help.

    1. Installing a test instance of Magento
    2. Create a WordPress plugin and theme development environment
    3. Create an environment for Zend Framework or CodeIgniter applications

    Are you interested in finding out more? If so, please add your e-mail address to the list and I'll keep you updated on the progress of the e-book.

    Also, if you have any subjects that you would covered, please add a comment to the page.


    Glen Scott

    I’m a freelance software developer with more than 10 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

HTML5, character encodings and DOMDocument loadHTML and loadHTMLFile

Extreme HTML Verschachteling

Whilst working on a script for my GetProThemes app recently, I came across a problem with PHP's loadHTML and loadHTMLFile methods.

The problem

I noticed that when using loadHTMLFile to parse an HTML document, the character encoding -- UTF-8 in this case -- was not being taken into consideration. Because of this, there was some mojibake after I extracted some content from the document. Here is an example of the problem:

$i18n_str = 'Iñtërnâtiônàlizætiøn';

$html = <<<EOS
<!doctype html>
<head>
  <meta charset="UTF-8">
  <title>html 5 document</title>
 </head>
 <body>
<h1 id="title">$i18n_str</h1>
</body>
</html>
EOS;

$dom = new DOMDocument();
$dom->loadHTML( $html );
echo $dom->getElementById( 'title' )->textContent;

// output: Iñtërnâtiônà lizætiøn

After some digging into the PHP source code, I discovered this function, along with loadHTML, uses Libxml for determining the character set of the HTML document automatically. It uses a function named htmlCheckEncoding for this purpose. What this function does is to look for a meta tag declaring the character set. Unfortunately, it only looks for the HTML4 style declaration:


<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

This means that if your source document is HTML5, it will not pick up the newer meta tag declaration which has this form:


<meta charset="utf-8">

It seems that this glitch has been fixed in version 2.8.0 of Libxml, but if you are stuck with an older version then I have created a workaround.

The solution

I have created a drop-in replacements for the loadHTML/loadHTMLFile methods which will automatically convert an HTML5 character set declaration, if it exists, into an HTML4 character set declaration and thus allowing Libxml to parse the document correctly.

Fixing the above example is trivial:

require_once 'DOMDocumentCharset.php';

$i18n_str = 'Iñtërnâtiônàlizætiøn';

$html = <<<EOS
<!doctype html>
<head>
  <meta charset="UTF-8">
  <title>html 5 test</title>
 </head>
 <body>
<h1 id="title">$i18n_str</h1>
</body>
</html>
EOS;
		
$dom = new DOMDocumentCharset();
$dom->loadHTMLCharset( $html );
echo $dom->getElementById( 'title' )->textContent;

// output: Iñtërnâtiônàlizætiøn

So, the fix involves:

1. Including the DOMDocumentCharset class
2. Instantiating DOMDocumentCharset rather than DOMDocument
3. Calling the new loadHTMLCharset method

The class will only activate the workaround if the installed Libxml version is less than 2.8.0, so upgrading Libxml will not break this code.

The source code can be found on GitHub: dom-document-charset

Glen Scott

I’m a freelance software developer with more than 10 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

An App in a Day

One thing I've really enjoyed about freelancing is the freedom to work on pet projects. When I have not been working with my paying clients, these projects have kept me busy. The trouble is, I seem to have many -- twenty at the last count -- in a perpetual state of "in progress".

So, today I had some free time and set myself a challenge -- develop and launch a useful web app in 24 hours. I decided to develop a browser for professionally-designed WordPress themes.

This challenge also allowed me to play around with some new technologies. In this case, I chose to use jQuery Masonry for the front-end Pinterest-like display.

GetProThemes screenshot

The app consists of two main parts:

1. A feed processing script that pulls in popular theme information from Mojo Themes and ThemeForest and saves them into a DB. This script is run via cron to update the themes on a weekly basis.

2. Some frontend logic that pulls out these themes and displays a preview graphic for users to click on.

In the end, I spent around eight hours on the development.

I registered a domain name, set up the hosting, added Google Analytics and affiliate referral codes and uploaded the files. The site can be found here:

GetProThemes.com

It's been a fun day, and I'll be very interested to hear if the site is useful to anyone!

Glen Scott

I’m a freelance software developer with more than 10 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

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 more than 10 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 more than 10 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 more than 10 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 more than 10 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 more than 10 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


Glen Scott

I’m a freelance software developer with more than 10 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