introduction to php – chapter 8 working with php
TRANSCRIPT
Introduction to PHP – Chapter Introduction to PHP – Chapter 88
Working with PHPWorking with PHP
JavaScript vs. PHPJavaScript vs. PHP
PHP scripts are similar to JavaScript scripts, but be careful with syntax!
PHP variables always begin with a “$” symbol. There is no equivalent to JavaScript’s “var” data declaration.
PHP scripts are embedded within a <?php … ?> tag.
PHP functions are similar to JavaScript functions, but argument passing is easier.
PHP functions can “return” a single value, with multiple values returned as elements in an array.
PHP scripts can read data from and write data to a file on a remote server.
PHP outputs can be used within the PHP application, but not “passed back” to JavaScript.
Solving the Water Vapor Solving the Water Vapor ProblemProblem
Pass instrument serial number, time and place, and instrument output voltages.
Find calibration constants for the instrument. Calculate sun’s position based on time and
place (long!). Calculate total column water vapor (short). Where should the solar position calculations
be done (they depend on time and place, but are independent of the instrument outputs)?
Decisions, decisions…Decisions, decisions…
Solar position calculations could be done in JavaScript, but we will do them in PHP to learn how to use the language.
Document 8.1 gives a complete JavaScript solution, assuming that the instrument calibration constants area known. Eventually, these calculations need to be translated into PHP.
A self-contained JavaScript A self-contained JavaScript solutionsolution
JavaScript…JavaScript…function getSunpos(m,d,y,hour,minute,second,Lat,Lon) {with (Math) {// Explicit type conversions to make sure inputs are treated like numbers, not strings. m=parseInt(m,10); d=parseInt(d,10); y=parseInt(y,10); hour=parseFloat(hour); minute=parseFloat(minute); second=parseFloat(second); Lat=parseFloat(Lat); Lon=parseFloat(Lon);
Note the use of parseFloat() and parseInt() to convert form field values to numbers.
function get_PW(IR1,IR2,A,B,C,beta,tau,airm,p) {var x = C*airm*tau - (Math.log(IR2/IR1)-A)/B;var PW = Math.pow(x,1./beta)/airm;return Math.round(PW*1000.)/1000.;
}
PHP equivalent…PHP equivalent…
$m=getSunpos($_POST["mon"],$_POST["day"],$_POST["yr"],$_POST["hr"],$_POST["min"],$_POST["sec"],$_POST["lat"],$_POST["lon"]);
$x = $C*$m*$tau - (log($IR2/$IR1)-$A)/$B;$PW = pow($x,1./$beta)/$m;
An HTML interface to PHPAn HTML interface to PHP
Output from PHPOutput from PHP
Returning multiple valuesReturning multiple valuesDocument 8.4. (circleStuff.php)<?php/* Note that this: function CIRCLESTUFF($r) { will also work because PHP function names are case-insensitive!*/ function CircleStuff($r) {
$area=M_PI*$r*$r; $circumference=2*M_PI*$r;
/* However, this won't work: return array($AREA,$circumference); because variable names are case-sensitive.*/ return array($area,$circumference); }
list($area,$circumference) = CircleStuff(3);echo $area . ", " . $circumference;
?>
More about file I/OMore about file I/O
A text file contains wind speed data:
1 1991 31 3.2, 0.4, 3.8, 4.5, 3.3, 1.9, 1.6, 3.7, 0.8, 2.3, 2.8, 2.4, 2.5, 3.2, 4.1, 3.9, 5.0, 4.4, 4.4, 5.5, 3.0, 3.7, 2.2, 2.0 2.6, 2.8, 2.3, 2.3, 1.2, 2.4, 3.1, 4.0, 3.6, 2.9, 6.0, 4.4, 0.8, 3.8, 3.5, 4.5, 2.7, 3.4, 6.6, 5.2, 1.6, 1.2, 2.3, 2.4…2 1991 28 4.6, 5.9, 3.1, 3.2, 4.5, 4.4, 3.9, 4.4, 7.5, 8.4,10.2, 9.2, 8.1, 6.3, 3.1, 3.5, 2.2, 1.4, 0.4, 4.2, 5.4, 4.0, 2.9, 1.7 2.5, 2.3, 2.1, 1.5, 2.3, 4.1, 5.3, 6.0, 6.0, 9.7,11.3,12.7,13.0,13.0,11.6, 9.9, 9.6, 8.7, 5.4, 5.1, 5.3, 5.6, 4.4, 4.2…
For each day, there are 24 hourly wind speed values. Missing hours arerepresented by a value of -1. Read this file and count and displaythe month (1-12) and the number of missing values for each month. Write the results into a file and save it.
Document 8.4. (windspd.php) <?php
$inFile="windspd.dat";$outFile="windspd.out";$in = fopen($inFile, "r") or die("Can't open file.");$out=fopen("c:/Documents and Settings/
All Users/Documents/phpout/".$outFile,"w");while (!feof($in)) {// Read one month, year, # of days. fscanf($in,"%u %u %u",$m,$y,$nDays); if (feof($in)) exit; echo $m . ', ' . $y . ', ' . $nDays . '<br />'; $nMissing=0; for ($i=1; $i<=$nDays; $i++) { $hrly = fscanf($in,
"%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f"); for ($hr=0; $hr<23; $hr++) {
echo $hrly[$hr] . ', ';if ($hrly[$hr] == -1) $nMissing++;
} echo $hrly[23] . '<br />'; } echo 'Number of missing hours this month is ' . $nMissing .
'.<br />';fprintf($out,"%u, %u, %u\r\n",$m,$y,$nMissing);
}fclose($in);fclose($out);?>
Another applicationAnother application
Write an HTML document that allows a user to select a solid object shape and enter its dimensions and the material from which it is made. The choices could be a cube, a rectangular block, a sphere, or a cube. You could choose anumber of possible materials—air, gold, water, etc. Then call a PHP application that will find the mass of the object by calculating its volume based on the specified shape and looking up the density of the material in a data file.
Document 8.5a (getMass.htm)<html><head><title>Calculate mass</title></head><body><form method="post" action="getMass.php">Enter length: <input type="text" name="L" value="3" /><br />Enter width: <input type="text" name="W" value="2" /><br />Enter height: <input type="text" name="H" value="10" /><br />Enter radius: <input type="text" name="R" value="3" /><br /><select name="shapes" size="10"> <option value="cube">cube</option> <option value="cylinder">cylinder</option> <option value="block">rectangular block</option> <option value="sphere">sphere</option></select><select name="material" size="10"> <option value="air">air</option> <option value="aluminum">aluminum</option> <option value="gold">gold</option> <option value="oxygen">oxygen</option> <option value="silver">silver</option> <option value="water">water</option></select><input type="submit" value="Click to get volume."<!--<input type="button" value="click"
onclick="alert(document.form1.shapes.selectedIndex);alert(shapes.options[shapes.selectedIndex].value); "
--> /></form></body></html>
PHP, the first step…PHP, the first step…
<?php print_r($_POST);?>
This code will display something like this:
Array ( [L] => 1 [W] => 1 [H] => 1 [R] => 3 [shapes] => cube [material] => oxygen )
Display the input values…
Create data files…Create data files…
(volume.dat)
shape volumecube $L*$L*$Lsphere 4/3*M_PI*$R*$R*$Rcylinder M_PI*$R*$R*$Lblock $L*$W*$H
(density.dat)
material density (kg/m^3)water 1000aluminum 2700gold 19300silver 10500oxygen 1.429air 1.2
Find the Find the material…material…
Document 8.5b (getMass.php)
<?phpprint_r($_POST);$material=$_POST[material];$shape=$_POST[shapes];$L=$_POST[L];$W=$_POST[W];$H=$_POST[H];$R=$_POST[R];echo "<br />" . $material . ", " . $shape . "<br />";$materialFile=fopen("density.dat","r");$shapeFile=fopen("volume.dat","r");// Read materials file.$found=false;$line=fgets($materialFile);while ((!feof($materialFile)) && (!$found)) { $values=fscanf($materialFile,"%s %f",$m,$d); if (strcasecmp($material,$m) == 0) { echo $material . ", " . $m . ", " . $d . "<br />";
$found=true; }}
Calculate the volume…Calculate the volume…
// Read volume file.$found=false;$line=fgets($shapeFile);while ((!feof($shapeFile)) && (!$found)) { $values=fscanf($shapeFile,"%s %s",$s,$v); if (strcasecmp($shape,$s) == 0) { echo $shape . ", " . $v . "<br />";
$found=true; }}// Close both data files.fclose($materialFile);fclose($shapeFile);// Calculate mass.$vv=$v . "*$d";echo "Result: ".eval("return round($vv,3);")." kg<br />"; ?>
This is the clever code!
Self-Self-contained contained HTML/PHP HTML/PHP applicationsapplications
Document 8.11 (CompoundInterest.php) <html ><head><title>Calculate Compound Interest</title></head><body><h3>Calculate Compound Interest</h3><form action="<?php $_SERVER['PHP_SELF']?>" method="post">Initial amount (no commas), $: <input type="text" name="initial" value="10000" /><br />Annual interest rate, %: <input type="text" name="rate" value="4" /><br />How many years?: <input type="text" name="years" value="20" /><br /><input type="submit" value="Generate compound interest table." /></form>
<?php$initial=$_POST["initial"];$rate=$_POST["rate"];$years=$_POST["years"];echo $initial." ".$rate." ".$years."<br />";for ($i=1; $i<=$years; $i++) { $amount=$initial*pow(1+$rate/100,$i); echo $i." ".number_format($amount,2)."<br />";}
?></body></html>