Easy local-hosting

Heres a super-simple way to quickly fire up a local web server for development and testing. It uses the built-in PHP server and has almost replaced MAMP for me.

The latest version of PHP (which also ships with OSX mavericks) includes it’s own built in server, all you need to do is change to the directory in terminal and type PHP -S 0.0.0.0:8000 (or port 80 if you want to authenticate each time). You will then be able to browse to localhost:8000 and your lovely site will be awaiting.

But that’s a bit of a pain to do each time. So I wrote a simple Automater script that allows you to launch the web server from the right-click menu on a folder. Automater is a tool on the mac that allows you to automate repetative tasks, so it’s ideal for this.

  1. First open up Automator from the applications folder and select ‘Service’ as the document type.

  2. Where it says ‘Service receives selected’ select folders in finder. This tells Automator that the input will be a folder location from finder. We now need to open terminal and run the php script from this location. We’ll do this with apples scripting language, applescript.

  3. In the Actions library to the left of the window type applescript into the search box. It should find’Run Applescript’, double-click or drag this into the project.

  4. Here is the script you need to use:

    -- bring the folder location into the script
    on run {input, parameters} 
    
        -- define a variable of 'the_path'
        set the_path to (the POSIX path of input) 
    
        -- open terminal and navigate to the directory
        tell application "Terminal"
            activate
            do script "cd " & POSIX path of the_path
    
            --launch the server and minimise the window
            do script "php -S localhost:8000" in window 1
            set miniaturized of window 1 to true
        end tell
    
    end run
  5. Your website should now be running on http://localhost:8000.

  6. We can now add an action to open the web browser for extra convenience. From the actions panel find ‘Get Specified URLs’ and add it to your action. Remove the apple link if it’s there, then click on add and type http://localhost:8000. We then need to add one final action to actually launch the browser, this is called ‘Display Webpages’. The action as seen in automater
  7. Hit save and give it a name like ‘localhost’. You will now be able to right click on a folder containing a site, go to services -> localhost and it will launch the server and open your browser for you, how convenient!

The server is perfect for front-end development and flat file CMS’s like statamic and kirby, but don’t expect it to run anything heavier, it doesn’t like databases at all. You will also need to close the server before you run another one, I managed to create a script that does this for you and is in action at feedmewebsites.com.