URL Encoding and Decoding from the command line

I needed a simple way to URL encode a bunch of data, and in the past I’ve also needed to generate this on the fly in my shell scripts. Not finding a simple solution I wrote my own utility using PHP. If you aren’t aware of running PHP from the CLI it can be handy, and in my case PHP includes the functions urlencode and urldecode.

This was tested and used on Mac running Leopard. I’m certain it will work fine on most flavors of unix, provided you adjust the path to PHP and it’s running to support the CLI.

You can download the zip version of this file here urlcoder.zip
From the help:
Usage: urlcoder.php [-option]
This program takes input from STDIN or a file and encodes or decodes the data for use in URLs
-f  filename to de/encode if no file name is given input will be taken from STDIN.
-e  Encode the input.
-d  Decode the input.
-v  Show the version.
-h  Show this help.
Usage Note: running the command without a file or piping input will leave the application running, and entering data with a carriage return at the prompt will process based on your en/decode option.
This program uses the PHP urldecode and urlencode functions. From the PHP Manual:
urlencode – Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.


urlcoder -e -f filename.txt
grep -o search datasource | urlcoder -e
echo "mike strutton" | urlcoder -e
urlcoder -e
(input strings manually followed by enter)

If you don’t frequent the Terminal (or unix shell), you will need to extract the zip file, saving it somewhere in your path, and modify the file to  it to be executable (chmod +x urlcoder). If you don’t understand this, then I highly doubt you have any use for a urlcoder anyway.

Questions, comments, variations? Drop a comment.