22 February 2016

CST336 Week 8

Finals week! Final went well - quite challenging. The best part was the programming portion (almost half the grade and over 2/3 the total time). I was especially glad I paid attention to the SQL portion ;) . Since I like to post code, but don't think it's a good idea to post the final, here is what I got for lab 8. Note that the hardest part of this assignment was figuring out the permissions necessary to copy the file elsewhere in the filesystem. The assignment completed in class that used the database was much easier to implement.


<?php
/* STEP 2 *******************/
session_start();

 if (!isset ( $_SESSION['username']))  {
     if (isset ($_POST['loginForm'])) {
        require '../db_connection.php'; 
        $sql = "SELECT * 
                FROM lab9_user
                WHERE username = :username
                AND password = :password";
        $stmt = $dbConn -> prepare($sql);
        $stmt -> execute( array(":username" => $_POST['username'],
                                ":password" => sha1($_POST['password'])));
        $record = $stmt->fetch();
        if (!empty($record)) {
            $_SESSION['username'] = $record['username'];
            $_SESSION['profilePic'] = $record['profilePic'];
            echo "<h2> Welcome  " . $record['realName'] . "!</h2>";
            $location = "/var/www/johnlester.rocks/cst336/labs/lab8Images/" . $record['username'];
   $uold = umask(0);
   if (!file_exists($location)) {
    mkdir($location,0777,true);
    umask($uold);
      //mkdir("/var/www/johnlester.rocks/cst336/labs/lab8Images/" . $record['username'], 0777, true);
            }
        } else {
            $error = " Wrong username / password";
            header("Location: lab8.html");
        }
     }  
 }
 
 
/* STEP 3 *******************/
  if (isset($_FILES['fileName'])) {
     $_SESSION['profilePic'] = $_FILES['fileName']['name'];
     move_uploaded_file($_FILES['fileName']['tmp_name'], "lab8Images/" . $_SESSION['username'] . "/" . $_FILES['fileName']['name'] );
    //Syntax move_uploaded_file ( string $filename , string $destination )
  }
?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Profile</title>
  <link rel="shortcut icon" href="/favicon.ico">
</head>

<body id="wrapper">
  <div>
<?php
   if (empty($_SESSION['profilePic'])) {
           echo "<img class='profilepic' src='lab8Default.png'><br/>";
   } else {
            echo "<h2> Welcome  " . $_SESSION['realName'] . "!</h2>";           
           echo "<img class='profilepic' src='./lab8Images/" . $_SESSION['username'] . "/" . $_SESSION['profilePic'] . "'><br/>";
   }
?>
  
  </div>
  <!--- Step 1 ****************-->
  <div align="left" class="upload">
  <form method="post" enctype="multipart/form-data">
      <br/>
      
      Select File to update profile picture:
      <br />
      <input type="file" name="fileName" />
      <br/>
      <input type="submit" name="loginForm">
      
  </form>
  
   </div>
</body>
</html>

16 February 2016

CST336 Week 7

Some great new content this week including AJAX, XML and JSON (mostly new to me). Using what we learned this week I began improving a web site of mine. For assignment 7 I began work on http://www.diablofirearms.com/classSignup.php. This courses content has given me all kinds of ideas on using databases more throughout this site. For this page I used the following code to require a log in (or creation of user account):

<?php
session_start();

if(!isset($_SESSION['username'])) {
 header("Location: userLogin.php");
}
?>

Then for the login/account creation page I used the following:
<?php
session_start();

if (isset($_POST['loginname'])) {
 require 'db_connection.php';

 $sql = "SELECT *
 FROM students
 WHERE username = :username
 AND password = :password";

 $stmt = $dbConn -> prepare($sql);
 $stmt -> execute(array(":username" => $_POST['loginname'], ":password" => hash("sha1", $_POST['password'])));
 $record = $stmt -> fetch();
 if (!empty($record)) {
  $_SESSION['username'] = $record['username'];
  $_SESSION['name'] = $record['name'];
  header("Location: classSignup.php");
 }
}
?>
<html>
<head>
  <meta content="text/html; charset=utf-8" http-equiv="content-type">
  <title>Diablo Firearms Training - Student Login</title>

