Using these files: HTML/JavaScript files can be copied into an code editor such as AceHTML. If the file does not require access to another code or image file, they can then be viewed from the editor. If they require access to other files, such as 1.5, which requires an image file, or 2.2a or 2.2d, which require access to another HTML file in a specific directory, then all the files must be saved in an appropriate directory. For example, 1.5 assumes that the image file is in the same directory as the HTML file. PHP files must be run on a local or remote server. As discussed in the book, they will NOT run directly from an code editor. So, you must save individual code files in the required directory, e.g., C:\wamp\www\ for an Apache server installed locally on your Windows computer. In some cases, data files are included in this file. In other cases, you must create your own data files. Command line interface (CLI) files, as discussed in Chapter 11, must be saved in a directory that contains the required PHP files. Note that in a few cases, the code as printed in the book required line breaks that will cause syntax errors if the code is copied exactly as it appears in the book. For example, quote-delimited text strings cannot be broken, but some of those text strings are too long for one line in the book. In this file, there are no such broken lines, and code copied from this file should not result in syntax errors caused by broken text strings, (When broken text strings are found, they produce an error message something like "unterminated text string.") Document 1.1 (HelloWorldHTML.htm) First HTML Document Hello, world! ----------------------------- Document 1.2 (HelloWorld.htm) Hello, world! ------------------------------ Document 1.3 (HelloWorld2.htm) Hello, world!

First JavaScript


------------------------------- Document 1.4a (HelloWorld3.htm) Hello, world! (v.3)

First JavaScript


----------------------------------- Document 1.4b (HelloWorld3HTML.htm) Hello, world! (with HTML)

First JavaScript


Hello,world!
He said, "It's a beautiful day!"
" ------------------------ Document 1.5 (house.htm) Our New House

Our New House

Here's the status of our new house. (We know you're fascinated!)


------------------------------ Document 2.1 (tagExamples.htm) Tag Examples

Here is a Level 1 Heading

Here is a Level 2 Heading


	Here is some preformatted text that has
 	been created with the pre element. Note that it retains the 
paragraph tab
included
in the original       document. Also, it does not "collapse" line feeds
and
		white          spaces. Often, it is easier to use preformatted text than it
is to use markup to get the same effect. Note, however, that the default 
rendering of
preformatted text is to use a monospaced Courier font. This is often a good choice for
displaying code in an HTML document, but perhaps not a good choice for other kinds of text content.

Here, a small graphic (the check box) has been inserted into the document using the "img" element. This text is outside the preformatted region, so the default font is different. If you look at the original document, you can also see that white spaces and line feeds are now collapsed.

Note too, that the text is now centered. The way the text is displayed will depend on how you have the display window set in your browser. It may change when you go from full screen to a window, for example.

Centering is now turned off. The default text alignment is to the left of your screen. You can change the size and color of text by using the <font> element. ------------------------- Document 2.2a (index.htm) My Page Here are links to homework and personal documents. -------------------------- Document 2.2b (resume.htm) Resumé Here is my resumé. ---------------------------- Document 2.2c (homework.htm) Homework Here are my homework problems. ------------------------------------------------------ Document 2.2d (index2.htm, a new version of index.htm) My Page Here are links to homework and personal documents. ------------------------- Document 2.3 (style1.htm) Style Sheets Here is the body. ------------------------ Document 2.4a (body.css) body {background:silver; color:white; font:24pt Times} h1 {color:red; font:18pt Impact;} h2 {color:blue; font:16pt Courier;} -------------------------- Document 2.4b (style2.htm) Style Sheet Example (See Color Example 2 for full-color output.)

Heading 1

Heading 2

Here is some text. ----------------------- Document 2.5a (rwb.css) p.red {background:red;color:blue;font:20pt Times} div.white {background:white;color:red;font:20pt Times} span.blue {background:blue;color:white;font:20pt Times} ----------------------- Document 2.5b (rwb.htm) A Red, White, and Blue Document

This text should be blue on a red background.

This text should be red on a white background.

This text should be white on a blue background.

----------------------------- Document 3.1 (radonTable.htm) Radon Table

Results of radon testing

The table below shows some radon levels measured in residences.
For values greater than or equal to 4 pCi/L, action should be taken
to reduce the concentration of radon gas. For values greater than or
equal to 3 pCi/L, retesting is recommended.

LocationValue, pCi/L Comments
DB's house, basement15.6 Action should be taken!
ID's house, 2nd floor bedroom3.7 Should be retested.
FJ's house, 1st floor living room 0.9 No action required.
MB's house, 2nd floor bedroom2.9 No action required.
------------------------ Document 3.2 (tbody.htm) Using the tbody element ---------------------------- Document 3.3 (cloudType.htm) Cloud Type Chart
MonthAverage
Temperature
°F
January30.4
February33.0
March42.4
April52.4
May62.9
June71.8
July76.7
August75.5
September68.2
October56.4
November46.4
December35.8
Cloud Type Chart
Altitude Cloud Name
High Cirrus
Cirrocumulus
Cirrostratus
Middle Altocumulus
Altostratus
Low Cumulus nonprecipitating
Altocumulus nonprecipitating
Stratocumulus nonprecipitating
Cumulonimbus precipitating
Nimbostratus precipitating
--------------------------- Document 3.4 (location.htm) Data Reporting Site Information
Please enter your last name:
Please enter your latitude: N or S
Please enter your longitude: E or W
Please enter your elevation: meters
Please indicate the seasons during which your site reports data:
Winter: Spring: Summer: Fall:
------------------------- Document 3.5 (select.htm) Pull-Down List
Select a month from this menu:
--------------------------------- Document 3.6 (siteDefinition.htm) Observation Site Descriptions
Observation Site Descritions
Site #Site NameLatitude LongitudeElevation
Site 1
Site 2
Site 3
Site 4
Site 5
---------------------------- Document 3.7 (location2.htm) Location information
Please enter your last name:
Please enter your latitude: N or S
Please enter your longitude: E or W
Please enter your elevation: meters
------------------------ Document 3.8 (lists.htm) Using HTML Lists This page demonstrates the use of unordered, ordered, and definition lists. Here are three ways to organize content in an HTML document:
  1. Use a table.
  2. Use a list.
  3. Use <pre> ... </pre> tags.
This is a way to produce a neatly formatted glossary list.
definition list (<dl>)
Use this to display a list of glossary items and their definitions.
ordered list (<ol>)
Use this to display a numbered list.
unordered list (<ul>)
Use this to display a list of bulleted items.
------------------------------- Document 3.9 (bookContents.htm) Table of Contents for My Book

Table of Contents for My Book

  1. Chapter One
    1. Section 1.1
      1. First Topic
      2. Second Topic
        • subtopic 1
        • subtopic 2
    2. Section 1.2
    3. Section 1.3
  2. Chapter Two
    1. Section 2.1
      1. First Topic
      2. Second Topic
        • subtopic 1
        • subtopic 2
    2. Section 2.2
    3. Section 2.3
  3. Chapter Three
    1. Section 3.1
      1. First Topic
      2. Second Topic
        • subtopic 1
        • subtopic 2
        • subtopic 3
    2. Section 3.2
    3. Section 3.3
      1. First Topic
      2. Second Topic
    4. Section 3.4
------------------------------ Document 3.10a (frameMain.htm) A simple frameset document ------------------------------ Document 3.10b (homeFrame.htm) My Home Frame

Home page display goes here.

--------------------------- Document 3.10c (frame1.htm) Title Frame
Frames
Demo
--------------------------- Document 3.10d (frame2.htm) Gossip Column Links to other stuff...
Gossip Column
Picture Gallery
home
------------------------------------- Document 3.10e (frameDescription.htm) How this image was created. This image was created in Windows' Paint program. Click here to return. -------------------------- Document 3.11 (cloud1.htm) Cloud Observations

Cloud Observations

Cloud Observations (Select as many cloud types as observed.)
High Cirrus Cirrocumulus Cirrostratus

Middle Altostratus Altocumulus

Low Stratus Stratocumulus Cumulus

