Skip to content


/etc/hosts file on Mac OSX

I just put this together to cover a question I was asked recently. Might be useful to someone…

Where is the /etc/hosts file in Mac OS X?

The hosts file used by Mac OS X is in /etc/. Windows users sometimes have problems finding it since there’s no %SystemRoot%\system32\drivers\etc folder in the Mac OS. UNIX users might not expect /etc/ to be hidden by the Mac OS X Finder, so they often look in /Library/Application Support/

Accessing /etc/hosts

/etc/ is hidden by default. The easiest way of getting to the hosts file is to open /Applications/Utilities/Terminal.app. Then type:
sudo nano /etc/hosts

…you will need to type in your password. Your hots file will open in the text editor ‘nano.’

Adding entries to /etc/hosts

On a new line type the IP Address followed by at least one space or tab and then the hostname. Examples:
127.0.0.1 mydevsite.local
192.168.1.222 ads.shadycompany.biz

…hit ctrl + o to Save, and then ctrl + x to quit the text editor.

See here for more about using /etc/hosts for Virtual Servers: Adding an entry to /etc/hosts on OS X

Background: What is /etc/hosts used for?

The hosts file is a simple way of mapping IP Addresses to hostnames. It overrides mappings provided by the Domain Name System network. The hosts file is commonly used by network administrators to provide access to LAN resources when no name resolution is available. The other common usage is to block access to specified hosts by adding host entries resolving them to — for example — 127.0.0.1.
More Resources:
http://en.wikipedia.org/wiki/Hosts_(file)

Posted in mac osx. Tagged with , , , .

Two Nifty Terminal History Tricks

I’ve covered the ‘history’ command before, but here are two more useful Mac OS X Terminal commands…

I’ve been using the Ctrl+ R trick (Hit Ctrl + R, start typing part of the command you want. If you don’t like the first suggestion hit Ctrl + R again to show the next one). This is really handy and fast and it will return matches from the middle of the string.

And I just found another great Terminal command here: Discover the last used command beginning with anything without executing it… this one is a bit harder to use:

![needle]:p

…where [needle] is the first character(s) of the command you’re looking for. It’s not as flexible because it only shows the most recent match instead of cycling through the results, but could still come in handy.

Posted in mac osx. Tagged with , .

Adding an entry to /etc/hosts on OS X

Web Developers, Administrators of Mac Networks, and anyone who likes to noodle with OS X will probably eventually need to add hosts file entries. I use them when I’m testing a moved and/or changed version of a website at new hosting before I move the DNS.

I used to add hosts file entries manually then wonder why they didn’t seem to work. I tried rebooting, logging out, etc with varying success, until I learned this trick. On the Mac you must flush the DNS cache for the changes to take effect. Mac OS X used to have a friendly utility called NetInfo Manager, but that seems to have been removed in Leopard, so we’re using terminal commands.

Open a terminal sesion and type:
sudo nano /etc/hosts

Hit the down arrow until you get to the end of the file, and add your hosts file entry, for example:
192.168.2.33 myintranetserver.mydomain.com
… I put in an extra line break at the end. I don’t think it’s really necessary but it’s a habit from having to use Windows, which would ignore the last line in a hosts file.

then flush the cache:
sudo dscacheutil -flushcache

…the name should now resolve! Test it:
ping myintranetserver.mydomain.com

Other Info

One thing that Windows, for all its annoyances, did get right is that changes to the hosts file (in ‘c:\Windows\system32\drivers\etc’) are reflected immediately. I’d like to see Apple do something about this in OS X, perhaps just flushing the cache automatically when /etc/hosts changes.

Another handy use for /etc/hosts is to set up mapping of virtual server addresses. For example, I use MAMP on my development Mac, and create new virtual hosts entries in Apache for each site I’m working on. Then for each I just add a new entry in the hosts file, e.g.:
127.0.0.1 devclientsite7.leftcolumn.net
… then I just use devclientsite7.leftcolumn.net:8080 in Safari or Firefox to access the development site. It means my development sites don’t have to be in subdirectories, instead I just make sure the sites use a config file to figure out what their address is, and I make sure that config file is updated when the site is moved to a live system.