<!-- Extra code removed for size -->

  <u><font color="red" size="5"><strong>Account Log In</strong></font></u>
      <form method=post>
        <table border="0">
          <tbody>
            <tr>
              <td style="text-align: right;">Username: </td>
              <td><input tabindex="1" name="loginname"></td>
            </tr>
            <tr>
              <td style="text-align: right;">Password: </td>
              <td><input tabindex="2" name="password" type="password"></td>
            </tr>
            <tr>
              <td style="text-align: center;" colspan="2"><input tabindex="3" value="Log In" type="submit"><input value="Reset" type="reset"></td>
            </tr>
          </tbody>
        </table>
      </form>

      <div align="center"><u><font color="red" size="5"><strong>New Account
Creation</strong></font></u></div>
      <form method=post action=createUser.php>
        <table border="0">
          <tbody>
            <tr>
              <td style="text-align: right;">New Username: </td>
              <td><input id="username" name="username" type=text required><span id="checkUsername"></span></td>
            </tr>
            <tr>
              <td style="text-align: right;">Password: </td>
              <td><input id=newPassword name="newPassword" type="password" required><span id="checkPassword"></span></td>
            </tr>
            <tr>
              <td style="text-align: right;">Repeat Password: <br>
              </td>
              <td><input id=newPasswordRepeat name="newPasswordRepeat" type="password" required></td>
            </tr>
            <tr>
              <td style="text-align: right;">Full Name: <br>
              </td>
              <td><input type=text name="realName" required><br>
              </td>
            </tr>
            <tr>
              <td style="text-align: right;">Email: <br>
              </td>
              <td><input type=text name="email" required><br>
              </td>
            </tr>
<tr>
              <td style="text-align: center;" colspan="2"><input value="Create Account" type="submit"><input value="Reset" type="reset"></td>
            </tr>
          </tbody>
        </table>
      </form>
      </center>

<!-- Extra code removed for size -->
<script> $("#username").change( function newUser() { $.ajax({ type: "post", url: "userLookup.php", dataType: "json", data: { "username": $("#username").val() }, success: function(data,status) { if (data['exists'] == "true") { $("#checkUsername").html("<br>Username is already taken."); $("#checkUsername").css("color","red"); $("#username").css("background-color","LightCoral"); $("#username").focus(); } else if (document.getElementById("username").value.length < 5) { $("#checkUsername").html("<br>Username is too short."); $("#checkUsername").css("color","red"); $("#username").css("background-color","LightCoral"); $("#username").focus(); } else { $("#checkUsername").html(""); $("#username").css("background-color","White"); } }, }); }); $("#newPassword").change( function newPass() { if (document.getElementById("newPassword").value.length < 7) { $("#checkPassword").html("<br>Password is too short."); $("#checkPassword").css("color","red"); $("#newPassword").css("background-color","LightCoral"); $("#newPassword").focus(); } else { $("#checkPassword").html(""); $("#newPassword").css("background-color","White"); } }); $("#newPasswordRepeat").change( function newPassRepeat() { if (document.getElementById("newPasswordRepeat").value.length < 7) { $("#checkPassword").html("<br>Password is still too short."); $("#checkPassword").css("color","red"); $("#newPasswordRepeat").css("background-color","LightCoral"); $("#newPassword").focus(); } else if (document.getElementById("newPassword").value != document.getElementById("newPasswordRepeat").value) { $("#checkPassword").html("<br>Passwords do not match"); $("#checkPassword").css("color","red"); $("#newPassword").css("background-color","LightCoral"); $("#newPasswordRepeat").css("background-color","LightCoral"); $("#newPasswordRepeat").focus(); } else { $("#checkPassword").html(""); $("#newPassword").css("background-color","White"); $("#newPasswordRepeat").css("background-color","White"); } }); </script> </body> </html>

08 February 2016

05 February 2016

CST336 Week 5

This week we covered PHP sessions, including the difference between cookies and sessions, how to create a new session in PHP as well as how to store and retrieve data from a session and killing a session. For the lab we created a user login process for our previous lab.

Lab 5 can be viewed at johnlester.rocks/cst336/labs/lab5.php.
<?php
session_start();

if(!isset($_SESSION['username'])){
header("Location: lab5-login.php");
}

echo "Welcome " . $_SESSION['name'];
?>

<form method="post" action="lab5-logout.php" onsubmit="confirmLogout()">
<input type="submit" value="Logout" />
</form>

