DBI Chapter 9: PHP

Outline

  • Hyper Text Preprocessor
  • Variables and types
  • Operators
  • Selection and loop statements
  • Array
  • Functions and variables scopes
  • Cookies and Sessions

HyperText Preprocessor (PHP)

  • An open-source, server-side, HTML-embedded scripting language uses for form handling and database access.
  • Syntax is similar to JavaScript.
  • Variables are dynamic typing i.e. the type of a variable is set every time it it assigned a value.
  • PHP scripts are either embedded in markup documents or are in files that are referenced by such documents.

Embeded PHP

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Test</title>
    </head>
    <body>
        <?php echo "<p>Hello World</p>"; ?>
    </body>
</html>

Referenced PHP

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Test</title>
    </head>
    <body>
        <?php include($_SERVER["DOCUMENT_ROOT"]."/basic_php.php"); ?>
<!--different ways-->
        <?php include("C:\\xampp\\htdocs\\test\\basic_php.php" ); ?>
    </body>
</html>

in basic_php.php

<?php echo '<p>Hello World</p>'; ?>

Variable Name

  • begin with a dollar sign ($), followed by a letter or an underscore followed by any number of letters, digits or underscore.
  • Variable names are case sensitive.
  • BUT reserved words or function name are not!

Variable Types

  • Four scalar types: Boolean, integer, double, and string.
  • No need to declare a variable, and type of a variable is set every time the variable is assigned a value.
<?php 
    $txt = "Hi";
    $x = 5;
    $y = 10.5;
    echo "<p>My variables and values: txt = $txt, x = $x, y = $y</p>"; 
?>
<!--My variables and values: txt = Hi, x = 5, y = 10.5-->

Integer and Double Overflow

  • Size is platform e.g. 32 bits or 64 bits.
<?php 
    $x = 9223372036854775807;

    echo "<p> " . $x . "</p>";

    $x = $x + 1;
    echo "<p> " . $x . "</p>";

    echo "<p> " . PHP_INT_MAX . "</p>";
    echo "<p> " . PHP_FLOAT_MAX . "</p>";
    /* only version 7.2 and above */

?>
<!--
9223372036854775807
9.2233720368548E+18
9223372036854775807
1.7976931348623E+308
-->
image.png

Interesting Facts about Types

  • double : there need not be any digits before before or after the decimal point so .345 or 345. are legal.
  • String :
    • Single quotes stop interpolation i.e. substitution.
    • Length is limited by the memory available on the computer.
  • Boolean:
    • zero, 0.0, empty string, and string "0" are false.
    • This implies string "0.0" is true.
<?php 
    $txt = "Hi\n";
    $n = 5;
    echo "<p> " . $txt . "</p>";

    $txt = 'Hi\n';
    echo "<p> " . $txt . "</p>";

    $txt = "Hi\n";
    echo "<p> $txt </p>";
    echo '<p> $txt </p>';
    echo "<p> \$txt </p>";
    /* like is \ is used as escape sequence */
?>
<!--
Hi
Hi\n
Hi
$txt
$txt
-->

Unassigned Variable: NULL

  • An unassigned variable i.e. unbound variable, has the value NULL.
  • NULL is coerced to a value depending on the context of use, e.g. 0 if number, empty string if string.
<?php 
    $txt = "Hi";
    $x = 5;
    $y = 10.5;
    $e;         
    $b = false;

    echo $x + $e + $y; 
    /* here $e is treated as zero */

    echo "<p> $txt" . $e . "$txt</p>"; 
    /* here $e is treated as empty string */

    echo "<p>" . ($e ? "true" : "false") . "</p>";
    /* false if it is empty string or string 0, otherwise true */

    $a = IsSet($e);
    /* IsSet check if $e has been assigned a value */
    echo $a ? "true" : "false"; 

    echo "<p>" . (($b == $e) ? "true" : "false") . "</p>";
?>
<!--
Notice: Undefined variable: e in C:\xampp\htdocs\test\basic_php.php on line 64
15.5
Notice: Undefined variable: e in C:\xampp\htdocs\test\basic_php.php on line 67
HiHi