Rain-Producing Nimbostratus Cumulonimbus
-------------------------------------- (partial data file for Document 3.12a) DRB Worcester PA 40.178 -75.3325 4030 5200 Mon day yr hr min sec EST PYR-1 PYR-2 T 7 1 2008 0 0 0 1 0.00031 0.00031 20.198 7 1 2008 0 1 0 1.000694444 0.00031 0.00031 20.174 7 1 2008 0 2 0 1.001388889 0.00031 0.00031 20.174 ------------------------------------ Document 3.12a (pyranometerMain.htm) Display pyranometer data --------------------------- Document 3.12b (header.htm) This is the header.
mon    day     yr    hr     min    sec     EST           PYR-1  PYR-2  T
------------------------- Document 4.1 (circle.htm) Calculate area of a circle. ------------------------------------- Document 4.2 (incrementDecrement.htm) Increment/decrement operators --------------------------------- Document 4.3 (mathFunctions2.htm) Demonstration of the Math object. ------------------------- Document 4.4 (grades.htm) Get letter grade ------------------------ Document 4.5 (taxes.htm) Calculate income tax ------------------------------ Document 4.6 (daysInMonth.htm) Days in Month --------------------------- Document 4.7 (counter2.htm) Counter ----------------------------- Document 4.8 (countdown2.htm) Countdown --------------------------- Document 4.9 (gorilla1.htm) The elevator problem (with gorillas). ------------------------------- Document 4.10 (newtonSqrt2.htm) Newton's square root algorithm ----------------------------------- Document 4.11 (stationPressure.htm) Convert sea level pressure to station pressure. Convert sea level pressure to station pressure (true pressure)

This application converts sea level pressure to station pressure.
Station pressure is the actual pressure at an observer's observing site.
It is always less than or equal to sea level pressure (unless you are below
sea level).
Fill in elevation and sea-level pressure: (m) (mbar)
(mbar)
----------------------------- Document 4.12 (quadratic.htm) Solving the Quadratic Equation
Enter coefficients for ax2 + bx + c = 0:
a = (must not be 0)
b =
c =
click for r1 =
click for r2 =
----------------------------------- Document 4.13 (RectangularRule.htm)

Rectangular Rule integration

for f(x)=x2
xo:
x1:

--------------------------- Document 5.1 (siteData.htm) Site Names ---------------------------------- Document 5.2 (stacksAndQueues.htm) Stacks and Queues ----------------------- Document 5.3 (sort.htm) Sorting Arrays ---------------------------- Document 5.4 (TwoDArray.htm) Two-D arrays ------------------------------ Document 5.5 (TwoDArray_2.htm) "Multidimensional" arrays ---------------------------- Document 5.6 (formArray.htm) Using the elements[] array to access values in forms.
A[0]
A[1]
-------------------------- Document 5.7 (sumForm.htm) Sum a column of values



Here is the sum of all the values.

--------------------------- Document 5.8 (sumForm2.htm) Sum a column of values
Here is the sum of all the values.

------------------------------- Document 5.9 (buttonAccess.htm) Accessing Radio Buttons and Checkboxes Access contents of form fields...
Give name:
Employee is punctual: Y       N
Employee likes these animals: Dogs Cats Boa constrictors

