PHP Console

journal

I have been troubled with finding a good calculator that does everything I need. I could not find one.

Apple's calculator works, but you can't do multiple windows and complex equations. So you'll have to copy the result to a text edit document, then do a lot of other things in order to get the result you want.

So the solution I've ended up with is a little PHP hack I've written to be my calculator. I am sharing it for anyone who ever had my urge to have a better calculator. Because it's PHP, you can use any functions such as pow(), tan(), and round(). You can do random numbers and much more.

Here is the steps to set this up. I will start by telling you how to setup a user binary folder so that you can write you own code and place it in a folder to where you can just type the command and have it run.

  1. Open terminal, type in sudo nano /etc/paths
  2. Once you are in the file, at the top row, type /usr/ubin The end result should look similar to this:
/usr/ubin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/usr/local/sbin

If you do not have some of the lines, do not fret as I may have more things installed.

  1. Exit and save the file by pushing ctr-x to exit and y when asked to save.
  2. Make the user binary folder by typing this in terminal sudo mkdir /usr/ubin; sudo chown $USER /usr/ubin
  3. Open your favorite text editor (mine TextMate), and place the following code in it.
#!/bin/bash
php /usr/ubin/console.php
  1. Save it as phpconsole in the user binary folder. To get to the user binary folder, push cmd-shift-g for "Go to Folder" and in the box, type /usr/ubin.
  2. Save it and then in terminal type chmod +x /usr/ubin/phpconsole to add execute permissions to the file.
  3. Open a new text document with the code below in it.
<?
while (1) {
    $command = readline("> ");
    try {
        if (preg_match("/^[0-9]+/i", $command) || !preg_match("/;/i", $command)) {
            $result = eval("return ".$command.";");
            echo $result."n";
        } else {
            eval($command);
        }
    } catch (Exception $e) {
        echo "Error: ".$e->getMessage()."n";
    }
}
?>
  1. Save it as console.php in the user binary folder.
  2. Test your work by typing phpconsole in terminal.

Examples of use:

$ phpconsole
> 1+1
2
$ phpconsole
> pow(15,2)*pi()
706.8583470577
$ phpconsole
> $kb = 10;
> $mb = 200;
> $gb = 4;
> $total = (($kb/1024)/1024)+($mb/1024)+$gb;
> echo "Total Size: ".round($total, 2)." GBn";
Total Size: 4.2 GB
$ phpconsole
> rand(1,5)
5
> rand(1,5)
3

Hope you enjoy this little hack, I know I am as I don't have to worry about bad calculators!

Previous Post Next Post