Notice: Undefined variable: e in C:\xampp\htdocs\test\basic_php.php on line 70
false
false
Notice: Undefined variable: e in C:\xampp\htdocs\test\basic_php.php on line 77
true
-->
  • Empty string or string "0" is false, otherwise is true.
  • IsSet($var) can be used to check if a value has been assigned to the variable.

Arithmetic Operators

  • Arithmetic operators have the usual meanings, but ** is exponential.
    3/2 => 1.5 float(auto)
    mod % => using integer (auto) => integer
<?php 
    $txt = "Hi";
    $x = 5;
    $y = 10.5;
    $b = true;
    $e;
    echo "<p>My variables and values: txt = $txt, x = $x, 
        y = $y, b = $b </p>"; 
    /*My variables and values: txt = Hi, x = 5, y = 10.5, b = 1 */
    echo "<p>x + y = $x + $y</p>";
    /*x + y = 5 + 10.5 */
    echo "<p>x + y = ";
    echo $x + $y;
    echo "</p>";
    /*x + y = 15.5*/
    echo "<p>x + y = " . ($x + $y) . "</p>";
    /*x + y = 15.5 */
    echo "<p>x + y = " . $x + $y . "</p>";
    /* no brackets ... bad idea!! */
    /*10.5 */       
    unset($y);
    echo "<p>x + y = " . ($x + $y) . "</p>";
    /*Undefined variable: y */
    /* x + y = 5*/
?>
Arithmetic operators

String Operations

  • Use . to catenate, .= to append.
  • String can be treated like array by using { ... }.
String operators

Type Conersions

  • Implicit conversions using coercions e.g. double to integer for modulus -> fractional part is dropped.
  • Explicit conversions: using type casting, intval or doubleval or strval, and settype.
  • Type checking :
    • is _int, int_integer, is_long
    • is_double, is_float, is_real
    • is_bool, is_string, is_array, is_object
<?php 
    $txt = "Hello world!";
    echo $txt{6}.$txt{4}.$txt{6}; //wow

    $txt = "1.5";
    $n = 1.234;
    echo "<p>" . ($n + $txt) . "</p>";  //2.734
    /* string coerced into double */

    $txt = "h1e5";
    $n = 1.234;
    echo "<p>" . ($n + $txt) . "</p>"; //1.234
    /* string that does not begin with a sign or a digit, 
    conversion fails, and zero is used */

    $txt = "1e5h"; //100000
    $n = 1.234;
    echo "<p>" . ($n + $txt) . "</p>"; //100001.234
    /* non numeric characters following the number in the string
    are ignored */

    echo "<p>" . (int)$n . "</p>"; //1
    echo "<p>" . intval($n) . "</p>"; //1
    echo "<p>" . gettype($n) . "</p>"; //double
    echo "<p>" . settype($n, "integer") . "</p>"; //1
    echo "<p>" . gettype($n) . "</p>"; //integer
?>

Print and echo

  • print is similar to echo, but print has a return value of 1 and echo can take multiple parameters.
    echo "This ", "string ", "was ", "made ", "with multiple parameters."
  • print can be used with or without parentheses.
    print (47);print expects string, so this has no error due to coercion.
    print "some apples are red <br/> No Kumquats are <br/>";

printf

  • display formatted output.
  • Examples of format specifiers : %s, %d, %f
    printf(liternal_string, param1, param2,...)
    %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.
$day = "Tuesday";
$high = 79;
printf("The high on %7s was %3d", $day, $high);

Relational Operators

  • >, <, >=, <=, !=, ==, ===
    "3" == 3true "3"===3false
  • If a string is compared with a number and the string can be converted to a number, then the string will be converted to a number.
    • If the string cannot be converted, then the number will be converted to a string.
  • If both operands are strings that can be converted to numbers, both will be converted and numeric comparison will be done.
    • If this is not desired, using strcmp.

Boolean Operators

  • There are 6 Boolean operators:
    and, or, xor, !, &&, and ||
  • and and or do the same job as && and || but has a lower precedence.

Selection Statements

  • Switch: control and case expressions can be integer, double, or string.

Loop statements

  • To terminate execution of a loop use break.
  • To skip the remainder of the current iteration use continue.

