rollDice3.php

Source of rollDice3.php

<?php
  session_start();
?>
<!DOCTYPE html>
<html lang = "en-US"> 

  <head>
    <meta charset = "UTF-8">
    <title>rollDice3.php</title>
  </head>
  <body>
    <h1>RollDice 3</h1>
    <h2>Uses a Session Variable</h2>
    <?php
function init(){
  global $count;
  global $total;
  //increment count if it exists
  if (isset($_SESSION["count"])){
    $count = $_SESSION["count"];
    $count++;
    $_SESSION["count"] = $count;
  } else {
    //if count doesn't exist, this is our first pass,
    //so initialize both session variables
    $_SESSION["count"] = 1;
    $_SESSION["total"] = 0;
    $count = 1;
  } // end if
} // end init
function rollDie(){
  global $total;
  $roll = rand(1,6);
  $image = "dado_$roll.png";
  print <<< HERE
    <img src = "$image"
         alt = "roll: $roll"
         height = "100px"
         width = "100px" />
HERE;
  $total = $_SESSION["total"];
  $total += $roll;
  $_SESSION["total"] = $total;
} // end rollDie
init();
rollDie();
print "    <p>Rolls: $count</p> \n";
print "    <p>Total: $total</p> \n";
    ?>
  </body>
</html>