Specifications
For example, under UNIX-like operating systems, you can use
$out = `ls -la`;
echo “<pre>”.$out.”</pre>”;
or, equivalently on a Windows server
$out = `dir c:`;
echo “<pre>”.$out.”</pre>”;
Either of these versions will obtain a directory listing and store it in $out. It can then be
echoed to the browser or dealt with in any other way.
There are other ways of executing commands on the server. We will cover these in Chapter 16,
“Interacting with the File System and the Server.”
Using Operators: Working Out the Form Totals
Now that you know how to use PHP’s operators, you are ready to work out the totals and tax
on Bob’s order form.
To do this, add the following code to the bottom of your PHP script:
$totalqty = $tireqty + $oilqty + $sparkqty;
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
$totalamount = number_format($totalamount, 2);
echo “<br>\n”;
echo “Items ordered: “.$totalqty.”<br>\n”;
echo “Subtotal: $”.$totalamount.”<br>\n”;
$taxrate = 0.10; // local sales tax is 10%
$totalamount = $totalamount * (1 + $taxrate);
$totalamount = number_format($totalamount, 2);
echo “Total including tax: $”.$totalamount.”<br>\n”;
If you refresh the page in your browser window, you should see output similar to Figure 1.5.
As you can see, we’ve used several operators in this piece of code. We’ve used the addition (+)
and multiplication (*) operators to work out the amounts, and the string concatenation operator
(.) to set up the output to the browser.
We also used the number_format() function to format the totals as strings with two decimal
places. This is a function from PHP’s Math library.
If you look closely at the calculations, you might ask why the calculations were performed in
the order they were. For example, consider this line:
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
PHP Crash Course
C
HAPTER 1
1
PHP CRASH
COURSE
33
03 7842 CH01 3/6/01 3:39 PM Page 33