Example: HTML, CSS and PHP

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Table</title>
        <style type = "text/css">
                td, th, table {
                border: thin solid black;
            }
                tr {
                text-align: center;
            }
            </style>
    </head>
    <body>
        <table>
            <caption> Powers table </caption>
                <tr>
                    <th> Number </th>
                    <th> Square Root </th>
                    <th> Square </th>
                    <th> Cube </th>
                    <th> Quad </th>
            </tr>
            <?php 
                for ($number = 1; $number <=10; $number++) 
                {
                        $root = sqrt($number);
                        $square = pow($number, 2);
                        $cube = pow($number, 3);
                        $quad = pow($number, 4);

                        print("<tr> <td> $number </td>");
                        print("<td> $root </td> <td> $square </td>");
                        print("<td> $cube </td> <td> $quad </td> </tr>");
                }
            ?>
        </table>
    </body>
</html>

Table

Array

  • Elements of an array do not need to be of the same type.

  • Creating an array by assigning values:
    $list[0] = 17;
    $list[1] = "Today is my birthday!"
    $list[] = 42; The key for this element is 2.

  • Creating an array using **array ** construct:

//traditional array
$list = array(17, 24, 45, 91);
// Non-traditional array with different keys.
//key =>value
$list = array(1 => 17, 2 => 24, 3 => 42, 4 =>91);
$ages = array("Joe" => 42, "Mary" => 41, "Bif" => 17);
$stuff = array("make" => "Cessna", "model" => "C210", "year" => 1960, 3 =>"sold");

Assigning Values to Array

  • The list construct can be used to assign multiple elements of an array to scalar variables in one statement.
<?php 
    $ages = array("Joe" => 42, "Mary" => 41, "Bif" => 17);

    foreach($ages as $temp)
    {
        print("$temp <br />");
    }
/*
42
41
17
*/
    $ages["Mary"] = 29;

    foreach($ages as $temp)
    {
        print("$temp <br />");
    }
/*
42
29
17
*/
    $primes = array(7, 9, 11);

    $a = 1;
    $b = 2;
    $c = 3;
            
    echo "$a $b $c <br />"; // 1 2 3

    list($a, $b, $c) = $primes;// only traditional array will work
    print("$a $b $c <br />"); //7 9 11

    list($a, $b, $c) = $ages;
    print("$a $b $c <br />");
    /* does not work for non traditional array 
          nothing  will comming up */ 

?>

Functions that Deal with Array

<?php 
    $primes = array(7, 9, 11, 13);
    foreach($primes as $temp)
    {
        print("$temp <br />");
    }
/*
7
9
11
13
*/
    $k = array_keys($primes);
    $v = array_values($primes);
    $l = sizeof($primes);

    print "<p> keys </p>";
    foreach($k as $temp)
    {
        print("$temp <br />");
    }
/*
0
1
2
3
*/
    print "<p> values </p>";
    foreach($v as $temp)
    {
        print("$temp <br />");
    }
/*
7
9
11
13
*/          
    print "<p> $l </p>"; //size of  => 4

    if(array_key_exists(2, $primes))
    {
        print "<p> Exist </p>";
    }
    else
    {
        print "<p> Not exist </p>";
    }
//Exist

    print "<p> unset element #2 </p>";
    unset($primes[2]);
// Not exist            
    if(array_key_exists(2, $primes))
    {
        print "<p> Exist </p>";
    }
    else
    {
        print "<p> Not exist </p>";
    }

    $k = array_keys($primes);
    $v = array_values($primes);
    $l = sizeof($primes);

    print "<p> $l </p>"; // 3

    foreach($primes as $temp)
    {
        print("$temp <br />");
    }
/*
7
9
13
*/
    print "<p> keys </p>";
    foreach($k as $temp)
    {
        print("$temp <br />");
    }
/*
0
1
3
*/

    print "<p> values </p>";
    foreach($v as $temp)
    {
        print("$temp <br />");
    }
/*
7
9
13
*/
?>

Functions that Deal with Array(2)

<?php 
    $str = "Are you ready for this?";
    $word = explode(" ", $str); // split the words out of string
    foreach($word as $temp)
    {
        print("$temp <br />");
    }

    $word = array("Not", "really");
    $str = implode(" ", $word); // put it in a string
    print "$str <br />";
/*
Are
you
ready
for
this?
Not really
*/          
?>

current - Array's Internal Pointer

  • When current points at the last element of the array, next returns false.
  • current is a pointer points to current position.
  • Obviously, if your array store false values, the loop iterations will stop when the value of current is false.
