Oxaric’s Blog

A compendium of amazing things…

Archive for the ‘PHP’ Category

Quick BASH Script For Easier PHP Execution

Posted by oxaric on December 4, 2008




If you’re not running a web server, such as Apache, you might find PHP script can be a bit annoying to run. First you write your .php script, save the file, run the file through PHP, save the output into an .html file, and finally open the .html file in your preferred browser.


In order to simplify the steps needed to view the results of your .php script I created the Bash script below to automate some of the intermediary steps. The script takes the filename of a .php script, runs it through PHP, saves the resulting .html code as filename.html, and then opens the html file in Firefox.


Example:

~/test> ./runphp.sh myscript.php


Click to directly download runphp.sh


# Louis Casillas, oxaric@gmail.com
# Usage:
#       ~$ ./runphp.sh myphpfile.php


# Takes a php filename and executes the php code which
# creates html code.  Saves the resulting html code 
# into filename.html and opens the html file with
# Firefox.


# Assumes you have a version of php and firefox  
# installed on your system


if [[ "$1" == "" ]]; then
   echo
   echo "Specify a php filename"
   echo


   exit
fi


php_filename="$1"
php_filename_size=${#php_filename}
period_position=-1


# search for the last period in the passed filename
for ((i=$php_filename_size;i>=0;i+=-1)); do


   if [[ "${php_filename:$i:1}" == "." ]]; then
      period_position=$i
      break;
   fi
done


# if the passed filename contains a period then erase the
# file extension and add .html to the filename
if [ $period_position -eq -1 ]; then
   html_filename="$php_filename"".html"
else
   html_filename="${php_filename:0:$period_position}"".html"
fi


# run the php code and store the resulting html code
php $php_filename > $html_filename


# open the html file in firefox
firefox $html_filename

Posted in BASH, Linux, PHP | Tagged: , , , , , , , , , | Leave a Comment »