Calculator, PHP, WebApp

How To Create a Four Function Web Calculator using PHP


Overview

Browser_ServerIt is assumed that the reader has some knowledge of HTML (HyperText Markup Language) and programming logic.  Access to reference materials is recommended!

The four-function calculator page uses HTML for web page presentation and PHP (initally known as Personal Home Page, now known as PHP HyperText PreProcessor) programming language.

This application utilizes a client-server architecture where the client (Web Browser) initiates a request by POSTing to the web server using HTTP (Hypertext Transfer Protocol).  In turn, the web server reciprocates with a web page to the client (Web Browser) as a response.

The following sections exhibit and explain code snippets for web page presentation and page processing logic including installation instructions onto a Windows operating system.

The web calculator is hosted at this link:   PHP_Calculator


Web Page Presentation

<body>

<!-- Calculator FORM -->
<form method="POST" action="<?php echo $myScriptName; ?>" name="CalculateIT">
<!-- Place border on FORM and border title accordingly -->
<fieldset style="border-color:green; background-color:beige">
<legend style="color:blue; font-size: 18pt; background-color:lightsteelblue"><?php echo $myTitle; ?></legend>
<!-- Audit Trail and Intermediate Result textboxes -->
<table align="center">
<tr>
<td align="center">Audit Trail</td>
<td align="center">Intermediate Results</td>
</tr>
<tr>
<td><textarea id="t1" rows="15" name="AuditTape" cols="30"  readonly="readonly"><?php echo $frm_AuditTape; ?></textarea></td>
<td><textarea id="t2" rows="15" name="AccumTape" cols="50" readonly="readonly"><?php echo $frm_AccumTape; ?></textarea></td>
</tr>
</table>

<!-- Script to scroll both result windows to bottom of window simultaneously -->
<script type="text/javascript">
function Scroll_to_Bottom() 
{
document.getElementById('t1').scrollTop=document.getElementById('t1').scrollHeight;
document.getElementById('t2').scrollTop=document.getElementById('t2').scrollHeight;
}
// Call the function
Scroll_to_Bottom ();
    </script>

<!-- Audit Trail and Intermediate Result textboxes -->
<br/> 
<table border="1" cellpadding="10" cellspacing="0" align="center" style="border-collapse: collapse ; background-color:DarkSeaGreen">
<tr>
<td>
<!-- Place border on keyboard and display components -->
<fieldset style="border-color:green; background-color:lightsteelblue">
<!-- Calculator Display Title -->
<?php echo $MaxInput; ?> Digit Display
<br/>
<!-- Calculator Display -->
	<input name="NumIn" size="15" value="<?php echo $frm_NumIn; ?>" style="text-align:right; font-size: 10pt" readonly="readonly">
<!-- Calculator Error Message area -->
<br/>
<font color=red size="2"><?php echo $ErrMsg; ?></font>
<!-- Calculator Keypad -->
<br/>
      <input id="btn" type="submit" value="C"   name="Fclear" >&nbsp;
      <input id="btn" type="submit" value="CE"  name="Fcleare" >&nbsp;
      <input id="btn" type="submit" value="off" name="Poff" style="background-color: red; ">&nbsp;
      <input id="btn" type="submit" value="on"  name="Pon" style="background-color: green; color:lawngreen; ">&nbsp;
<br/>
      <input id="btn" type="submit" value="7"   name="B7" >&nbsp;
      <input id="btn" type="submit" value="8"   name="B8" >&nbsp;
      <input id="btn" type="submit" value="9"   name="B9" >&nbsp;
      <input id="btn" type="submit" value="/"   name="Fdiv" >&nbsp;
<br/>
      <input id="btn" type="submit" value="4"   name="B4" >&nbsp;
      <input id="btn" type="submit" value="5"   name="B5" >&nbsp;
      <input id="btn" type="submit" value="6"   name="B6" >&nbsp;
      <input id="btn" type="submit" value="x"   name="Fmult" >&nbsp;
<br/>
      <input id="btn" type="submit" value="1"   name="B1" >&nbsp;
      <input id="btn" type="submit" value="2"   name="B2" >&nbsp;
      <input id="btn" type="submit" value="3"   name="B3" >&nbsp;
      <input id="btn" type="submit" value="-"   name="Fminus" >&nbsp;
<br/>
      <input id="btn" type="submit" value="0"   name="B0" >&nbsp;
      <input id="btn" type="submit" value="."   name="Bdot" >&nbsp;
      <input id="btn" type="submit" value="="   name="Fequal" >&nbsp;
      <input id="btn" type="submit" value="+"   name="Fplus" >&nbsp;
</fieldset>
</td>
</tr>
</table>
</fieldset>
</form>
<u><i>myCalc</i></u> is for illustrative and educational purposes and does not represent a fully robust and tested calculator product.<br>
Copyright &copy; 2015  Larry Belmontes, Jr.
</body>