# elements:
Which one (0 to # elements - 1)? Contents:
-------------------------------- Document 5.10 (chooseSelect.htm) Using values from a select list

Shows how to access values from a <select> tag.

Only one item can be chosen...


Click in this field to see what you have chosen:

Multiple items can be chosen...

Hold down Shift or Ctrl key to make multiple selections.

Click on this field to see what you have chosen:
----------------------------- Document 5.11 (siteData4.htm) "Multidimensional" arrays ----------------------------------------- Data file siteData.dat for siteData4.htm: var siteID = new Array(); function IDArray(ID,lat,lon,elev) { this.ID=ID; this.lat=lat; this.lon=lon; this.elev=elev; } siteID[0]=new IDArray("Drexel",39.955,-75.188,10.); siteID[1]=new IDArray("home",40.178,-75.333,140.); siteID[2]=new IDArray("NC",35.452,-81.022,246); siteID[3]= new IDArray("Argentina",-34.617,-58.367,30.); siteID[4]=new IDArray("Netherlands",52.382,4.933,-1); ----------------------------- Document 5.12 (password1.htm) Check a password
Enter your password:
(Tab to or click on this box to check your password.)
------------------------------- Document 5.13 (magicSquare.htm) magic Square -------------------------- Document 6.1 (circle1.htm) Circle Area (1)

Circle Area (1)

Enter radius, then press tab key or click on "area" box.
radius (cm): area (cm2):
-------------------------- Document 6.2 (circle2.htm) Circle Area (2)

Circle Area (1)

Enter radius, then press tab key or click on "area" box.
radius (cm): area (cm2):
-------------------------- Document 6.3 (circle3.htm) Circle Area (4)

Circle Area (3)

Enter radius, then press tab key or click on "area" box.
radius (cm): area (cm2):
------------------------------ Document 6.4 (circleStuff.htm) Circle Stuff

Circle Stuff

Enter radius, then press tab key or click on "area" box.
radius (cm): area (cm2): circumference(cm):
------------------------------- Document 6.5 (circleStuff2.htm) Circle Stuff with Arrays

Circle Stuff

Enter radius, then press tab key or click on "area" or "circumference field.
radius (cm): area (cm2): circumference(cm):
------------------------------ Document 6.6 (parseIntBug.htm) parseInt() "bug"
integer value:
Click for parseInt("string") result:
Click for parseInt("string",10) result:
Click for parseFloat("string") result:
----------------------------- Document 6.7 (calculator.htm) Simple Calculator
Type expression to be evaluated, using numbers and +, -, *, /:
----------------------------- Document 6.8 (factorial2.htm) Calculate n!

Calculate n factorial (n!)

Enter n (a non-negative integer): (Press Tab to get n!.)

---------------------------- Document 6.9 (fibonacci.htm) Calculate Fibonacci numbers

Calculate the nth Fibonacci number

Enter n (a positive integer): (Press Tab to get nth Fibonacci number.)
-------------------------- Document 6.10 (towers.htm) --------------------------- Document 6.11a (passID.htm) Get ID and password.
ID: PW:
---------------------------- Document 6.11b (catchID.htm) Receive ID and password from another document.
------------------------- Document 6.12 (sort2.htm) Sorting Arrays ---------------------------- Document 6.13 (dewpoint.htm) Dewpoint Calculator

Dewpoint Temperature Calculator


Temperature: °C
Relative Humidity: %



Dewpoint Temperature: °C

------------------------ Document 6.14 (loan.htm) Loan Calculator

Loan Calculator

Principal Amount: $:
Annual rate: %
Number of Months:

Monthly Payment: $
---------------------------- Document 6.15 (legendre.htm) Legendre Polynomials

Calculate the nth Legendre polynomial, Pn(x), for any x and n ≥ 0

n (≥ 0):
x:

Legendre polynomial:
----------------------------- Document 6.16 (buildMenu.htm) Build a variable-length pull-down menu
Here's the menu:
Click on an item to select it.

This is the item selected:
------------------------------------ Document 6.17a (passwordProtect.htm)

You will need a password to visit my site.

---------------------------- Document 6.17b (&_crazy.htm)

You have entered &_crazy.htm.

---------------------------- Document 7.1. (getCalib.htm) Get calibration constant

Get calibration constants for water vapor instrument

Enter serial number here:
---------------------------- Document 7.2. (getCalib.php) ".""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo "
QuantityValue
Instrument ID$SN
Calibration Constants
A$A
B$B
C$C
τ$tau
β$beta
"; } ?> ------------------------------ Document 7.3. (helloWorld.php) --------------------------- Document 7.4. (PHPInfo.php) ------------------------------------ (partial data file for Document 7.5) SN A B C beta tau WV2-113, 0.762, 0.468, 0.20, 0.65, 0.10 ------------------------------ Document 7.5. (writeCalib.php) Get calibrations for water vapor instrument "; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo "
QuantityValue
Instrument ID$SN
Calibration Constants
A$A
B$B
C$C
τ$tau
β$beta
"; } fprintf($out,"Data have been reported for: %s,%f,%f,%f,%f,%f\n",$SN,$A,$B,$C,$tau,$beta); fclose($out); ?> --------------------------- Document 7.6a (quadrat.htm) Solving the Quadratic Equation Enter coefficients for ax2 + bx + c = 0:
a = (must not be 0)
b =
c =

--------------------------- Document 7.6b (quadrat.php) --------------------------------- Document 7.7a (WeatherReport.htm) Weather Report

Report weather observations

Date (mm/dd/yyyy) :
Time (UT hh:mm:ss):
Air temperature (deg C):
Barometric pressure (millibar):
Cloud cover (octas 0-8):
Precipitation today (total mm):

--------------------------------- Document 7.7b (WeatherReport.php) " . "date:" . $date . "
" . "time: " . $time . "
" . "BP : " . $BP . "
" . "octas: " . $octas . "
" . "precip: " . $precip . "
"; $out=fopen("WeatherReport.csv","a"); fprintf($out,"%s, %s, %.1f, %.2f, %u, %.2f\r\n", $date,$time,$T,$BP,$octas,$precip); fclose($out); ?> -------------------------- Document 8.1 (PWcalc2.htm) WV calculations for calibrated instrument

Calculations for Total Precipitable Water Vapor (PW)

Location:
longitude (decimal degrees): latitude (decimal degrees):
Calibration constants:
A (you must provide a value), B, and C:
β and τ:
Date:
mm/dd/yyyy
Time:
hh:mm:ss (must be Universal Time)
Station pressure (mbar, not currently used in calculation):
Instrument voltages:
IR1 IR1dark
IR2 IR2dark

Relative air mass:
Overhead precipitable water vapor (cm H2O):

--------------------------- Document 8.2a (PWcalc3.htm) WV calculations for calibrated instrument

Calculations for Total Precipitable Water Vapor (PW)

Location:
longitude (decimal degrees): latitude (decimal degrees):
Instrument Serial Number:
Date:
mm/dd/yyyy
Time:
hh:mm:ss (must be Universal Time)
Station pressure (mbar, not currently used in calculation):
Instrument voltages:
IR1 IR1dark
IR2 IR2dark
--------------------------- Document 8.2b (PWcalc3.php) WV calculations for calibrated instrument 0. -floor(3*(floor(($y+4900+$temp)/100))/4); $JD =$JD-0.5+$hour/24+$minute/1440+$second/86400; return $JD; } function getSunpos($m,$d,$y,$hour,$minute,$second,$Lat,$Lon) { // Retrieve Julian date $JD=getJD($m,$d,$y,$hour,$minute,$second); // Solar position, ecliptic coordinates $dr=pi()/180; $T=($JD-2451545)/36525; $L0=280.46645+36000.76983*$T+0.0003032*$T*$T; $M=357.52910+35999.05030*$T-0.0001559*$T*$T-0.00000048*$T*$T*$T; $M_rad=$M*$dr; $e=0.016708617-0.000042037*$T-0.0000001236*$T*$T; $C=(1.914600-0.004817*$T-0.000014*$T*$T)*sin($M_rad) +(0.019993-0.000101*$T)*sin(2.*$M_rad)+0.000290*sin(3.*$M_rad); // Replacement code for L_true=fmod(L0+c,360) $L_save=($L0+$C)/360; if ($L_save < 0) $L_true=($L0+$C)-ceil($L_save)*360; else $L_true=($L0+$C)-floor($L_save)*360; if ($L_true < 0) $L_true+=360; $f=$M_rad+$C*$dr; $R =1.000001018*(1-$e*$e)/(1.+$e*cos($f)); // Sidereal time $Sidereal_time=280.46061837+360.98564736629*($JD-2451545.)+0.0003879*$T*$T-$T*$T*$T/38710000; // Replacement code for Sidereal=fmod(Sidereal,360) $S_save=$Sidereal_time/360.; if ($S_save < 0.) $Sidereal_time=$Sidereal_time-ceil($S_save)*360; else $Sidereal_time=$Sidereal_time-floor($S_save)*360; if ($Sidereal_time < 0.) $Sidereal_time+=360; // Obliquity $obliquity=23+26/60+21.448/3600-46.8150/3600*$T-0.00059/3600*$T*$T +0.001813/3600*$T*$T*$T; // Ecliptic to equatorial $right_Ascension = atan2(sin($L_true*$dr)*cos($obliquity*$dr),cos($L_true*$dr)); $declination = asin(sin($obliquity*$dr)*sin($L_true*$dr)); $Hour_Angle = $Sidereal_time + $Lon - $right_Ascension/$dr; $elev=asin(sin($Lat*$dr)*sin($declination)+cos($Lat*$dr)*cos($declination)*cos($Hour_Angle*$dr)); /* relative air mass from Andrew T. Young, Air mass and refraction (Eq. 5), Appl. Opt., 33, 6, 1108-1110 (1994) */ $cosz=cos(pi()/2-$elev); // echo $cosz; $airm=(1.002432*$cosz*$cosz+0.148386*$cosz+0.0096467)/($cosz*$cosz*$cosz+ 0.149864*$cosz*$cosz+0.0102963*$cosz+0.000303978); return $airm; } ?> Calculations for Total Precipitable Water Vapor (PW)"; $m=getSunpos($_POST["mon"],$_POST["day"],$_POST["yr"],$_POST["hr"],$_POST["min"],$_POST["sec"], $_POST["lat"],$_POST["lon"]); $IR1=$_POST["IR1"]-$_POST["IR1_dark"]; $IR2=$_POST["IR2"]-$_POST["IR2_dark"]; $A=$_POST["A"]; $B=$_POST["B"]; $C=$_POST["C"]; $beta=$_POST["beta"]; $tau=$_POST["tau"]; $SN=$_POST["SN"]; $len=strlen($SN); // Open WV instrument calibration constant file… $inFile = "WVdata.dat"; $in = fopen($inFile, 'r') or die("Can't open file"); // Read one header line… $line=fgets($in); // Search rest of file for SN match… $found=1; while ((!feof($in)) && ($found == 1)) { $line=fgets($in); $values=sscanf($line,"%s %f %f %f %f %f\n"); list($SN_dat,$A,$B,$C,$beta,$tau)=$values; if (strncasecmp($SN_dat,$SN,$len)==0) { $found=0; } } fclose($in); // Build table of outputs… echo "

"; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo "
InputValue
Instrument SN$SN
Calibration Constants
A$A
B$B
C$C
τ$tau
β$beta
Measurements
IR1 (sunlight - dark)$IR1
IR2 (sunlight - dark)$IR2

"; $x = $C*$m*$tau - (log($IR2/$IR1)-$A)/$B; $PW = pow($x,1./$beta)/$m; echo "

"; echo ""; echo "
Output Value
relative air mass"; echo round($m,4); echo "
PW, cm H2O"; echo round($PW,4); echo "

"; ?> ------------------------------ Document 8.3 (circleStuff.php) ------------------------------------ (partial data file for Document 8.4) 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 … -------------------------- Document 8.4 (windspd.php) '; $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<24; $hr++) { // echo $hrly[$hr] . ', '; if ($hrly[$hr] == -1) $nMissing++; } // echo $hrly[23] . '
'; } echo 'Number of missing hours this month is ' . $nMissing .'.
'; fprintf($out,"%u, %u, %u\r\n",$m,$y,$nMissing); } echo "All done.
" // fclose($in); // fclose($out); ?> ----------------------------------- (density.dat file for Document 8.5) material density (kg/m^3) water 1000 aluminum 2700 gold 19300 silver 10500 oxygen 1.429 air 1.2 (volume.dat file for Document 8.5) shape volume cube $L*$L*$L sphere 4/3*M_PI*$R*$R*$R cylinder M_PI*$R*$R*$L block $L*$W*$H --------------------------- Document 8.5a (getMass.htm) Calculate mass
Enter length:
Enter width:
Enter height:
Enter radius:
--> />
--------------------------- Document 8.5b (getMass.php) " . $material . ", " . $shape . "
"; $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 . "
"; $found=true; } } // 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 . "
"; $found=true; } } // Close both data files. fclose($materialFile); fclose($shapeFile); // Calculate mass. $vv=$v . "*$d"; echo "Result: ".eval("return round($vv,3);")." kg
"; ?> --------------------------- Document 8.6 (bmp_info.php) "; $in=fopen($inFile,'r'); // Read header. $c=array(); for ($i=0; $i<14; $i++) { $c[$i]=ord(fgetc($in)); echo $c[$i]." "; } echo "
"; // Calculate file size. $size=$c[5]*16777216+$c[4]*65536+$c[3]*256+$c[2]; echo "File size = ".$size." bytes.
"; // Find offset to start of image. $offset=$c[10]; echo "Offset to start of image = ".$offset."
"; // Read image information record. for ($i=0; $i<40; $i++) { $c[$i]=ord(fgetc($in)); echo $c[$i]." "; } echo "
"; // Get # of rows and columns. $cols=$c[7]*16777216+$c[6]*65536+$c[5]*256+$c[4]; $rows=$c[11]*16777216+$c[10]*65536+$c[9]*256+$c[8]; echo "This image has ".$rows." rows and ".$cols." columns.
"; // Get some other information. $nPlanes=$c[13]*256+$c[12]; echo "# of color planes = ".$nPlanes."
"; $bitsPerPixel=$c[15]*256+$c[14]; echo "Bits per pixel = ".$bitsPerPixel."
"; $compressionType=$c[19]*16777216+$c[18]*65536+$c[17]*256+$c[16]; echo "Compression type = ".$compressionType."
"; $imageSize=$c[23]*16777216+$c[22]*65536+$c[21]*256+$c[20]; echo "Image size = ".$imageSize."
"; $Xresolution=$c[27]*16777216+$c[26]*65536+$c[25]*256+$c[24]; echo "X-resolution = ".$Xresolution."
"; $Yresolution=$c[31]*16777216+$c[30]*65536+$c[29]*256+$c[28]; echo "Y-resolution = ".$Yresolution."
"; $nColors=$c[35]*16777216+$c[34]*65536+$c[33]*256+$c[32]; echo "number of colors = ".$nColors."
"; $importantColors=$c[39]*16777216+$c[38]*65536+$c[37]*256+$c[36]; echo "important colors = ".$importantColors."
"; // Close the file. fclose($in); ?> --------------------------- Document 8.7 (bmp_read.php) "; $in=fopen($inFile,'r'); // Read header. $ch=array(); for ($i=0; $i<14; $i++) { $ch[$i]=ord(fgetc($in)); echo $ch[$i]." "; } echo "
"; //$offset=$ch[10]; for ($i=0; $i<40; $i++) { $ch[$i]=ord(fgetc($in)); echo $ch[$i]." "; } echo "
"; $cols=$ch[5]*256+$ch[4]; $bytes=3*$cols; // Each row is padded to contain a multiple of 4 bytes. $nPad=4-$bytes%4; echo "# of pad bytes = ".$nPad."
"; $rows=$ch[9]*256+$ch[8]; echo "rows and columns: ".$rows." ".$cols."
"; // Read image. for ($r=1; $r<=$rows; $r++) { for ($c=1; $c<=$cols; $c++) { for ($i=0; $i<=2; $i++) { $ch[$i]=fgetc($in); echo ord($ch[$i]); } echo " "; } // Read pad bytes at end of line. for ($p=1; $p<=$nPad; $p++) { $pad=fgetc($in); echo "pad"; } echo "
"; } fclose($in); ?> -------------------------------- Document 8.8 (bmp_grayscale.php) "; $in=fopen($inFile,'r'); $out=fopen($outFile,'w'); // Read header. $ch=array(); for ($i=0; $i<14; $i++) { //$ch[$i]=ord(fgetc($in)); //echo $ch[$i]." "; //fwrite($out,chr($ch[$i]),1); fwrite($out,fgetc($in)); } echo "
"; //$offset=$ch[10]; for ($i=0; $i<40; $i++) { $ch[$i]=ord(fgetc($in)); echo $ch[$i]." "; fwrite($out,chr($ch[$i]),1); } echo "
"; $cols=$ch[5]*256+$ch[4]; $bytes=3*$cols; $nPad=4-$bytes%4; // Each row padded to contain a multiple of 4 bytes. echo "# of pad bytes = ".$nPad."
"; $rows=$ch[9]*256+$ch[8]; echo "rows and columns: ".$rows." ".$cols."
"; // Read image. for ($r=1; $r<=$rows; $r++) { for ($c=1; $c<=$cols; $c++) { for ($i=0; $i<=2; $i++) { $ch[$i]=fgetc($in); } $avg=(ord($ch[0])+ord($ch[1])+ord($ch[2]))/3; fwrite($out,chr($avg),1); fwrite($out,chr($avg),1); fwrite($out,chr($avg),1); } // Read pad bytes at end of line. for ($p=1; $p<=$nPad; $p++) { $pad=fgetc($in); fwrite($out,$pad); } } fclose($in); fclose($out); echo "A grayscale file has been created.
"; ?> ------------------------------- Document 8.9 (bmp_hidetext.php) "; $in=fopen($inFile,'r'); $out=fopen($outFile,'w'); $hiddenText="Please don't eat me!"; $startRow=9; // Read header. $ch=array(); for ($i=0; $i<14; $i++) { $ch[$i]=ord(fgetc($in)); echo $ch[$i]." "; // Write starting row for text here, in unused byte. if ($i==6) fwrite($out,chr($startRow),1); else fwrite($out,chr($ch[$i]),1); } echo "
"; //$offset=$ch[10]; for ($i=0; $i<40; $i++) { $ch[$i]=ord(fgetc($in)); echo $ch[$i]." "; fwrite($out,chr($ch[$i]),1); } echo "
"; $cols=$ch[7]*16777216+$ch[6]*65536+$ch[5]*256+$ch[4]; $bytes=3*$cols; $nPad=4-$bytes%4; // Each row padded to contain a multiple of 4 bytes. echo "# of pad bytes = ".$nPad."
"; $rows=$ch[11]*16777216+$ch[10]*65536+$ch[9]*256+$ch[8]; echo "rows and columns: ".$rows." ".$cols."
"; // Read image. $K=strlen($hiddenText); $knt=0; for ($r=1; $r<=$rows; $r++) { for ($c=1; $c<=$cols; $c++) { for ($i=0; $i<=2; $i++) { $ch[$i]=fgetc($in); } $avg=(ord($ch[0])+ord($ch[1])+ord($ch[2]))/3; fwrite($out,chr($avg),1); fwrite($out,chr($avg),1); fwrite($out,chr($avg),1); } // Read pad bytes at end of line. for ($p=1; $p<=$nPad; $p++) { $pad=fgetc($in); if (($r>=$startRow) && ($knt<$K)) { // Write text into pad bytes. fwrite($out,substr($hiddenText,$knt,1),1); $knt++; } else fwrite($out,$pad,1); } } fclose($in); fclose($out); echo "A grayscale file has been created.
"; ?> ---------------------------------- Document 8.10 (TransformImage.php) ------------------------------------ Document 8.11 (CompoundInterest.php) Calculate Compound Interest

Calculate Compound Interest

Initial amount (no commas), $:
Annual interest rate, %:
How many years?:
"; for ($i=1; $i<=$years; $i++) { $amount=$initial*pow(1+$rate/100,$i); echo $i." ".number_format($amount,2)."
"; } ?> ----------------------------- Document 9.1 (keyedArray.php) A keyed array:
'; $stuff = array('mine' => 'BMW', 'yours' => 'Lexus', 'ours' => 'house'); foreach ($stuff as $key => $val) { echo '$stuff[' . $key . '] = '. $val . '
'; } ?> -------------------------------------- Document 9.2 (ConsecutiveKeyArray.php) "; for ($i=0; $i'; echo "Using implied keys with foreach... loop
"; foreach ($a as $i => $x) echo 'a[' . $i . '] = ' . $x . '
'; echo "An array with keys starting at an integer other than 0
"; $negKey = array(-1 => 'BMW', 'Lexus', 'house'); for ($i=-1; $i<2; $i++) echo $negKey[$i] . '
'; echo 'A keyed array with consecutive character keys...
'; $stuff = array('a' => 'BMW', 'b' => 'Lexus', 'c' => 'house'); for ($i='a'; $i<='c'; $i++) echo $stuff[$i] . '
'; ?> ------------------------------ Document 9.3 (base_1Array.php) A keyed array with indices starting at 1...
'; $a = array(1 => 63.7, 77.5, 17, -3); foreach($a as $key => $val) { echo 'a[' . $key . '] = '. $val . '
'; } for ($i=1; $i<=sizeof($a); $i++) echo $a[$i] . '
'; ?> ------------------------ Document 9.4 (two-D.php) A 2-D array
'; $a = array( 0 => array(1,2,3,4), 1 => array(5,6,7,8), 2 => array(9,10,11,12), 3 => array(13,14,15,16), 4 => array(17,18,19,20) ); $n_r=count($a); echo '# rows = ' . $n_r . '
'; $n_c=count($a[0]); echo '# columns = ' . $n_c . '
'; for ($r=0; $r<$n_r; $r++) { for ($c=0; $c<$n_c; $c++) echo $a[$r][$c] . ' '; echo '
'; } ?> ------------------------ Document 9.5 (sort1.php) '; for ($i=0; $i'; sort($a); echo 'Sorted array:
'; for ($i=0; $i'; ?> ------------------------ Document 9.6 (sort2.php) '; ?> ------------------------ Document 9.7 (sort3.php) '; for ($i=0; $i'; echo 'Sorted array with user-defined comparisons of elements:
'; usort($a,"compare"); for ($i=0; $i'; ?> ---------------------------------- Document 9.8 (StacksAndQueues.php) Stacks and Queues "; print_r($a); // Add two elements to $a… array_push($a,"Susan",0.5); echo "
Push two elements on top of stack:
"; print_r($a); // Remove three elements from $a… array_pop($a); array_pop($a); array_pop($a); echo "
Remove three elements from top of stack:
"; print_r($a); // Treat $a like a queue (first in, first out)… $a = array(-17,"David", 33.3,"Laura"); echo "
Back to original array:
"; print_r($a); echo "
Remove two elements from front of queue:
"; array_shift($a); array_shift($a); print_r($a); echo "
Add three elements to end of queue:
"; array_push($a,"Susan",0.5,"new_guy"); print_r($a); echo "
Add a \"line crasher\" to the beginning of the queue:
"; array_unshift($a,"queue_crasher_guy"); print_r($a); ?> ---------------------------- Document 9.9a (quadrat2.htm) Solving the Quadratic Equation
Enter coefficients for ax2 + bx + c = 0:
a = (must not be 0)
b =
c =

---------------------------- Document 9.9b (quadrat2.php) "; $coefficientArray=array_keys($_POST["coeff"]); $a = $_POST["coeff"][$coefficientArray[0]]; $b = $_POST["coeff"][$coefficientArray[1]]; $c = $_POST["coeff"][$coefficientArray[2]]; $d = $b*$b - 4.*$a*$c; if ($d == 0) { $r1 = $b/(2.*$a); $r2 = "undefined"; } else if ($d < 0) { $r1 = "undefined"; $r2 = "undefined"; } else { $r1 = (-$b + sqrt($b*$b - 4.*$a*$c))/2./$a;; $r2 = (-$b - sqrt($b*$b - 4.*$a*$c))/2./$a;; } echo "r1 = " . $r1 . ", r2 = " . $r2; ?> ----------------------------- Document 9.10a (quadrat3.htm) Solving the Quadratic Equation
Enter coefficients for ax2 + bx + c = 0:
a = (must not be 0)
b =
c =

----------------------------- Document 9.10b (quadrat3.php) "; $coefficientArray=$_POST["coeff"]; $a = $coefficientArray[0]; $b = $coefficientArray[1]; $c = $coefficientArray[2]; $d = $b*$b - 4.*$a*$c; if ($d == 0) { $r1 = $b/(2.*$a); $r2 = "undefined"; } else if ($d < 0) { $r1 = "undefined"; $r2 = "undefined"; } else { $r1 = (-$b + sqrt($b*$b - 4.*$a*$c))/2./$a;; $r2 = (-$b - sqrt($b*$b - 4.*$a*$c))/2./$a;; } echo "r1 = " . $r1 . ", r2 = " . $r2; ?> ----------------------------- Document 9.11a (CloudObs.htm) Cloud Observations

Cloud Observations

Cloud Observations (Select as many cloud types as observed.)
High Cirrus Cirrocumulus Cirrostratus

Middle Altostratus Altocumulus

Low Stratus Stratocumulus Cumulus

Rain-Producing Nimbostratus Cumulonimbus
----------------------------- Document 9.11b (CloudObs.php) "; for ($i=0; $i<$n; $i++) echo $high[$i] . "
"; $mid = $_POST["mid"]; $n = count($mid); echo "For mid clouds, you observed
"; for ($i=0; $i<$n; $i++) echo $mid[$i] . "
"; $low = $_POST["low"]; $n = count($low); echo "For low clouds, you observed
"; for ($i=0; $i<$n; $i++) echo $low[$i] . "
"; $rain = $_POST["rain"]; $n = count($rain); echo "For precipitating clouds, you observed
"; for ($i=0; $i<$n; $i++) echo $rain[$i] . "
"; ?> ------------------------- Document 9.12 (histo.php) "; $h=array(); // echo "Number of boxes = ".$n_boxes."
"; for ($i=0; $i<$n_boxes; $i++) { array_push($h,0); // echo $h[$i]."
"; } echo "size of histogram array = ".sizeof($h)."
"; for ($n=0; $n"; $sum+=$h[$i]; } echo "# of entries = ".$sum."
"; } $in=fopen("histo.dat","r"); $a=array(); $i=0; while (!feof($in)) { fscanf($in,"%f", $s); $a[$i]=$s; $i++; // array_push($a,$s); will also work. // echo 'a['.$i.'] = '.$a[$i].'
'; } /* Alternative code… $i=0; while (!feof($in)) { fscanf($in,"%f",$a[$i]); $i++; } */ echo 'Number of scores: '.sizeof($a).'
'; buildHisto($a,0,100,10); fclose($in); ?> ------------------------------- Document 9.13 (cardShuffle.php) "; for ($i=0; $i<52; $i++) { $j=rand(0,51); $save=$deck[$i]; $deck[$i]=$deck[$j]; $deck[$j]=$save; } for ($i=0; $i<52; $i++) echo $deck[$i]." "; echo "
"; sort($deck); echo "Resort deck...
"; for ($i=0; $i<52; $i++) echo $deck[$i]." "; echo "
----------------------------- (data file for Document 9.14) Date Value 01/15/2006 17.3 01/20/2006 0.55 05/17/2006 83.9 09/09/2006 9.33 11/13/2006 15 01/01/2007 74.4 02/28/2007 64.4 05/05/2007 100 06/06/2007 64.4 12/12/2007 22.54 ------------------------------- Document 9.14a (DataReport.htm) Data Management Application
Date (mm/dd/yyyy format):
Value (number):
find date:       find value:       insert new report in chronological order:       view all reports:
------------------------------- Document 9.14b (DataReport.php) "; $in=fopen($fileName,"r"); $line=fgets($in); // read header echo $line."
"; switch($choose) { case "view_all": while (!feof($in)) { fscanf($in,"%s %f",$date,$x); echo $date." ".$x."
"; } break; case "find_date": $found=false; while (!feof($in) && (!$found)) { fscanf($in,"%s %f",$date,$x); if (strtotime($date)==strtotime($new_date)) { echo $date." ".$x."
"; $found=true; } } if (!$found) echo "This record not found.
"; break; case "find_value": $found=false; while (!feof($in)) { fscanf($in,"%s %f",$date,$x); if ($x==$new_value) { echo $date." ".$x."
"; $found=true; } } if (!$found) echo "This record not found.
"; break; case "insert": $temp=array(); $i=0; $added=false; $duplicate=false; // copy data into array while (!feof($in)) { fscanf($in,"%s %f",$date,$x); if ((strtotime($date)==strtotime($new_date)) && ($x==$new_value)) $duplicate=true; if ((strtotime($date)>strtotime($new_date)) && (!$added) && (!$duplicate)) { // insert new record $temp[$i][0]=$new_date; $temp[$i][1]=$new_value; $added=true; $i++; } $temp[$i][0]=$date; $temp[$i][1]=$x; $i++; } if (strtotime($new_date)>strtotime($temp[$i-1][0])) { $temp[$i][0]=$new_date; $temp[$i][1]=$new_value; } echo "new array...
"; for ($i=0; $i"; } if ($duplicate) echo "Duplicate record, not added.
"; break; } fclose($in); ?> --------------------------------- Document 9.15 (InsertionSort.php) =$a[$last]) $a[$last+1]=$element; else if ($first<$last) { $a[$last+1]=$a[$last]; insertInOrder($element,$a,$first,$last-1); } else { $a[$last+1]=$a[$last]; $a[$last]=$element; } } $x=array(7,3,4,13,544,-17,-1,0); $x=insertionSort($x,0,7); var_dump($x); ?> ---------------------------------------- Document 10.1 (conditionalExecution.php) "; $discriminant=0.3; if ($discriminant < 0.) echo "There are no real roots.
"; elseif ($discriminant == 0.) { echo "There is one real root.
"; $r1 = -$b/$a/2; echo $r1; } else { echo "There are two real roots.
"; list($r1,$r2) = getRoots($a,$b,$c); echo "
Print the roots here..."; } ?> ------------------------------- Document 10.2 (daysInMonth.php) "; break; case 4: case 6: case 9: case 11: echo "There are 30 days in this month.
"; break; case 2: echo "There are either 28 or 29 days in this month.
"; break; default: echo "I do not understand your month entry."; } ?> ----------------------------- Document 10.3 (countdown.php) =0; $i--) echo $i . "
"; echo "FIRE!
"; ?> -------------------------------- Document 10.4 (loopExamples.php) "; for ($i=0; $i<=sizeof($a); $i++) echo $a[$i] . '
'; $a = array(1 => 17,2 => -13.3, 3 => "stringThing", 4 => "PHP"); foreach ($a as $k => $x) echo "a[" . $k . "] = " . $x . "
"; $b = array(77, 33, 4); foreach($b as $x) { echo("$x" . "
"); } ?> --------------------------- Document 10.5 (foreach.php) "; $a = array(1 => 17,2 => -13.3, 3 => "stringThing", 4 => "PHP"); foreach ($a as $k => $x) echo "a[" . $k . "] = " . $x . "
"; ?> --------------------------- Document 10.6 (squares.php) '; } while ($x*$x < 100.); ?> ----------------------------- (data file for Document 10.7) 01/14/2007 17:33:01 02/28/2007 09:15:00 ---------------------------- Document 10.7 (dateTime.php) ",$day,$month,$year,$hour,$min,$sec); } ?> --------------------------------- Document 10.8 (formatExample.php)
%s
%e
%f
",$a,$b,$b); printf("
%d %u
",$a,$a); printf("
%d %u
",$c,$c); // note effect of %u! printf("
He said, \"Let's go!\"
"); printf("
Your discount is \$%'012.2f
",$d); printf("
%'x26s
",$e); ?> -------------------------------- Document 10.9 (arrayDisplay.php) %s",$result); vprintf("
%s, %f, %s, %u, %s",$a); $result = sprintf("
%s, %f, %s, %um %s", $a[0],$a[1],$a[2],$a[3],$a[4]); echo '
' . $result; ?> ------------------------------------ Document 10.10 (stringFunctions.php) "; echo substr_compare($str1,$str2,8) . "
"; echo strpos($str1,"wor") . "
"; echo stristr($str1,"wor") . "
"; ?> ----------------------------- Document 10.11 (arrayPop.php) ------------------------------ Document 10.12 (arrayPush.php) %u
",$n); print_r($stack); printf("
%u
",sizeof($stack)); ?> ------------------------------- Document 10.13 (arrayShift.php) ' . $rottenFruit; echo '
' . count($queue); ?> --------------------------------- Document 10.14 (arrayUnshift.php) ' . count($a) . '
'; print_r($a); ?> ------------------------------------- Document 10.15 (SortingFunctions.php) "; var_dump($x); sort($x,SORT_STRING); echo "
sort as string
"; var_dump($x); usort($x,"compare"); echo "
normal sort, descending order
"; var_dump($x); $a=array('mine' => 'BMW','hers' => 'Lexus', 'ours' => 'House'); sort($a); echo "
sort keyed array
"; var_dump($a); echo "
but the keys haven't been retained:
"; foreach($a as $key => $val) echo '$a[' . $key . '] = '. $val . '
'; $a=array('mine' => 'BMW','hers' => 'Lexus', 'ours' => 'House'); asort($a); echo "use asort() to retain the keys
"; foreach($a as $key => $val) echo '$a[' . $key . '] = '. $val . '
'; arsort($a); echo "use ursort() to sort keyed array in reverse order
"; foreach($a as $key => $val) echo '$a[' . $key . '] = '. $val . '
'; ksort($a); echo "use ksort() to sort by key rather than by value
"; foreach($a as $key => $val) echo '$a[' . $key . '] = '. $val . '
'; krsort($a); echo "use krsort() to sort array in reverse order by key
"; foreach($a as $key => $val) echo '$a[' . $key . '] = '. $val . '
'; ?> ------------------------------ "; for ($i=1; $i"; } foreach ($a as $s) { list($site,$Lat,$Lon)=explode(" ",$s); echo $site.", ".$Lat.", ".$Lon."
"; } ?> ---------------------------- Document 10.17 (varDump.php) ------------------------------ Document 10.18 (arrayList.php) "; list($who, , $to_what) = $stuff; echo "$who $to_what
"; $a = array('david','apple','Xena','Sue'); $b = array(); list($b[0],$b[1],$b[2],$b[3]) = $a; var_dump($b); echo "
Access with for... loop.
"; for ($i=0; $i"; echo "Access with foreach... loop.
"; foreach ($b as $key => $x) echo "a[" . $key . "] = " . $x . "
"; ?> -------- CLI 11.1 C:\PHP>php hello.php Hello, world! C:\PHP> -------- CLI 11.2 C:\PHP>php pdf_1.php –.5 .5 Array ( [0] => pdf_1.php [1] => -.5 [2] => .5 ) ------------------------- Document 11.1 (pdf_1.php) -------- CLI 11.3 C:\PHP>php pdf_1.php –.5 .5 Array ( [0] => pdf_1.php [1] => -.5 [2] => .5 ) 0.38292418907776 C:\PHP> ------------------------- Document 11.2 (pdf_2.php) -------- CLI 11.4 C:\PHP>php pdf_2.php Give lower and upper limits for evaluating pdf, separated by a space: -3 3 -3, 3 0.99729820978444 -------------------------- Document 11.3a (pdf_3.htm) Integrate the normal probability density function

Evaluate the normal probability density function

x1:
x2:
-------------------------- Document 11.3b (pdf_3.php) 0) { $a = $_SERVER['argv']; print_r($a); $x1=$a[1]; $x2=$a[2]; } else { $x1=$_POST['x1']; $x2=$_POST['x2']; echo $x1 . ", " . $x2 . "
"; } $n=200; $sum=0; $dx=($x2-$x1)/$n; for ($i=1; $i<=$n; $i++) { $x=$x1+($i-1)*$dx; $y1=exp(-$x*$x/2)/sqrt(2.*M_PI); $x=$x1+$i*$dx; $y2=exp(-$x*$x/2)/sqrt(2.*M_PI); $sum+=$y1+$y2; } echo $sum*$dx/2.; ?> ------------------------------ Document 12.1 (ImageSpace.php) -------------------------- Document 12.2a ( pie1.php) ------------------------- Document 12.2b (pie2.php) ------------------------- Document 12.2c (pie3.php) 0) $start[$i] = $end[$i-1]; $end[$i] = $start[$i] + $slice; } // Display title ImageString($im,5,$x_title,$y_title,$TitleString,$black); // draw filled arcs for ($i=0; $i<$n; $i++) { ImageFilledArc($im,$x0,$y0,$dia,$dia,$start[$i],$end[$i], $PieColor[$i],IMG_ARC_PIE); } // Display legend for ($i=0; $i<$n; $i++) { ImageFilledRectangle($im,$x0_legend, $y0_legend+$dy_legend*$i,$x0_legend+$legend_size, $y0_legend+$dy_legend*$i+$legend_size,$PieColor[$i]); ImageString($im,5,$x0_legend+$legend_size+5, $y0_legend+$dy_legend*$i+5,$legends[$i],$black); } // Display and release allocated resources. ImageGIF($im); ImageDestroy($im); ?> ------------------------------ (data file for Document 12.3a) Quarterly Sales 17.7 January-March 15 April-June 19.2 July-September 30 October-December --------------------------------- Document 12.3a (pieChartTest.htm)

----------------------------- Document 12.3b (pieChart.php) 0) $start[$i]=$end[$i-1]; $end[$i]=$start[$i]+$slice; } // Display title ImageString($im,5,$x_title,$y_title,$TitleString,$black); // draw filled arcs for ($i=0; $i<$n; $i++) { ImageFilledArc($im,$x0,$y0,$dia,$dia,$start[$i],$end[$i], $PieColor[$i],IMG_ARC_PIE); } // Display legend for ($i=0; $i<$n; $i++) { ImageFilledRectangle($im,$x0_legend, $y0_legend+$dy_legend*$i,$x0_legend+$legend_size, $y0_legend+$dy_legend*$i+$legend_size,$PieColor[$i]); ImageString($im,5,$x0_legend+$legend_size+5, $y0_legend+$dy_legend*$i+5,$legends[$i],$black); } // Display and release allocated resources. ImageGIF($im); ImageDestroy($im); } // MAIN PROGRAM ----------------------- $inFile=$_POST["fileName"]; //$inFile="pieChart.dat"; $in=fopen($inFile,"r") or exit("Can't open this file."); $A=array(); $legends=array(); // rtrim() removes line feeds, etc. from end of string $Title=rtrim(fgets($in)); $i=-1; while (!feof($in)) { $i++; fscanf($in,"%f %s",$A[$i],$legends[$i]); $A[$i]=round($A[$i],0); } fclose($in); generatePie($Title,$A,$legends); ?> -------------------------- Document 12.4a (Hbar1.php) odd number of values $x_labels = array("-2.5","-2.0","-1.5","-1.0","-0.5", "0.0","+0.5","+1.0","+1.5","+2.0","+2.5"); $y_labels = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep", "Oct","Nov","Dec"); $x_values = array(1.3,0.9,-0.2,-0.5,1,0,-2.5, -.5,.6,.2,.7,2.3); $n_x = count($x_labels); // number of x labels $n_y = count($y_labels); // number of y labels $xvalue_max = 2.5; // define image space $x_max = 800; $y_max = 500; // starting coordinates for title $x0_title = 10; $y0_title = 10; // space between x-axis labels $dx = 50; // space between horizontal bars $dy = 30; // y-tic size $y_tic = 10; // bar height $bar_height = 25; // label offsets $xlabel_offset = 40; $ylabel_offset = 80; $xaxis_xoffset = 0; $xaxis_yoffset = 20; $x0 = 100; $y0 = 60; // starting coordinates for of x-axis // create and color image space background $im = imageCreate ($x_max, $y_max) or die ("Cannot Initialize new GD image stream"); $background_color = ImageColorAllocate($im,234,234,234); // define colors $text_color = ImageColorAllocate($im,0,0,0); // text color $line_color = ImageColorAllocate($im,0,0,0); // line color $title_font_size = 5; // large font for title // black text for title $title_color = ImageColorAllocate($im,0,0,0); // draw chart title ImageString($im,$title_font_size,$x0_title,$y0_title, $chartTitle,$title_color); // draw x-axis ImageLine($im,$x0,$y0,$x0+$dx*($n_x-1),$y0,$line_color); // draw x labels for ($i=0; $i<$n_x; $i++) { ImageString($im,$title_font_size,$x0+$xaxis_xoffset+$i*$dx, $y0-$xaxis_yoffset,$x_labels[$i],$text_color); ImageLine($im,$x0+$xaxis_xoffset+$i*$dx,$y0, $x0+$xaxis_xoffset+$i*$dx,$y0+$y_tic,$line_color); } // draw y labels for ($i=0; $i<$n_y; $i++) { ImageString($im,$title_font_size,$xlabel_offset, $ylabel_offset+$i*$dy,$y_labels[$i],$text_color); } // Create GIF image. ImageGIF($im); // Release allocated resources. ImageDestroy($im); ?> -------------------------- Document 12.4b (Hbar2.php) odd number of values $x_labels = array("-2.5","-2.0","-1.5","-1.0", "-0.5","0","+0.5","+1.0","+1.5","+2.0","+2.5"); $y_labels = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep", "Oct","Nov","Dec"); $x_values = array(1.3,0.9,-0.2,-2.5,1,0,-1.1, -.5,.6,2.2,.7,.3); $n_x = count($x_labels); // number of x labels $n_y = count($y_labels); // number of y labels $xvalue_max = 2.5; // define image space $x_max = 800; $y_max = 500; // starting coordinates for title $x0_title = 10; $y0_title = 10; // space between x-axis labels $dx = 50; // space between horizontal bars $dy = 30; // y-tic size $y_tic = $dy*($n_y+1); // bar height $bar_height = 25; // label offsets $xlabel_offset = 40; $ylabel_offset = 80; $xaxis_xoffset = 0; $xaxis_yoffset = 20; $x0 = 100; $y0 = 60; // starting coordinates for of x-axis // location of vertical 0-axis $x0axis_offset = $x0 + $dx*floor($n_x/2); $x_length = 100; // create and color image space background $im = imageCreate ($x_max, $y_max) or die ("Cannot Initialize new GD image stream"); $background_color = ImageColorAllocate($im,234,234,234); // define colors // text color $text_color = ImageColorAllocate($im,0,0,0); // line color $line_color = ImageColorAllocate($im,0,0,0); // negative bar color $negative = ImageColorAllocate($im,0,0,255); // positive bar color $positive = ImageColorAllocate($im,255,0,0); // large font for title $title_font_size = 5; // black text for title $title_color = ImageColorAllocate($im,0,0,0); // draw chart title ImageString($im,$title_font_size,$x0_title,$y0_title, $chartTitle,$title_color); // draw x-axis ImageLine($im,$x0,$y0,$x0+$dx*($n_x-1),$y0,$line_color); // draw x labels for ($i=0; $i<$n_x; $i++) { ImageString($im,$title_font_size,$x0+$xaxis_xoffset+$i*$dx, $y0-$xaxis_yoffset,$x_labels[$i],$text_color); ImageLine($im,$x0+$xaxis_xoffset+$i*$dx,$y0, $x0+$xaxis_xoffset+$i*$dx,$y0+$y_tic,$line_color); } // draw y labels and bars for ($i=0; $i<$n_y; $i++) { $x_scaled = ImageString($im,$title_font_size,$xlabel_offset, $ylabel_offset+$i*$dy,$y_labels[$i],$text_color); } // draw bars for ($i=0; $i<$n_y; $i++) { $x_scaled = $x_values[$i]/$xvalue_max*$dx*floor($n_x/2); $color = $negative; if ($x_scaled >= 0) $color = $positive; ImageFilledRectangle($im,$x0axis_offset, $ylabel_offset+$i*$dy,$x0axis_offset+$x_scaled, $ylabel_offset+$i*$dy+$bar_height,$color); } // draw vertical 0-axis ImageLine($im,$x0axis_offset,$y0,$x0axis_offset, $y0+$dy*$n_y+$dy,$line_color); // draw line across bottom ImageLine($im,$x0,$y0+$dy*$n_y+$dy,$x0+$dx*($n_x-1), $y0+$dy*$n_y+$dy,$line_color); // Create GIF image. ImageGIF($im); // Release allocated resources. ImageDestroy($im); ?> ---------------------------------- Document 12.5a (HbarChartTest.htm)