$cities = array("Hoboken", "Chicago", "Moab", "Atlantis");
$city = current($cities);
/*in the beginning at the time. current will point to the first element.*/
print("The first city is $city <br />");
while ($city = next($cities))
/*move the pointer to the next */
  print("$city <br />");

each and current Functions

  • The each function returns a two-element array consisting of the key and the value of the current element.
  • each returns the element being referenced by the current pointer and then moves that pointer.
  • next first moves the current pointer and then returns the value being referenced.
$salaries = array("Mike"=>42500, "Jerry" => 51250, "Fred" =>37920);

while ($employee = each($salaries)){
  $name = $employee["key"];
  $salary = $employee["value"];
  print("The salary of $name is $salary <br />");
}
/*
The salary of Mike is 42500.
The salary of Jerry is 51250.
The salary of Fred is 37920.
*/

prev, reset and end Funcitons

$people = array("Peter", "Joe", "Glenn", "Cleveland");

echo current($people) .  "<br />"; //Peter
echo next($people) . "<br />"; //Joe
echo current($people) . "<br / >"; //Joe
echo prev($people) . "<br />"; //Peter
echo end($people) . "<br />"; //Cleveland
echo prev($people) . "<br />"; //Glenn
echo current($people) . "<br / >"; //Glenn
echo reset($people) . "<br />"; //Peter
echo next($people) . "<br />"; //Joe

Implementing Stack

  • array_push add one or more elements.
  • array_pop deletes last element, returns the element or return null if array is empty.
$a = array("red", "green");
array_push($a, "blue", "yellow");
print_r($a);
/*red green blue yellow*/
$a = array("red", "green", "blue");
b = array_pop ($a); //b = "blue"
print_r($a);
// red green

foreach

  • In foreach, the current pointer is implicitly initialized with reset i.e. the first element.
foreach($list as $temp)
  print("$stemp <br />")
  • You can also get key and value from the array using:
$lows = array("Mon" => 23, "Tue" => 18,"Wed" => 27);
foreach ($lows as $day => $temp)
  print("The low temperature on $day was $temp <br />");

Sorting Array

  • If an array has both string and numeric values, the string values migrate to the beginning in alphabetical order, and then the numeric values follow in ascending order.
  • sort: replace keys with 0, 1, 2
  • asort: keep the original key-value associations.
  • ksort: sort by keys, and maintain key-value associations.
  • rsort, arsort, krsort :sort in reverse order.
<!DOCTYPE html>
<html lang = "en">
    <head>
        <title> Sorting </title>
        <meta charset = "utf-8" />
    </head>
    <body>
        <?php
            $original = array("Fred" => 31, "Al" => 27, "Gandalf" => "wizard",  "Betty" => 42, "Frodo" => "hobbit");
        ?>
        <h4> Original Array </h4>
        <?php
            foreach ($original as $key => $value)
            {
                print("[$key] => $value <br />");
            }
            $new = $original;
            sort($new);
        ?>
<!--
Original Array
[Fred] => 31
[Al] => 27
[Gandalf] => wizard
[Betty] => 42
[Frodo] => hobbit
-->
        <h4> Array sorted with sort </h4>
        <?php
            foreach ($new as $key => $value)
            {
                print("[$key] = $value <br />");
            }
            $new = $original;
            asort($new);
        ?>
<!--
Array sorted with sort
[0] = hobbit
[1] = wizard
[2] = 27
[3] = 31
[4] = 42
-->
        <h4> Array sorted with asort </h4>
        <?php
            foreach ($new as $key => $value)
            {
                print("[$key] = $value <br />");
            }
            $new = $original;
            ksort($new);
        ?>
<!--
Array sorted with asort
[Frodo] = hobbit
[Gandalf] = wizard
[Al] = 27
[Fred] = 31
[Betty] = 42
-->
        <h4> Array sorted with ksort </h4>
        <?php
            foreach ($new as $key => $value)
            {
                print("[$key] = $value <br />");
            }
        ?>
<!--
Array sorted with ksort
[Al] = 27
[Betty] = 42
[Fred] = 31
[Frodo] = hobbit
[Gandalf] = wizard
-->
    </body>
</html>

