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.

Be Sociable, Share!

2 thoughts on “URL Encoding and Decoding from the command line

  1. Fantastic! I was looking for a solution to do exactly this for the better part of the evening – I’ve found I don’t know how many ways to url-encode utf8 text, but this seems to be one of the few standalone decode/encode tools. Great work.

    It runs without modification on Ubuntu 8.04 with the standard LAMP stack installed.

  2. You could improve this utility by having it accept multiple parameter at once (e.g. -ef instead of -e -f) and by declaring $file to avoid the warning on the function in line 71 when using standard input. Nicely done anyway, you have my gratitude as I could not find anything similar around.