Create a horizontal bar chart

Chart title (text):
Data arrays (values separated by one space):
Minimum values:
Maximum values:
Minimum data value:
Maximum data value:
X-axis labels (string values separate by one space):
Bar labels (string values separated by one space):
Bar height (pixels):
Vertical space between bars (pixels):


------------------------------ Document 12.5b (HbarChart.php) = 0) $color = $positive; ImageFilledRectangle($im,$x0 + $xmin_scaled, $ylabel_offset + $i*$dy,$x0 + $xmax_scaled, $ylabel_offset + $i*$dy + $bar_height,$color); } // draw vertical 0-axis // ImageLine($im,$x0axis_offset,$y0,$x0axis_offset,$y0+$dy*$n_y+$dy,$line_color); // draw line across bottom ImageLine($im,$x0,$y0+$dy*$n_y+$dy, $x0+$dx*($n_x-1),$y0+$dy*$n_y+$dy,$line_color); // Create GIF image. //ImageGIF($im,"HbarChart.gif"); ImageGIF($im); // Release allocated ressources. ImageDestroy($im); } // MAIN PROGRAM ------------------------------------ $Title = $_POST["Title"]; $A_min = $_POST["A_min"]; $A_max = $_POST["A_max"]; $X = $_POST["X"]; $Y = $_POST["Y"]; $BarHeight = $_POST["BarHeight"]; $dy = $_POST["dy"]; HorizontalBarChart($Title,$A_min,$A_max,$X,$Y,$BarHeight, $dy); ?> -------------------------- Document 12.6a (Vbar1.php) -------------------------- Document 12.6b (Vbar2.php) 0) ImageString($im,2,$x,$y,$x_labels[$i],$label_color); ImageLine($im,$x0+$i*$y_gap,$y0,$x0+$i*$y_gap, $y0-($n_y-1)*$y_gap,$grid_color); } // draw y-axis labels and horizontal grid $black=ImageColorAllocate($im,0,0,0); // define a black and transparent dashed line for grid lines $style = array( $black,$black,$black,$black,$black, IMG_COLOR_TRANSPARENT,IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT,IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT ); ImageSetStyle($im,$style); for ($i=0; $i<$n_y; $i++) { // next two lines right-justify the y-axis labels $ylabel=$ylabel_mask . $y_labels[$i]; $ylabel=substr($ylabel,strlen($ylabel)-$ylabel_length); $x=$x0+$ylabel_xoffset; $y=$y0+$ylabel_yoffset-$i*$y_gap; ImageString($im,2,$x,$y,$ylabel,$label_color); ImageLine($im,$x0,$y0-$i*$x_gap,$x0+$n_x*$x_gap, $y0-$i*$y_gap,IMG_COLOR_STYLED); } // Draw axis titles. ImageString($im,$title_font_size,$x0+$xtitle_xoffset, $y0+$xtitle_yoffset,$x_title,$label_color); ImageStringUp($im,$title_font_size,$x0+$ytitle_xoffset, $y0+$ytitle_yoffset,$y_title,$label_color); // Create GIF image. ImageGIF($im); // Release allocated resources. ImageDestroy($im); ?> -------------------------- Document 12.6c (Vbar3.php) 0) ImageString($im,2,$x,$y,$x_labels[$i],$label_color); ImageLine($im,$x0+$i*$x_gap,$y0,$x0+$i*$x_gap, $y0-($n_y-1)*$y_gap,$grid_color); } // draw y-axis labels and horizontal grid $black=ImageColorAllocate($im,0,0,0); // define a black and transparent dashed line for grid lines $style = array( $black,$black,$black,$black,$black, IMG_COLOR_TRANSPARENT,IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT,IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT ); ImageSetStyle($im,$style); for ($i=0; $i<$n_y; $i++) { // next two lines right-justify the y-axis labels $ylabel=$ylabel_mask . $y_labels[$i]; $ylabel=substr($ylabel,strlen($ylabel)-$ylabel_length); $x=$x0+$ylabel_xoffset; $y=$y0+$ylabel_yoffset-$i*$y_gap; ImageString($im,2,$x,$y,$ylabel,$label_color); ImageLine($im,$x0,$y0-$i*$y_gap,$x0+$n_x*$x_gap, $y0-$i*$y_gap,IMG_COLOR_STYLED); } // Draw axis titles. ImageString($im,$title_font_size,$x0+$xtitle_xoffset, $y0+$xtitle_yoffset,$x_title,$label_color); ImageStringUp($im,$title_font_size,$x0+$ytitle_xoffset, $y0+$ytitle_yoffset,$y_title,$label_color); // Draw bars. $y_range=$y_gap*($n_y-1); $ymin=0; $ymax=100; for ($i=0; $i<$n_x; $i++) { ImageFilledRectangle($im,$x0+$bar_offset+$x_gap*$i,$y0,$x0+$bar_offset+$bar_width+$x_gap*$i, $y0-($Y[$i]-$ymin)/($ymax-$ymin)*$y_range,$bar_color); } // Create GIF image. ImageGIF($im); // Release allocated resources. ImageDestroy($im); ?> ---------------------------------- Document 12.7a (VbarChartTest.htm) Vbar chart interface