On OS X Tiger (10.4) and probably earlier, there was some strange behaviour with hosts file entries. You could add an entry and it would take effect, but if you had no network available, the name would not resolve and could not be used, even if it resolved to 127.0.0.1! So you have the bizarre situation of putting in addresses for virtual hosts as described in the previous paragraph, all of which resolve to 127.0.0.1, but still not being able to use them for testing and development when not connected to the Internet. If anyone can enlighten me as to how this was anything other than a bug in OS X I’d be interested…

You can also use hosts file entries to block ads (by resolving common ad server addresses to e.g.: 127.0.0.1). You can download huge lists of ad servers for this purpose. This is a good idea when you’re stuck using Internet Explorer on Windows, especially on dial-up.

Posted in mac osx. Tagged with , , , .

MacBook Pro won’t wake up from sleep

One day my new MacBook Pro 17″ wouldn’t wake up. When I opened the lid machine was running but the Desktop wouldn’t load (just a default blue Desktop background colour) and there was no response from the Mouse or Keyboard. I eventually had to hard reset the Mac.

This annoying issue can apparently be caused a few different ways, but if your Mac is new and has all System Updates applied, chances are that the issue is caused when you close the lid and then move the mac before the contents of RAM are written out. There’s a feature called Safe Sleep, enabled by default, which can preserve and restore the state of a sleeping Mac even when the battery is removed. This sounds great, but the Safe Sleep procedure can take up to 30 seconds, which is too long for me.

How to fix this annoying problem? Here’s how I switched it off:

sudo pmset -a hibernatemode 0
sudo rm /var/vm/sleepimage

…you need to supply the super user password. After making the change, reboot the Mac. The Mac should now Sleep within a couple of seconds. The second line removes the file that Sleep Safe uses to store the contents of RAM. Since you’ve switched off Safe Sleep, the space can be recovered.

Personally I don’t see the need for Safe Sleep on a Mac with a non-removable battery, but be aware that if the machine is asleep and runs out of battery power you wil lose your logged in session! I haven’t tried it, and most OS X apps will deal pretty well with this anyway, but it’s not wise to let this happen…

More details:

Apple pmset Manual
Macworld article on setting sleep modes

Posted in mac osx. Tagged with , , .

Zend Framework: How to add FCKeditor to a Zend_Form

There are around 1,083,367 JavaScript-based Rich-Text Editors out there, and I’m sure most are pretty good. But I’ve had good results with FCKeditor so I use it on all my projects. Here’s a step-by-step guide to adding the FCKeditor to your Zend Form Elements.

1 – The basics

Download FCKeditor and Upload it to your Web Server. It needs to be somewhere accessible to the world, for example: /js/fckeditor/, which on your server may be a path like /var/www/html/your_site/js/fckeditor/.


2 – .htaccess

The .htaccess that sets up your index.php as the bootstrap needs to exclude the files that FCKeditor uses. If your bootstrap code in .htaccess looks like this:

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

you’ll need to change it. I typically only rewrite to /index.php if the requested file really doesn’t exist. So .htaccess should be something like this:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1


3 – Zend_Form Elements

In the Form code, you need to make sure that you know the id of the Element (In this case the id is ‘body’), and that you are filtering out all tags and attributes that you don’t want to explicitly allow. Create an allowed_tags list like the one below and ensure that the FormElement has a StripTags filter applied to it:

$allowed_tags = array(
	'a' =>	array('href', 'title'),
	'strong',
	'img'	=>	array('src', 'alt'),
	'ul',
	'ol',
	'li',
	'em',
	'u',
	'strike');

$body = new Zend_Form_Element_Textarea('body');
$body->setLabel('Body')
	->setAttrib('rows', 12)
	->setAttrib('cols', 40)
	->setRequired(true)
	->addFilter('StringTrim')
	->addFilter('StripTags', $allowed_tags);


4 – View Script

Let’s Assume that you use Layouts, and that you only want to use the FCKeditor on a couple of pages on your site. You don’t want to include the FCKeditor code on every page because it just adds to the page size, so we do something like this in the View Script (Note: WordPress is messing with the quote marks in this block, ensure you have single quotes after src= and before the last semicolon. The other quotes should be double quotes.):

$this->custom_head = '<script src="/js/fckeditor/fckeditor.js" type="text/javascript"></script>';
$this->custom_head .= "<script language='javascript' type='text/javascript' src='/js/customs.js'></script>";
$this->custom_body = ' onload="setupFCK()"';


