PHP

Upsorn Praphamontripong, Fall 2014 (based in part on class materials by Jeff Offutt)

This is a short introduction to get you start and experience with php. For more information, please refer to Sebesta book. The official website for PHP is http://www.php.net.

Overview

What is PHP (PHP Hypertext Preprocessor)?

  • PHP is a server-side scripting language
  • Scripts are embedded in HTML tags
  • Syntax looks similar to JavaScript (but runs on the server, no the client)
  • Dynamically typed
  • Interpreted language

What does PHP do?

  • Allow web developers to write dynamically generated pages quickly
  • Handle forms
  • Process files
  • Access databases

PHP syntax

Basic structure of PHP

PHP documents look like HTML with code inside, but it is not HTML and the PHP code itself will not render inside a browser.
                  <?php
                     ... php code (each statement ends with a semicolon) ...
                  ?>
                  

How to save your PHP pages

  • External PHP file
    • Write PHP code and save it as an external file (e.g., sample.php)
    •         <?php
                 ... php code ...
              ?>
              
    • Include it into an html file (e.g., index.html) by inserting <?php include('sample.php') ?> in the html file
  • Internal to the file
    • Write PHP code in <body> ... </body> of an html file (e.g., index.html)
              <body>
                ...
                <?php
                   ... php code ... 
                ?>
                ...
              </body>
              

Comments in PHP

Three syntax styles for comments
  • // this is a comment
  • # this is a comment
  • /* this is for
        multiple lines of comments */

Variables

  • Variable name begins with a $
  • variable names are case-sensitive
  • $variable_name = value;
  • Variables may be initialized without being declared

Arrays

  • Each array element consists of two parts: key and value (key may be integer or string)
  • To create an array
    • Use the assignment operation
      $states[0] = "Virginia";
      $states[] = "Georgia"; // implicit key = the array's current key + 1
      $capitals['VA'] = "Richmond";
      $matrix[7][11] = 2.718;
    • Use the array construct
      $list = array(17, 24, 30); // specify values without keys, PHP interpreter will furnish the numeric keys 0, 1, 2
      $agelist = array("Joe" => 17, "Mary" => 24, "Ann" => 30); // specify values with keys
  • To access array elements
    $list[2] = 34;
    $agelist['Mary'] = 44;

Functions and control structures

  • Some predefined functions that operate on numeric values
    • floor(0.60); // returns 0
    • ceil(0.60); // returns 1
    • round(0.60); // returns 1
    • rand(); // returns random number
      rand(10, 100); // returns random number between 10 and 100
    • abs(-6.7); // returns 6.7
    • min(2,8,6,4,10); // returns 2
      min(array(2,8,6,4,10)); // returns 2
    • max(2,8,6,4,10); // returns 10
      max(array(2,8,6,4,10)); // returns 10
  • Some predefined functions that operate on string values
    • strlen("Hello"); // returns 5
    • strcmp("Hello world!","Hello world!"); // returns 0 (two strings are equal)
    • strpos("Hello world!", "world"); // returns 6
    • substr("Hello world!", 6, 1); // returns w
    • chop("Hello world!","world!"); // returns Hello
    • trim(" Hello world! "); // returns Hello world!
  • User-defined functions
            function name([parameter]) {
               ...
            } 
            
  • Control statements
    • Selection statements
              if($num > 0)  
                $pos_count++; 
              elseif ($num < 0)
                $neg_count++; 
              else { 
                $zero_count++;
              } 
              
              $loop = 5;
              while (--$loop) {
                switch ($loop % 2) {
                  case 0: 
                    echo "Even<br />\n";
                    break;
                  case 1;
                    echo "Odd<br />\n";
                    break;
                }
              }
              
    • Loop statements
              $fact = 1;
              $count = 1;
              while($count < $n)  {  
                $count++;
                $fact *= $count;
              } 
              
              $count = 1;
              $sum = 0;
              do {  
                $sum += $count++;
                $count++;
              } while ($count <= 100);
              
              for ($count = 1, $fact = 1; $count < $n; $count++;)  
              {
                $fact *= $count;
              }
              

Output statements

  • echo $myVar;
  • print "Hello World!";
  • printf("Your total bill is %5.2f", $price);
    note: examples on formatting
    %10s — a character string field of 10 characters
    %6d — an integer field of six digits
    %5.2f — a float or double field of five spaces, with two digits to the right of the decimal point, the decimal point, and two digits to the left
  • String concatenation uses .
    print "Hello, ".$_POST['name'];

Handling data from the client

  • Often called form variable or form data
  • Store in implicit arrays
  • $_GET['form_input_name'] // The form data is sent with the HTTP GET method.
  • $_POST['form_input_name'] // The form data is sent with the HTTP POST method.
  • $_SERVER['PHP_SELF']; // PHP super global variable which holds information about headers, paths, and script locations.
    // Returns the filename of the currently executing script
        <?php
           if ( isSet($_POST['submit']) ) 
           {
             print "Hello, ".$_POST['name'];
           } 
           else  
           {           
        ?>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
          Your name: <input type="text" name="name"> <br />
          <input type="submit" name="submit">
        </form>
        <?php 
           }
        ?>
        

Reading and writing files

  • Open file: fopen(filename, mode)
  • Read file: fgets(file, length)
  • Write file: fputs(file, string, length)
        <?php
           $file = fopen("infilename.txt", "r");     // r: read only
           while ( !feof($file) ) {
             echo fgets($file), "<br />";
           }
        ?>
        
        <?php
           $file = fopen("outfilename.txt", "a");    // a: write only, append
           fputs($file, $HTTP_USER_AGENT."\n");
        ?>