<?php
require '../db_connection.php';

function getStadiums() {
global $dbConn;

$sql = "SELECT stadiumId, stadiumName
FROM nfl_stadium
ORDER BY stadiumName";

$stmt = $dbConn -> prepare($sql);
$stmt -> execute();
return $stmt -> fetchAll();
}

function getTeamNames() {
global $dbConn;

$sql = "SELECT teamId, teamName
FROM nfl_team
ORDER BY teamName";

$stmt = $dbConn -> prepare($sql);
$stmt -> execute();
return $stmt -> fetchAll();
}

if (isset($_POST['delete'])) {//checks whether the "delete" button was clicked

$sql = "DELETE FROM nfl_stadium
WHERE stadiumId = :stadiumId";
$stmt = $dbConn -> prepare($sql);
$stmt -> execute(array(":stadiumId"=>$_POST['stadiumId']));
echo "Stadium has been deleted!";
}

if (isset($_POST['add'])) {//checks whether the "Add" button was clicked

$sql = "INSERT INTO nfl_match
(team1_id, team2_id, date, time, stadiumId, team1_score, team2_score)
VALUES
(:team1_id, :team2_id, :date, :time, :stadiumId, :team1_score, :team2_score)";
$stmt = $dbConn -> prepare($sql);
$stmt -> execute(array(":team1_id" => $_POST['team1'], ":team2_id" => $_POST['team2'], ":date" => $_POST['date'], ":time" => $_POST['time'], ":stadiumId" => $_POST['stadiumId'], ":team1_score" => $_POST['team1_score'], ":team2_score" => $_POST['team2_score']));
$matchId = $dbConn -> lastInsertId();

$sql = "INSERT INTO nfl_matchRecap
(matchId, recap)
VALUES
(:matchId, :recap)";
$stmt = $dbConn -> prepare($sql);
$stmt -> execute(array(":matchId" => $matchId, ":recap" => $_POST['recap']));

echo "RECORD ADDED!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<title>Lab 5 John Lester</title>
<meta name="description" content="">
<meta name="author" content="su5196">

<meta name="viewport" content="width=device-width; initial-scale=1.0">

<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">

<script>
function confirmDelete(stadiumName) {
var remove = confirm("Do you really want to delete " + stadiumName + "?");
if (!remove) {
event.preventDefault();
}
}

function confirmLogout(event) {
var logout = confirm("Do you really want to log out?");
if (!logout) {
event.preventDefault();
}
}
</script>

<link rel="stylesheet" type="text/css" href="../../css/style.css" />

<style>
form {
display: inline;
}

</style>

</head>

<body>
<div>

<h3> NFL Matches </h3>

<form method='post'>

Select Team 1:
<?php $teamNames = getTeamNames(); ?>

<select name="team1">
<?php
foreach ($teamNames as $team) {
echo "<option value='" . $team['teamId'] . "'>" . $team['teamName'] . "</option>";
}
?>
</select>

<br />
<br />

Select Team 2:
<select name="team2">
<?php
foreach ($teamNames as $team) {
echo "<option value='" . $team['teamId'] . "'>" . $team['teamName'] . "</option>";
}
?>
</select>
<br>
<br>
Date:
<input type="date" name="date" />
<br />
<br />

Time:
<input type="time" name="time" />
<br />
<br />
Stadium:
<select name="stadiumId">
<?php $stadiumList = getStadiums();
foreach ($stadiumList as $stadium) {
echo "<option value='" . $stadium['stadiumId'] . "'>" . $stadium['stadiumName'] . "</option>";
}
?>
</select>
<br />
<br />
Team 1 Score:
<input type="number" name="team1_score" />
<br />
<br />
Team 2 Score:
<input type="number" name="team2_score" />
<br />
<br />
<textarea name="recap" rows="15" cols="60" placeholder="Match Recap"></textarea> 
<br />
<br />
<input type="submit" name="add" value="Add match"/>

</form>

<h3> NFL Stadiums </h3>

<?php
foreach ($stadiumList as $stadium) { ?>
<?php echo $stadium['stadiumName']?>
<form action="lab5UpdateStadium.php" method="post">
<input type="hidden" name="stadiumId" value="<?php echo $stadium['stadiumId']?>" />
<input type="submit" name="update" value="Update" />
</form>
<form method="post" onsubmit="confirmDelete('<?php echo $stadium['stadiumName']?>')">
<input type="hidden" name="stadiumId" value="<?php echo $stadium['stadiumId'] ?>" />
<input type="submit" name="delete" value="Delete" />
</form>
<br />
<?php }//end foreach ?>

</div>
</body>
</html>


lab5-login.php:

<?php
session_start();

if (isset($_POST['username'])){
 require '../db_connection.php';

 $sql = "SELECT *
 FROM nfl_admin
 WHERE username = :username
 AND password = :password";

 $stmt = $dbConn -> prepare($sql);
 $stmt -> execute(array(":username" => $_POST['username'], ":password" => hash("sha1", $_POST['password'])));

 $record = $stmt -> fetch();

 if (empty($record)){
  echo "Wrong username/password!";
 } else {
  $_SESSION['username'] = $record['username'];
  $_SESSION['name'] = $record['firstname'] . " " . $record['lastname'];
  header("Location: lab5.php");
 }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Lab 5 - John Lester</title>
<meta name="description" content="">
<meta name="author" content="su5196">

<meta name="viewport" content="width=device-width; initial-scale=1.0">

<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">

<style>
form {
 display: inline;
}
</style>

</head>

<body>
<div>
<h1>Login</h1>
<form method="post">
Username: <input type="text" name="username" /><br />
<p></p>
Password: <input type="password" name="password" /><br />
<p></p>
<input type="submit" value="Login" />
<p></p>
</form>
<p>
Username: lest2631<br />
Password: qwerty
</p>
</div>
</body>
</html>


lab5-logout.php:

<?php
session_start();
session_destroy();

header("Location: ../");
?>


and finally, lab5UpdateStadium.php:

<?php
session_start();

if(!isset($_SESSION['username'])){
header("Location: lab5-login.php");
}

echo "Welcome " . $_SESSION['name'];
?>
<form method="post" action="lab5-logout.php" onsubmit="confirmLogout()">
<input type="submit" value="Logout" />
</form>

<?php
require '../db_connection.php';

function getStadium($stadiumId){
global $dbConn;

$sql = "SELECT * 
FROM nfl_stadium
WHERE stadiumId = :stadiumId";
$stmt = $dbConn -> prepare($sql);
$stmt -> execute(array(":stadiumId"=>$stadiumId));
return $stmt->fetch(); 
}

if (isset($_POST['save'])) { //checks whether we're coming from "save data" form

$sql = "UPDATE nfl_stadium
SET stadiumName = :stadiumName,
street = :street,
city = :city
WHERE stadiumId = :stadiumId";
$stmt = $dbConn -> prepare($sql);
$stmt -> execute(array(":stadiumName"=>$_POST['stadiumName'],
":street"=>$_POST['street'],
":city"=>$_POST['city'],
":stadiumId"=>$_POST['stadiumId']
)); 

echo "RECORD UPDATED!! <br> <br>"; 
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<title>John Lester Lab 5updateStadium</title>
<meta name="description" content="">
<meta name="author" content="lara4594">

<meta name="viewport" content="width=device-width; initial-scale=1.0">

<link rel="shortcut icon" href="../../favicon.ico">
</head>

<body>
<div>

<?php
if (isset($_POST['stadiumId'])) {
$stadiumInfo = getStadium($_POST['stadiumId']); ?>

<form method="post">
Stadium Name: <input type="text" name="stadiumName" value="<?php echo $stadiumInfo['stadiumName']; ?>" /><br />
Street: <input type="text" name="street" value="<?php echo $stadiumInfo['street']; ?>" /><br />
City: <input type="text" name="city" value="<?php echo $stadiumInfo['city']; ?>" /><br />
State: <input type="text" name="state" value="<?php echo $stadiumInfo['state']; ?>" /><br />
Zip: <input type="text" name="zip" value="<?php echo $stadiumInfo['zip']; ?>" /><br />
<input type="hidden" name="stadiumId" value="<?php echo $stadiumInfo['stadiumId']; ?>">
<input type="submit" name="save" value="Save"> 
</form>

<?php
 }
?>
<br /><br />
<a href="lab5.php"> Go back to main page </a>

</div>
</body>
</html>