Functions

  • Parameters are optional.
  • Function's definition need not appear before the function is called.
  • Function overloading is not allowed.
  • Function cannot be redefined.
  • Function names are not case sensitive.
  • return returns a value to the caller (no return means no values is returned.)
  • You can pass by value as well as pass by reference.
  • the number of actual parameters does not need to match the number of formal parameters.
function foo(&$var) //"&" pass by reference , formal parameters
{
  $var++;
}

$a = 5;
foo($a); // actual parameters
// $a is 6 here.

global and static Variables

  • Without global, $bigsum outside of the function is hidden.
global and static
  • static will only initial one time.

preg_match amd preg_split

  • preg_match returns true if pattern exists.
  • preg_split returns an array but operates on string.
if (preg_match ("/^PHP/", $str))
  print "\$str begins with PHP <br />";
else
  print "\$str does not begin with PHP <br />";

$fruit_string = "apple : orange : banana";
$fruits = preg_split("/ : /", $fruit_string);

Handling Forms

  • _POST and_GET can be used to get form values.
  • POST: pass with PHP script. (cannot see.)
  • GET: pass in the URL.(value can see from the URL)

POST

http://localhost:8081/test/mycal.php

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Post</title>
    </head>
    <body>
        <form action = "mycal.php" method = "post">
            <input type = "text" name = "one" size = "30" />
            <input type = "text" name = "two" size = "30" />
            <input type = "submit" value = "Calculate" />
                <input type = "reset" value = "Reset" />
        </form>
    </body>
</html>
<!--in mycal.php-->
<!DOCTYPE html>
<html>
    <head>
        <title>Post Process</title>
    </head>
    <body>
        <?php
            $one = $_POST["one"];
            $two = $_POST["two"];
            $sum = $one + $two;
            
            print "$one + $two = $sum <br />";
        ?>
    </body>
</html>

GET

http://localhost:8081/test/mycal.php?one=3&two=2

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Post</title>
    </head>
    <body>
        <form action = "mycal.php" method = “get”>
            <input type = "text" name = "one" size = "30" />
            <input type = "text" name = "two" size = "30" />
            <input type = "submit" value = "Calculate" />
                <input type = "reset" value = "Reset" />
        </form>
    </body>
</html>
<!--mycal.php-->
<!DOCTYPE html>
<html>
    <head>
        <title>Post Process</title>
    </head>
    <body>
        <?php
            $one = $_GET["one"];
            $two = $_GET["two"];
            $sum = $one + $two;
            
            print "$one + $two = $sum <br />";
        ?>
    </body>
</html>

Cookies

  • A session is the time span during which a browser interacts with a particular server.
  • A session beigins when a browser connects to the server and ends either when:
    • The browser is terminated, or
    • The server terminated the session because of client inactivity.
  • HTTP is stateless, i.e no means for storing information about a session that is available to a subsequent session.
  • Cookies used to identify each of the customer when visiting the website.
  • A cookie is created by the server and includes small informaiton such as name and textual value.
  • HTTP header can include one or more cookies.
  • A cookie is given a lifetime when cookie is created, and the cookie will be deleted from the browser when the lifetime is reached.

$_COOKIE and setcookie

  • setcookie takes one or more parameters: e.g. name, value, expiration time.
  • If value is absent, setcookie undefines the cookie.
  • A cookie MUST be created before any other HTML is created by the PHP document
<?php
  //set the expiration date to one hour ago
  setcookie("user", "", time() - 3600);
?>
<?php
  $cookie_name = "user";
  $cookie_value = "John Doe";
  setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //86400 = 1 day
// before any other HTML
?>

<html>
  <body>
    <?php
        if(!isset($_COOKIE[$cookie_name])){
          echo "Cookie named ' " . $cookie_name . " ' is not set!";
        } else {
          echo "Cookie ' " .  $cookie_name . " ' is set!";
          echo "Value is : " . $_COOKIE[$cookie_name];
        }    
    ?>
  </body>
</html>

$_SESSION

session

session 2

Conclusions

  • PHP has some similarities with C and JavaScript.
  • print, echo and printf can be used to display information on the browser.
  • array and it's pointers: current, prev, and next.
  • foreach loop.
  • _GET and_POST
  • _COOKIE and_SESSION.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容