Create vertical bar chart

Data file name:
Chart title:
X-axis title:
Y-axis title:
Number of bars:
Minimum value:
Maximum value:
Y-axis labels:
X-label space (pixels)
Bar width (% of x-label space):
Bar color (RRR,GGG,BBB):
Offset for x-axis title (pixels):
Offset for y-axis title (pixels):


------------------------------ Document 12.7b (VbarChart.php) "; $title=$_POST["title"]; $xTitle=$_POST["xTitle"]; $yTitle=$_POST["yTitle"]; $nBars=$_POST["nBars"]; $yMin=$_POST["min"]; $yMax=$_POST["max"]; $xWidth=$_POST["xWidth"]; $yLabels=explode(",",$_POST["yLabels"]); $barWidth=$_POST["barWidth"]; $barColor=$_POST["barColor"]; $xTitleOffset=$_POST["xTitleOffset"]; $yTitleOffset=$_POST["yTitleOffset"]; $in=fopen($FileName,"r"); $xLabels=array(); $Y_lo=array(); $Y_hi=array(); $i=0; while (!feof($in)) { fscanf($in,"%s %f %f",$xLabels[$i],$Y_lo[$i],$Y_hi[$i]); //echo $xLabels[$i]." ".$Y_lo[$i]." ".$Y_hi[$i]."
"; $i++; } fclose($in); drawChart($title,$barColor,$barWidth,$xWidth,$nBars, $xTitle,$yTitle,$xTitleOffset,$yTitleOffset,$yMin, $yMax,$xLabels,$yLabels,$Y_lo,$Y_hi); ?> ---------------------------------- (data file for vertical bar chart) CO 10 15 O3_1 15 30 O3_8 0 0 SO2 50 100 NO2 2 25 PM_10 50 70 PM_2.5 80 95 -------------------------- Document 12.8a (line1.php) ---------------------------------- (partial data file for Document 12.8) DRB Worcester, PA 40.178 -75.3325 4030 mon day yr hr min sec EST V 6 1 2008 0 0 0 1 0.00031 6 1 2008 0 1 0 1.000694444 0.00031 6 1 2008 0 2 0 1.001388889 0.00031 6 1 2008 0 3 0 1.002083333 0.00031 6 1 2008 0 4 0 1.002777778 0.00031 6 1 2008 0 5 0 1.003472222 0.00031 6 1 2008 0 6 0 1.004166667 0.00031 ------------------------ Document 12.8b line2.php ---------------------------------- Document 12.9a (lineGraphTest.htm) Line Graph

Draw a line graph

Chart title:
X-axis title:
Y-axis title:
Xmin:
Xmax:
Ymin:
Ymax:
X-axis labels:
Y-axis labels:
X-title offset (pixels):
Y-title offset (pixels):
Name of file containing X-Y values:
----------------------------------- (small test file for Document 12.9) 0.582 0.003 8.2398 0.681 0.003 7.0438 0.746 0.003 6.2972 0.799 0.003 5.6974 0.849 0.003 5.1569 0.896 0.003 4.7228 0.931 0.003 4.4054 0.962 0.003 4.1332 1.006 0.003 3.7906 1.037 0.003 3.5338 1.068 0.003 3.2936 1.091 0.003 3.0758 1.121 0.003 2.8257 1.158 0.003 2.6090 1.176 0.003 2.4870 1.203 0.003 2.3003 1.223 0.003 2.1956 1.24 0.003 2.1043 1.25 0.003 1.9784 1.272 0.003 1.8467 ------------------------------ Document 12.9b (lineGraph.php)