5 – Layout Script

The Layout Script needs to know about this new variable, so the Layout Script needs to know to refer to $this->custom_head if it is set. Drop the code below inside the <head> section of your layout script:

<?php

if ($this->custom_head) {
	echo $this->custom_head;
}
?>

…and change the html body element to look like this:

<body<?php if ($this->custom_body) {
	echo $this->custom_body;
}?>>

6 – Loading the FCKEditor when the page loads

Create /js/custom.js and put this in it:

function setUpFCK() { if(document.getElementById('body')) { var oFCKeditor = new FCKeditor('body') ; oFCKeditor.BasePath = "/js/fckeditor/" ; oFCKeditor.Height = 400; oFCKeditor.ReplaceTextarea() ; } }

7 – FCKeditor changes

I like to implement FCKeditor as a single row of buttons for basic editing, just to keep it from looking too big and clunky. I use a set of icons like this:

FCKConfig.ToolbarSets["Default"] = [
	['Bold','Italic','Underline','StrikeThrough','OrderedList','UnorderedList','Blockquote','Link','Unlink','Image', 'SpecialChar','SpellCheck']
] ;

And I don’t want to enable any kind of file uploads, so I make sure these configs are all set to false (edited to show the relevant bits):

FCKConfig.LinkBrowser = false ;
...
FCKConfig.ImageBrowser = false ;
...
FCKConfig.FlashBrowser = false ;
...
FCKConfig.LinkUpload = false ;
...
FCKConfig.ImageUpload = false ;
...
FCKConfig.FlashUpload = false ;


8 – Anything else?

Not really! There are no Controller changes, which is good because this stuff all belongs in Views anyway. The Models know about the allowed tags, which is good because that’s the kind of work that Models should do. So to me this solution fits the MVC pattern and is not too hack-like. Feedback welcome…

Update: 25/3/09

Fixed various problems with the instructions and it should now all work properly.

Update: 20/3/09

I’ve been doing a bit of reading about Ruby on Rails with the intention of moving to it as my primary development platform. I haven’t quite got my head around the integration of front-end stuff like FCKeditor yet but Rails really does look like it simplifies the creation and maintenance of forms, which is, after all, about 70% of the work in websites. Need an example? Well Rails has a sensible defaults approach to forms where they can be created automatically based on the model. So compare that to Zend Framework, where I create a separate class for the Form that must match the structure of the model (and be updated when the model changes)! For a big site, that is significant: only one class per table/model!

Update: 29/11/2011

Fixed a typo. Also: check out Frost’s comment below for a tidier way to do this.

Posted in zend framework. Tagged with , , , .

Zend Framework one-line platform config: Configure, Don’t Integrate

Separating config from code in Zend Framework is not as simple as it is in say, Ruby on Rails. And when your source code is version-controlled you want to minimise the manual configuration required. So here’s a nice way to keep it simple. The idea is to keep configuration data for your test and production environments in a single config file that does not change, then switch environments in a dedicated separate one-line config file.

Here’s a sample platforms.ini:

[test]
developer_mode = true
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.dbname = testdb
db.params.username = lkdf034k3k3b
db.params.password = SJGS43we3sdd

[production]
developer_mode = false
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.dbname = productiondb
db.params.username = ksjdhfkjjdhf
db.params.password = jfdhkjsdhdjk

.. .And here’s active_platform.ini. This is where we define which of test or production is currently active:

[platform]
setting = test

…And here’s how index.php refers to active_platform.ini to first determine which platform it’s on, and second load the appropriate config from platforms.ini:

// which platform mode are we on? i.e.: test or production
$active_platform = new Zend_Config_Ini('application/configs/active_platform.ini','active_platform');

// get the platform config
$config = new Zend_Config_Ini('application/configs/platforms.ini', $active_platform->setting);
Zend_Registry::set('config', $config);

// set up the db
$db = Zend_Db::factory($platform_config->db);
Zend_Db_Table::setDefaultAdapter($db);

When you want to deploy to production, you change the setting in active_platform.ini to ‘production.’ Simple as that.. this may be obvious but I’ve found it to speed up deployment and make it less error-prone.

Posted in zend framework. Tagged with , , .