The above snippet represents the HTML BODY section.  The FORM, which is within the BODY, contains three components (keypad, audit trail and results) used to interact between the web browser and web server.  Below is a description of the HTML used in the web page.

Line Description
4 FORM declaration containing all interactive components within the <FORM> and </FORM> HTML tags.
When form is submitted (keypad button is pressed), form data is POST-ed to the web server and invokes script named calc_42.php as part of the ACTION keyword.  $myScriptName is set to “calc_42.php”, see calculator logic snippet.
6-7 Declare a green border with the title of myWeb Calculator.  The border surrounds all calculator components.  A beige background is applied within the green boarder.
9-18 Declare a one-row, two-column table containing two text boxes (AuditTape, AccumTape) centered horizontally within the FORM.
21-29 Javascript to scroll down both text boxes (AuditTape, AccumTape) simultaneously to keep current activity visible.
33 Declares a one-row, one-column table to contain the display and keypad components centered horizontally within the FORM.  A DarkSeaGreen background is applied to the this table.
37 Declare a green border with a lightsteelblue background for keypad components (display, error message, keypad).
39 Display title (e.g. 12 Digit Display) on the calculator keypad.
42 Numeric entry text box on the calculator keypad.
45 Error message area to display errors in red.
48-71 The buttons representing the calculator keypad.  When any keypad button is pressed, the FORM contents are POSTed to the web server for processing.


Application Processing Logic

<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL | E_STRICT);
/*'
'********************************************************
' My first web calculator
'
' Author     : Elario Belmontes, Jr.
' Description: Four function calculator simulator for
'              educational purposes to illustrate the 
'              use of a web page on a personal web
'              server
' Languanges : PHP, JAVASCRIPT, JQUERY, HTML, CSS
' File Name  : calc_42.php
' Disclaimer: This software is intended for educational learning
'             purposes.
'
'             This software is provided "AS IS" and without any
'             expressed or implied warranties, including, without
'             limitation, the implied warranties of merchantability
'             and fitness for a particular purpose.
'
'             No guarantee; No warranty; Install / Use at your own risk.
'
'
' Copyright (C) 2015 Larry Belmontes, Jr. 
'
'
'
'********************************************************
'
/*'
'********************************************************
' Create/Resume a session
'********************************************************
'*/
session_start();
/*'
'********************************************************
' Get my script file name
'********************************************************
'*/
$myScriptName = basename($_SERVER['PHP_SELF']);
/*'
'********************************************************
' Initialize variables
'********************************************************
'*/
$myTitle = "myWeb Calculator";
$ErrMsg = "&nbsp;";
$MaxInput = 12;
/*'
'********************************************************
' Process FORM post (i.e. calculator button pressed)
'********************************************************
'*/
if ($_SERVER['REQUEST_METHOD'] === 'POST')
	{
	//echo "session NumberIn=" . $_SESSION['NumberIn'] . "<br>";
	//echo "session NumberInFunction=" . $_SESSION['NumberInFunction'] . "<br>";
	/*'
	'********************************************************
	' Obtain data from FORM controls 
	'   and initialize variables
	'********************************************************/
	$frm_AuditTape = ($_POST['AuditTape']);
	$frm_NumIn = ($_POST['NumIn']);
	$frm_AccumTape = ($_POST['AccumTape']);
	/*'
	'********************************************************
	' Button on FORM pressed -
	'   Process number, function or housekeep button on form
	'
	'   Loop through each FORM field and take appropriate
	'     action from POST data
	'       (i.e.  AuditTape=&AccumTape=&NumIn=&B8=8)
	'********************************************************/
	foreach($_POST as $frm_Control =>$value)
		{
		switch ($frm_Control)
			{
			/*'
			'********************************************************
			' Math functions: add, subtract, multiply, divide
			'********************************************************/
			case "Fplus":
			case "Fminus":
			case "Fmult":
			case "Fdiv":
				Do_Math();
			break;
			/*'
			'********************************************************
			' Terminate Math function: equals
			'********************************************************/
			case "Fequal":
				Finalize_Math();
			break;
			/*'
			'********************************************************
			' Housekeep: Clear all
			'********************************************************/
			case "Fclear":
				Clear_key();
			break;
			/*'
			'********************************************************
			' Housekeep: Power Off
			'********************************************************/
			case "Poff":
				Power_Off_key();
   				exit();
			break;			
			/*'
			'********************************************************
			' Housekeep: Power On
			'********************************************************/
			case "Pon":
   				Power_On_key();
			break;
   			/*'
			'********************************************************
			' Housekeep: Clear entry
			'********************************************************/
			case "Fcleare":
				Clear_Entry_key();
			break;
			/*'
			'********************************************************
			' Numeric entry
	   		'  Limit to 16 digits entry excluding decimal point
			'********************************************************/
   			case "B0":
			case "B1":
			case "B2":
			case "B3":
			case "B4":
			case "B5":
			case "B6":
			case "B7":
			case "B8":
			case "B9":
		    	Numeric_key();
			break;
			/*'
			'********************************************************
			' Decimal point entry
			'********************************************************/
   			case "Bdot":
   				Decimal_key();
			break;
			}
		}
	}
