Introduction to PHP by wuxiangyu


									   Introduction to PHP

To boldly go where JavaScript has
           never been…
              JavaScript vs. PHP

   JavaScript is a client-side language that resides
    in your browser. It is available for use with no
    effort on your part.
   PHP must be installed on a server (local or
    remote), and you must have specific permissions
    to access PHP applications.
   JavaScript cannot access any information
    outside an HTML document.
   PHP applications can access and create files
    stored elsewhere in a server.
    A typical server-side problem:
A user enters information about measurements taken with a
sun-viewing instrument (a sun photometer) that is used to
measure total column water vapor in the atmosphere.
The information provided by the user consists of the
instrument’s serial number, the location and time of the
measurements, and voltage outputs from the instrument.
The application must use this information to find the location
of the sun at the time and place of the measurement and
then calculate total column water vapor based on calibration
constants stored for the instrument used to collect the data.
The data file might look like this:

     SN A B C beta tau
     WV2-113 0.762 0.468 0.20 0.65 0.10
     WV2-114 0.814 0.468 0.20 0.650.10
     WV2-157 0.911 0.468 0.20 0.65 0.10
                The HTML document:
Document 1.1. (getCalib.htm)
<title>Get calibration constant</title>
<script language="javascript">
 document.write("This document last modified on "+document.lastModified+".")
<h2>Get calibration constants for water vapor instrument</h2>
<form method="post" action="getCalib.php">
Enter serial number here: <input type="text" name="SN" value="WV2-157" /><br />
<input type="submit" value="Click here to get calibration constants…" />
          Steps to using PHP

   1. Setting up a PHP environment.

1. Install a server on a computer (local or remote).
2. ownload and install a PHP interpreter.
3. Configure the server to recognize PHP documents and
   to locate the PHP interpreter.
             Steps to using PHP
    2. Creating, editing, and executing
    PHP documents.
1. PHP documents are text files that can be created with
any text editor. (A “real” code editor such as AceHTML is
2. Figure out where to store PHP documents. With the WAMP
server, they are stored in /wamp/www.
3. Create and edit PHP documents in an editor.
4. Execute the documents from your browser. With Windows
IIS the “URL” is localhost/{PHP file name}.
5. Make required changes in your editor and “refresh” the
application in your browser.
             Steps to using PHP
  3. Passing information from an HTML
  Document to a PHP application.
By design, this is very easy to do in PHP! The statement

<form method="post" action="getCalib.php">

Automatically passes all form field values to the PHP
document to a system-defined array called $_POST.
In the PHP document,


retrieves the instrument serial number passed from
Document 1.1.
         Looking for a match…
Document 1.2. (getCalib.php)
// Extract instrument ID from POST data…
// Open WV instrument calibration constant file…
  $inFile = "WVdata.dat";
  $in = fopen($inFile, "r") or exit("Can't open file");
// Read one header line…
// Search rest of file for SN match…
 while ((!feof($in)) && ($found == 0)) {
   $values=fscanf($in,"%s %f %f %f %f %f");
   if (strncasecmp($SN_dat,$SN,$len)==0) $found=1;
Several ways to read data from file…
 Read values from the file into an array, according to a specified format.
 Then assign the elements to named variables:
$values=fscanf($in,"%s %f %f %f %f %f");

 Read an entire line as a string and then read values from the string
 according to a specified format:

  list($SN_dat,$A,$B,$C,$beta,$tau)=sscanf($line,"%s %f %f %f %f %f");

  Read an entire line and assign named variables directly,
  according to a specified format:

   fscanf($in,"%s %f %f %f %f %f",$SN_dat,$A,$B,$C,$beta,$tau);
                   Processing the data…
 if ($found == 0)
    echo "Couldn't find this instrument.";
  else {
// Build table of outputs…
    echo "<p><table border='2'><tr><th>Quantity</th>
    echo "<tr><td>Instrument ID</td>
    echo "<tr bgcolor='silver'>

        <td colspan='2'>Calibration Constants</td>
         echo "<tr><td>A</td><td>$A</td></tr>";
         echo "<tr><td>B</td><td>$B</td></tr>";
         echo "<tr><td>C</td><td>$C</td></tr>";
         echo "<tr><td>&tau;</td><td>$tau</td></tr>";
         echo "<tr><td>&beta;</td><td>$beta</td></tr>";
         echo "</table>";
     Saving your results on a server…
$inFile = "WVdata.dat";
 $in = fopen($inFile, "r") or exit("Can't open file.");
"c:/Documents and Settings/All Users/Documents/PHPout/"

"Data have been reported for: %s,%f,%f,%f,%f,%f\n",
      Solving a quadratic equation
For the quadratic equation ax2 + bx + c = 0,
find the real roots:
r1 = [-b + (b2 – 4ac)1/2 ]/2a r2 = [-b - (b2 – 4ac)1/2 ]/2a
The “a” coefficient must not be 0. If the discriminant,
b2 – 4ac = 0, there is only one root.
If the discriminant is less than 0, there are no real roots.
Document 1.6a (quadrat.htm)

<title>Solving the Quadratic Equation</title>
<form method="post" action="quadrat.php">
Enter coefficients for ax<sup>2</sup> + bx + c = 0:
<br />
a = <input type="text" value="1" name="a" />
 (must not be 0)<br />
b = <input type="text" value="2" name="b" /><br />
c = <input type="text" value="-8" name="c" /><br /><br />
<input type="submit" value="click to get roots..." />
Document 1.6b (quadrat.php)

$a = $_POST["a"];
$b = $_POST["b"];
$c = $_POST["c"];
$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;
Preventing multiple form submissions
 Document 1.7a (WeatherReport.htm)
 <title>Weather Report</title>
 <script language="javascript" type="text/javascript" >
  var alreadySubmitted = false;
  function submitForm ( )
    if (alreadySubmitted)
      alert("Data already submitted. Click on 'Reset Button' and start over." );
      return false;
      alreadySubmitted = true;
      return true;
          Multiple submissions, part 2
   This code allows only one “submit,” after which you have to click the Reset button.
   Note that this is a JavaScript solution, but the problem often occurs when you are
   submitting data to a PHP application that appends to an existing file.
<h2>Report weather observations</h2>
<form method="post" action="WeatherReport.php"
 onSubmit="return submitForm(this.form);" >
 Date (mm/dd/yyyy) : <input type="text" name="date" value="09/23/2007" /><br />
 Time (UT hh:mm:ss): <input type="text" name="time" value="17:00:00" /><br />
 Air temperature (deg C):<input type="text" name="T" value="23" /><br />
 Barometric pressure (millibar): <input type="text" name="BP" value="1010" /><br />
 Cloud cover (octas 0-8): <input type="text" name="octas" value="7" /><br />
 Precipitation today (total mm): <input type="text" name="precip" value="2.3" /><br />
 <input type="submit" name="PushButton" value="Click to submit..." /><br />
<input type="reset" value="Reset Button"

To top