Spring 2012 - MATH 40A: Introduction to Programming for Internet

Humberto Naves

Email: hnavesatmath.ucla.edu
Office Location: MS 6160
Office hours: In the PIC Lab, Bolter Hall 2817
Class homepage:PIC 40A
My webpage: Humberto



Useful links Basic HTML
  1. Sample page
  2. Redirect
CSS
  1. Table
  2. Menu
  3. Project Page
  4. Home Page
Javascript
  1. Root calculator
  2. Table generator
  3. Expression calculator
  4. Notepad
PHP
  1. Notepad in PHP
    #!/usr/local/bin/php
    <?php
      session_save_path(realpath(dirname(__FILE__) . '/session'));
      session_start();
      if (isset($_GET['notes'])) {
        $_SESSION['notes'] = $_GET['notes'];
      }
    ?>
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8"/>
        <meta name="authors" content="Humberto Silva Naves"/>
        <meta name="description" content="Notepad Example"/>
        <meta name="keywords" content="PIC, Homework"/>
        <meta name="copyright" content="2012 Humberto Silva Naves"/>
        <title>Notepad</title>
        <style type="text/css">
          html, body, textarea {
            font-family: Lucida Console;
            letter-spacing: 2px;
            color: green;
            background-color: black;
          }
          #content {
            text-align: center;
            margin: 0px auto;
          }
          #notes {
            width: 600px;
          }
          #controls {
            width: 200px;
            margin: 0px auto;
            padding-left: 400px;
          }
          .control_button {
            width: 90px;
          }
        </style>
        <script type="text/javascript">
          function clearNotes() {
            var notesElement = document.getElementById("notes");
            notesElement.value = "";
            enableSaveButton(true);
          }
    
          function enableSaveButton(enable) {
            var saveButton = document.getElementById("save_button");
            saveButton.disabled = !enable;
          }
    
          function promptSave() {
            var saveButton = document.getElementById("save_button");
            if (saveButton.disabled == false) {
              return "You have unsaved changes";
            }
          }
          window.onbeforeunload = promptSave;
    
          function submitData() {
            enableSaveButton(false);
            document.forms["notes_form"].submit();
          }
        </script>
      </head>
      <body onload="enableSaveButton(false);">
        <div id="content">
          <h1>Type your notes here</h1>
          Session id: <?php echo session_id(); ?><br/>
          <form id="notes_form" action="notepad.php" method="GET">
            <textarea id="notes" name="notes" rows="16" onchange="enableSaveButton(true);"
             onkeyup="enableSaveButton(true);"><?php echo htmlspecialchars($_SESSION['notes']); ?></textarea>
            <br/><br/><div id="controls">
              <input id="save_button" class="control_button" type="submit" value="Save" onclick="submitData();"/>
              <input class="control_button" type="button" value="Clear" onclick="clearNotes();" />
            </div>
          </form>
        </div>
      </body>
    </html>
            
  2. Hangman
    #!/usr/local/bin/php
    
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8"/>
        <meta name="authors" content="Humberto Silva Naves"/>
        <meta name="description" content="Hangman Example"/>
        <meta name="keywords" content="PIC, Homework"/>
        <meta name="copyright" content="2012 Humberto Silva Naves"/>
        <title>Hangman</title>
        <style type="text/css">
          #main_div {
            margin: 0 auto;
            text-align: center;
          }
          .red {
            color: red;
          }
        </style>
      </head>
      <body>
        <div id="main_div">
    <?php
    
    # list of words to guess below.
    $list = array(
      "BALL",
      "CAR",
      "BACKPACK",
      "COMPUTER",
      "OFFICE",
      "BLACKBOARD",
      "LANDSCAPE",
      "SPECTRE",
      "THRONES",
      "EYEBROW",
      "HANDKERCHIEF",
      "SOLSTICE",
      "BREAKTHROUGH",
      "COOL",
      "TRYST",
      "DWELL",
      "VOLATILE",
      "PRIMITIVE",
      "COMPONENT"
    );
    
    $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    # ========= Code ==========
    
    if (isset($_GET["n"])) $n=$_GET["n"];
    if (isset($_GET["letters"])) $letters=$_GET["letters"];
    if (!isset($letters)) $letters = "";
    
    if (isset($PHP_SELF)) $self=$PHP_SELF;
    else $self=$_SERVER["PHP_SELF"];
    
    $links="";
    
    
    
    $max = 8;  # maximum number of wrong
    srand ((double)microtime() * 1000000);
    $wrong = 0;
    
    if (!isset($n)) {
      $n = rand(1,count($list)) - 1;
    }
    
    $word = trim($list[$n]);
    $done = 1;
    $word_line = "";
    for ($x = 0; $x < strlen($word); $x++) {
      if (strstr($letters, $word[$x])) {
        $word_line .= $word[$x];
      } else {
        $word_line .= "_";
        $done = 0;
      }
      $word_line .= " ";
    }
    
    if (!$done) {
      for ($c=0; $c < strlen($alpha); $c++) {
        if (strstr($letters, $alpha[$c])) {
          if (strstr($word, $alpha[$c])) {
            $links .= "\n<strong>$alpha[$c]</strong> ";
          } else {
            $links .= "\n<span class=\"red\">$alpha[$c]</span>";
            $wrong++;
          }
        } else {
          $links .= "\n<a href=\"$self?letters=$letters$alpha[$c]&n=$n\">$alpha[$c]</a> ";
        }
      }
      echo "\n<p><br /><img src=\"hangman$wrong.gif\" /></p>\n";
    
      if ($wrong >= $max)
      {
        $n++; # next puzzle
        if ($n > (count($list) - 1)) $n = 0;
        echo "<br /><br /><h1>$word_line</h1>\n";
        echo "<p><br /><span class=\"red\">SORRY, YOU ARE HANGED!!!</span><br /><br />";
        echo "The word was \"<strong>$word</strong>\"<br /><br />\n";
        echo "<a href=\"$self?n=$n\">Play again.</a></p>\n\n";
      }
      else
      {
        echo "# Wrong Guesses Left: <strong>".($max-$wrong)."</strong><br />\n";
        echo "<h1>$word_line</h1>\n";
        echo "<p><br />Choose a letter:<br /><br />\n";
        echo "$links\n";
        echo "</p>\n";
      }
    }
    else
    {
      $n++;	 # next puzzle
      if ($n > (count($list) - 1)) $n = 0;
      echo "\n<p><br />\n<img src=\"hangwon.gif\"  />\n";
      echo "<br /><br /><h1><font size=\"5\">\n$word_line</font></h1>\n";
      echo "<p><br /><br /><strong>Congratulations!!!  You win!!!</strong><br /><br /><br />\n";
      echo "<a href=\"$self?n=$n\">Play again</a>\n\n";
    }
    ?>
        </div>
      </body>
    </html>
            
  3. Where am I
    #!/usr/local/bin/php
    <?php
      function getClientIp() {
        if (!$ip = $_SERVER['HTTP_CLIENT_IP']) {
          if (!$ip = $_SERVER['HTTP_X_FORWARDED_FOR']) {
            if (!$ip = $_SERVER['REMOTE_ADDR']) {
              $ip = '';
            }
          }
        }
        return $ip;
      }
    
      function curlGetJSON($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
    
        $returnValue = curl_exec($ch);
        curl_close($ch);
    
        return json_decode($returnValue);
      }
    
      function getIpOrgInfo($ip) {
        $ipResult = curlGetJSON('http://whois.arin.net/rest/ip/' . $ip);
        $orgResult = curlGetJSON('http://whois.arin.net/rest/org/' . $ipResult->net->orgRef->{'@handle'});
        $city = $orgResult->org->city->{'$'};
        $country = $orgResult->org->{'iso3166-1'}->name->{'$'};
        $organization = $orgResult->org->name->{'$'};
        $zip = $orgResult->org->postalCode->{'$'};
        $state = $orgResult->org->{'iso3166-2'}->{'$'};
        $addr = $orgResult->org->streetAddress->line;
        if (is_array($addr)) {
          $address = "";
          for ($i = 0; $i < count($addr); $i++) {
            $address .= $addr[$i]->{'$'} . "\n";
          }
        } else {
          $address = $addr->{'$'};
        }
    
        return array (
          "organization" => $organization,
          "country" => $country,
          "state" => $state,
          "city" => $city,
          "address" => $address,
          "zip" => $zip
        );
      }
    
      if (isset($_GET['ip'])) {
        $ip = $_GET['ip'];
      } else {
        $ip = getClientIp();
      }
      #$ip = '131.179.212.111';
      #$ip = '74.125.159.147';
    
    
      $orgInfo = getIpOrgInfo($ip);
      $fullAddress = $orgInfo["address"];
      $fullAddress .= ", " . $orgInfo['city'];
      $fullAddress .= ", " . $orgInfo['state'];
      $fullAddress .= ", " . $orgInfo['zip'];
      header ("Location: http://maps.google.com/maps?q=" . urlencode($fullAddress));
    ?>
            
  4. Prime numbers