else
	{
	/*'
	'********************************************************
	' NOT a POST, initialize session variables 
	'  Assume first time invoked
	'********************************************************/
    $_SESSION['NumberIn'] = "";
    $_SESSION['NumberInFunction'] = "";
	$frm_AuditTape = "";
	$frm_NumIn = "";
	$frm_AccumTape = "";
   	$myTitle = "Welcome to myWeb Calculator and happy calculating!";
	}

On initial calculator submission, the client PC web browser sends a calc_42.php URL request to the web server (IIS) via HTTP. The calc_42.php code is directed to the PHP processor on IIS and starts execution at line 1 establishing a session (line 37) followed setting variable $myScriptname (line 43), declaration of variables (lines 49-51) , and first time action logic (lines 162-167). No other functions are executed until the <HTML> tag is reached. An HTML response is constructed from code between the <HTML> and </HTML> tags that includes STYLE, JavaScript and FORM code. The HTML response is sent via HTTP to the client PC and rendered by the web browser as an initial calculator page.

On subsequent calculation submission, the client PC web browser posts a calc_42.php request to the web server (IIS) via HTTP. The calc_42.php code is directed to the PHP interpretor on IIS and starts executions at line 1 resuming the session (line 37) followed by setting variable $myScriptname (line 33), declaration of variables (lines 49-51) , and POST action logic (lines 47-144) processing the appropriate button via the associated function (e.g. Call Numeric_key when key 0-9 is clicked) including the updating of FORM fields. No other functions are executed until the <HTML> tag is reached. An HTML response is constructed from code between the <HTML> and </HTML> tags that includes STYLE, JavaScript and FORM code. The HTML response is sent via HTTP to the client PC and rendered by the web browser as an updated calculator page.  Below is a description of the PHP logic for the above snippet.

Line Description
37 Create or resume a session
43 Set $myScriptName from the invoking script name (i.e. calc_42.php)
49-51 Initialize variables; $myTitle, $ErrMsg and $MaxInput
57-154 Logic to execute when post method = POST (keypad button has been pressed)

Line Description
66-68 Fetch current (values before processing) FORM variables from AuditTape, AccumTape and NumIn
78
Loop
Loop through each FORM CONTROL testing for specific buttons
86-91 When  + – x or /   button is detected, invoke function Do_Math to process math function of add, subtract, multiply or divide updating associated FORM controls (i.e textboxes)
96-98   When  =   button is detected, invoke function Finalize_Math to complete current math operation updating associated FORM controls
103-105   When  C   button is detected, invoke function Clear_key to initialize result textboxes and calculator display
110-113   When  off   button is detected, invoke function Power_Off_key to clear web page and present hyperlink to power on calculator
118-120   When  on  button is detected, invoke function Power_On_key to set error message to “Power already ON…”
125-127   When  CE   button is detected, invoke function Clear_Entry_key to clear numeric entry display
133-144   When  0 1 2 3 4 5 6 7 8 or 9   button is detected, invoke Numeric_key to concatenate current digit to existing numeric entry display
149-151   When  .  button is detected, invoke function Decimal_key to concatenate a decimal point to existing numeric entry display
End
Loop
156-168 Logic to execute when post method does not = POST (first time action)

Line Description
162-163 Declare and initialize session variables to store data between calculator interactions
164-166 Initialize FORM variables; $frm_AuditTape, $frm_NumIn and $frm_AccumTape
167 Set $myTitle to “Welcome to myCalculator and happy calculating!”


Download and Install PHP Web Calculator

This application was successfully installed and tested on:

  • Windows Server 2003 with IIS 6 and PHP 5.2.6
  • Firefox 36, Chrome v41 , IE 8 (JQuery did not work correctly not allowing simultaneous scrolling in text boxes, but calculator functions were unaffected)

Other web servers such as Apache with PHP support can be used, but this post is based on Windows IIS.

1. The web server, IIS (Information Internet Services), must be installed with PHP support on your desktop/laptop computer or server.

2. Download the ZIP file and extract to a temporary directory.

Download calc_42_php

3. Open the ZIP file and copy file, calc_42.php, to the web server PHP webroot directory.

4. Open a brower window (e.g. Internet Explorer or Chrome)

5. Type http://localhost/calc_42.php in the address bar and press ENTER.

6. The calculator web page should display

7. On the calculator keyboard the following buttons in order –
 3  +  7  /  2  =       The result should be 5

8. Happy calculating!!


Next Learning Experience

Introduce a client-side solution by using JavaScript to perform all logic needs for the web calculator.  No web server is required in this case.  Simply, point your browser to an HTML file.

Take a look at other related posts.

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image

This site uses Akismet to reduce spam. Learn how your comment data is processed.