Web Exam help: Difference between revisions

From ICO wiki
Jump to navigationJump to search
(Created page with "==IMAGE GALLERY== ==Index.php== <source lang="html5"> <?php require_once "config.php"; include "header.php"; $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME); if ($c...")
 
Line 120: Line 120:


<?php include "footer.php" ?>
<?php include "footer.php" ?>
</source>
==ADDALBUM.PHP==
<source lang="html5">
<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
  $statement = $conn->prepare(
      "insert into Sheela_gallery_album(name, owner_id) values(?,?)");
  $statement->bind_param("si", $_POST["album_name"], $_SESSION["user"]["id"]);
  $statement->execute();
}
?>
<form method="post">
  <p>Here you can create a new album, it's basically a group of images that are to be uploaded</p>
  <label>Enter album name</label>
  <input type="text" name="album_name"/>
  <input type="submit"/>
</form>
</source>
==LAURI-ADDALBUM.PHP==
<source lang="html5">
<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $statement = $conn->prepare(
        "insert into lauri_gallery_album(name, owner_id) values(?,?)");
    if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); // check all the errors!
    $statement->bind_param("si", $_POST["album_name"], $_SESSION["user"]["id"]);
    if (!$statement->execute()) die("Execute failed (" . $conn->errno . ") " . $conn->error); // check all the errors!
    header("Location: album.php?id=" . mysqli_insert_id($conn)); // This will redirect to newly created album page
}
?>
<form method="post">
  <p>Here you can create a new album, it's basically a group of images that are to be uploaded</p>
  <label>Enter album name</label>
  <input type="text" name="album_name"/>
  <input type="submit"/>
</form>
</source>
==ALBUM.PHP==
<source lang="html5">
<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
?>
Back to landing page <a href="index.php">here</a>.
Upload images <a href="upload.php">here</a>
Images of album:
ss<?php
// To show images of the album
$statement = $conn->prepare(
"select Sheela_gallery_image.hash, Sheela_gallery_image.created " .
"from Sheela_gallery_image " .
"where Sheela_gallery_image.album_id = ? " .
"order by Sheela_gallery_image.created desc");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement->bind_param("i", $_GET["id"]);
$statement->execute();
?><ul><?php
  foreach ($statement->get_result() as $row) {
?><li><img src="thumbnails/<?=$row['hash']?>"
  title="<?=$row['name'];?>"/> uploaded <?=$row['created']?></li><?php
  }
?></ul>
</source>
==LAURI-ALBUM.PHP==
<source lang="html5">
<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
?>
Back to landing page <a href="index.php">here</a>.
Upload images <a href="upload.php">here</a>
Images of album:
<?php
// To show images of the album
$statement = $conn->prepare(
"select lauri_gallery_image.hash, lauri_gallery_image.created " .
"from lauri_gallery_image " .
"where lauri_gallery_image.album_id = ? " .
"order by lauri_gallery_image.created desc");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement->bind_param("i", $_GET["id"]);
$statement->execute();
?><ul><?php
  foreach ($statement->get_result() as $row) {
?><li><img src="thumbnails/<?=$row['hash']?>"
  title="<?=$row['name'];?>"/> uploaded <?=$row['created']?></li><?php
  }
?></ul>
</source>
==COMMOM.PHP==
<source lang="html5">
<?php
function show_likes($image_id) {
  $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
  if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
  $statement = $conn->prepare("
    select id
    from Sheela_gallery_like
    where image_id = ? and user_id = ?");
  $statement->bind_param("ii", $image_id, $_SESSION["user"]["id"]);
  $statement->execute();
  $result = $statement->get_result(); // Consume the results of the executed query
 
  // Here we will check if user already likes this image
  if ( $result->fetch_array() ) {
    // we got a row -> user already likes this image
    echo '<button onClick="unlike(' . $image_id . ');">Unlike!</button>';
  } else {
    // or if no rows -> user hasn't liked it yet
    echo '<button onClick="like(' . $image_id . ');">Like!</button>';
  }
  $statement = $conn->prepare(
    "SELECT Sheela_gallery_user.display_name " .
    "FROM Sheela_gallery_like " .
    "JOIN Sheela_gallery_user ON Sheela_gallery_like.user_id = Sheela_gallery_user.id " .
    "WHERE Sheela_gallery_like.image_id = ?");
  if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
  $statement->bind_param("i", $image_id);
  $statement->execute();
  $first = true; // First user shall not have comma prefixed
  foreach ($statement->get_result() as $like) {
    if (!$first) {
    echo ", ";
    }
    echo $like["display_name"];
    $first = false; // All other users have their nicknames comma prefixed
  }
};
?>
</source>
==LAURI-COMMON.PHP==
<source lang="html5">
<?php
function show_likes($image_id) {
  $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
  if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
  $statement = $conn->prepare("
    select id
    from lauri_gallery_like
    where image_id = ? and user_id = ?");
  $statement->bind_param("ii", $image_id, $_SESSION["user"]["id"]);
  $statement->execute();
  $result = $statement->get_result(); // Consume the results of the executed query
 
  // Here we will check if user already likes this image
  if ( $result->fetch_array() ) {
    // we got a row -> user already likes this image
    echo '<button onClick="unlike(' . $image_id . ');">Unlike!</button>';
  } else {
    // or if no rows -> user hasn't liked it yet
    echo '<button onClick="like(' . $image_id . ');">Like!</button>';
  }
  $statement = $conn->prepare(
    "SELECT lauri_gallery_user.display_name " .
    "FROM lauri_gallery_like " .
    "JOIN lauri_gallery_user ON lauri_gallery_like.user_id = lauri_gallery_user.id " .
    "WHERE lauri_gallery_like.image_id = ?");
  if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
  $statement->bind_param("i", $image_id);
  $statement->execute();
  $first = true; // First user shall not have comma prefixed
  foreach ($statement->get_result() as $like) {
    if (!$first) {
    echo ", ";
    }
    echo $like["display_name"];
    $first = false; // All other users have their nicknames comma prefixed
  }
};
?>
</source>
==CONFIG.PHP==
<source lang="html5">
<?php
// This is site specific configuration! Do not commit this to Git!
define("DB_SERVER", "localhost");
define("DB_USER",  "test");
define("DB_PASS",  "t3st3r123");
define("DB_NAME",  "test");
define("DB_PREFIX", "Sheela_");
?>
</source>
==DELETEALBUM.PHP==
<source lang="html5">
<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$statement = $conn->prepare(
"delete from Sheela_gallery_album where id = ?");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); // check all the errors!
$statement->bind_param("i", $_GET["id"]);
if (!$statement->execute()) die("Execute failed (" . $conn->errno . ") " . $conn->error); // check all the errors!
header("Location: index.php");
</source>
==FOOTER.PHP==
<source lang="html5">
</div>
    <footer>
      <ul>
        <li>Phone: +372 1234 4567</li>
        <li><a href="http://facebook.com">Visit us on Facebook!</a></li>
      </ul>
    </footer>
  </body>
</html>
</source>
==HEADER.PHP==
<source lang="html5">
<?php
session_set_cookie_params(0, '/~ssumathi', 'enos.itcollege.ee', 0, 1);
session_start();
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <meta name="description" content="Introduction to this Image_Gallery">
    <title>This goes into the titlebar</title>
    <link type="text/css" rel="stylesheet" href="css/style.css"/>
    <script type="text/javascript"src="js/main.js"></script>
  </head>
  <body>
  <div id ="content">
</source>
==LIKE.PHP==
<source lang="html5">
<?php
// like.php?image_id=123 will attempt to add like to an image for currenty logged in user
session_start();
require_once "config.php";
require_once "common.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
$statement = $conn->prepare("
    insert into Sheela_gallery_like (image_id, user_id)
    values (?, ?)");
$statement->bind_param("ii", $_GET["image_id"], $_SESSION["user"]["id"]);
$statement->execute();
show_likes($_GET["image_id"]); // This will simply return a fragment of HTML
?>
</source>
==LOGOUT.PHP==
<source lang="html5">
<?php
session_start();
session_destroy();
unset($_SESSION["user"]);
header('Location: index.php'); // This will redirect back to index
</source>
==REGISTRATION.PHP==
<source lang="html5">
<?php
require_once "config.php";
include "header.php";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    $statement = $conn->prepare(
        "INSERT INTO `Sheela_gallery_user` (`email`, `password_salt`, `password_hash`, `display_name`) " .
        "VALUES (?, ?, ?, ?)");
    if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    $salt = substr(str_shuffle(
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
    $statement->bind_param("ssss",
        $_POST["email"],
        $salt,
        sha1($salt . $_POST["password"]),
        $_POST["display_name"]);
    if ($statement->execute()) {
        header("Location: index.php");
    } else {
        if ($statement->errno == 1062) {
            echo "This e-mail is already registered";
      } else {
            die("Execute failed: (" . $statement->errno . ") " . $statement->error);
      }
    }
}
?>
<form method="post"><!-- This form is submitted to the same reg.php file with POST method -->
  <ul>
    <li>e-mail: <input type="mail" name="email" value="<?=@$_POST['email'];?>" required/></li>
    <li>password: <input type="password" name="password" pattern="[a-zA-Z0-9]{8,16}" title="Password has to be at least 8 characters" required/></li>
    <li>nickname: <input type="text" name="display_name" placeholder="cute honeybunny" pattern="[a-z]{3,10}" required/></li>
  </ul>
  <input type="submit"/>
</form>
</source>
==UPLOAD.PHP==
<source lang="html5">
<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (array_key_exists("uploaded_image", $_FILES)) {
    if ($_FILES["uploaded_image"]["error"] == 1) die("Too big image!"); // File size check
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimetype = finfo_file($finfo, $_FILES["uploaded_image"]["tmp_name"]);
    if (strpos($mimetype, "image/") != 0) // This is basically mimetype.startswith("image/")
        die("Go away! Only images allowed!");
    $checksum = sha1(file_get_contents(
        $_FILES["uploaded_image"]["tmp_name"])) . "." .
        pathinfo($_FILES["uploaded_image"]["name"], PATHINFO_EXTENSION);
    // Keep the original image in uploads/ folder
    if (!file_exists("uploads/" . $checksum)) {
        copy(
          $_FILES["uploaded_image"]["tmp_name"],
          "uploads/" . $checksum);
    }
// Generate thumbnail, this assumes you have created thumbnails/ folder and set permissions to 777
if (!file_exists("thumbnails/" . $checksum)) {
$im = new Imagick("uploads/" . $checksum);
$im->thumbnailImage(128, 0); // Width of 128px and automatically determine height based on aspect ratio
$im->writeImage("thumbnails/" . $checksum);
}
// Generate smaller version of the image
if (!file_exists("small/" . $checksum)) {
$im = new Imagick("uploads/" . $checksum);
$im->thumbnailImage(960, 0); // Width of 960px and automatically determined height
$im->writeImage("small/" . $checksum);
}
    // TODO: Check that specified album is owned by the currently logged in user (SQL select query!)
    // something like this, if you find a matching row the upload permission is granted:
    // select * from Sheela_gallery_album where owner_id = $_SESSION["user]["id"] and id = $_POST['album_id']
    // These four lines are the new stuff!
    $statement = $conn->prepare("insert into `Sheela_gallery_image` (`album_id`, `name`, `hash`) values (?,?,?)");
    $statement->bind_param("iss", $_POST["album_id"], $_FILES["uploaded_image"]["name"], $checksum);
    $statement->execute();
    ?>
    <p>Mimetype was: <?= $mimetype; ?></p>
    <p>Original was: <a href="uploads/<?=$checksum;?>"><?=$checksum;?></a>
<p>960px was: <a href="small/<?=$checksum;?>"><?=$checksum;?></a>
<p>Thumbnail was: <a href="thumbnails/<?=$checksum;?>"><?=$checksum;?></a>
    <p>Filename was: <?=$_FILES["uploaded_image"]["name"];?></p>
    <p>File stored at: <?=$_FILES["uploaded_image"]["tmp_name"];?></p>
<?php
}
?>
<form method="post" enctype="multipart/form-data">
<select name="album_id">
    <?php
    $statement = $conn->prepare("select id, name from Sheela_gallery_album where owner_id = ?");
$statement->bind_param("i", $_SESSION["user"]["id"]);
$statement->execute();
foreach ($statement->get_result() as $row) {
?>
<option value="<?=$row['id']?>"><?=$row['name']?></option>
<?php
}
?>
    </select>
  Select file for upload: <input id="file" type="file" name="uploaded_image" accept="image/*">
  <input type="submit"/>
</form>
</source>
==UNLIKE.PHP==
<source lang="html5">
<?php
// unlike.php?image_id=123 will attempt to remove a like
session_start();
require_once "config.php";
require_once "common.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
$statement = $conn->prepare("
    delete from lauri_gallery_like
    where image_id = ? and user_id = ?
    limit 1");
$statement->bind_param("ii", $_GET["image_id"], $_SESSION["user"]["id"]);
$statement->execute();
show_likes( $_GET["image_id"]);
?>
</source>
==LAURI-MAIN.JS==
<source lang="html5">
function like(image_id) {
  var request = new XMLHttpRequest();
  request.open('GET', 'like.php?image_id=' + image_id, true);
  // This is an example of callback
  request.onload = function() {
    // This function runs once response has been received
    if (request.status >= 200 && request.status < 400) {
      document.querySelector("#likes_" + image_id).innerHTML =
        request.responseText;
    }
  };
  // This will only start the request
  request.send();
}
function unlike(image_id) {
  var request = new XMLHttpRequest();
  request.open('GET', 'unlike.php?image_id=' + image_id, true);
  // This is an example of callback
  request.onload = function() {
    // This function runs once response has been received
    if (request.status >= 200 && request.status < 400) {
      document.querySelector("#likes_" + image_id).innerHTML =
        request.responseText;
    }
  };
  // This will only start the request
  request.send();
}
</source>
==CSS-STYLE.CSS==
<source lang="html5">
ul.thumbnails {
list-style: none;
}
ul#thumbnails li {
float: left;
display: block;
width: 160px;
</source>
</source>



Revision as of 20:29, 5 June 2016

IMAGE GALLERY

Index.php

<?php
require_once "config.php";
include "header.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error)
  die("Connection to database failed:" .
    $conn->connect_error);
$conn->query("set names utf8"); 

?>

<h1 style="color:Purple ;font-family:Indie Flower; float:Center"><em><center>Sheela's Image#Gallery</center></em></h1>
<p>
<?php 

if ($_SERVER['REQUEST_METHOD'] == "POST") {
  $statement = $conn->prepare(
      "select * from Sheela_gallery_user where email = ? and " .
      "password_hash = SHA1(CONCAT(password_salt, ?))");
  if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
  $statement->bind_param("ss", $_POST["email"], $_POST["password"]);
  $statement->execute();
  $results = $statement->get_result();
  $row = $results->fetch_assoc();
  if (!$row)
	  echo "Login failed!";
  $_SESSION["user"] = $row;
}

// Here we check if the user is logged in
if ($user = @$_SESSION["user"]) { // Extra lazy hack, use $user instead of $_SESSION["user"] from now on
  ?>
  <h1>Hello <?=$user["display_name"];?></h1>
  <p>
  Add albums <a href="addalbum.php">here</a>.
  Upload images <a href="upload.php">here</a>.
  </p>
  My albums:
  <?php
  // Here we list user's albums
  $statement = $conn->prepare("select * from Sheela_gallery_album where owner_id = ?");
  $statement->bind_param("i", $user["id"]);
  $statement->execute();
  ?><ul><?php
      foreach ($statement->get_result() as $row) {
        ?><li><a href="album.php?id=<?=$row['id']?>"><?=$row['name'];?></a>
		<a href="deletealbum.php?id=<?=$row['id']?>">[Delete]</a>
</li><?php
      }
  ?></ul>
  
 My recent uploads: 
  
  <?php

  // To show images of the user
$statement = $conn->prepare(
    "select Sheela_gallery_image.id, Sheela_gallery_image.hash, Sheela_gallery_image.created " .
	"from Sheela_gallery_image " .
	"join Sheela_gallery_album " .
	"on Sheela_gallery_album.id = Sheela_gallery_image.album_id " .
	"where Sheela_gallery_album.owner_id = ? " .
	"order by Sheela_gallery_image.created desc " .
	"limit 2");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);

  
$statement->bind_param("i", $user["id"]);
$statement->execute();
  ?><ul class="thumbnails"><?php
      foreach ($statement->get_result() as $row) {
        ?><li>
            <img src="thumbnails/<?=$row['hash']?>" title="<?=$row['name'];?>"/>
            uploaded <?=$row['created'] ?> <?=$row["id"]?>
            <?php
            $statement = $conn->prepare(
                "SELECT Sheela_gallery_user.display_name " .
                "FROM Sheela_gallery_likes " .
                "JOIN Sheela_gallery_user ON Sheela_gallery_likes.user_id = Sheela_gallery_user.id " .
                "WHERE Sheela_gallery_likes.image_id = ?");
            $statement->bind_param("i", $row["id"]);
            $statement->execute();
            $first = true; // First user shall not have comma prefixed
            foreach ($statement->get_result() as $like) {
              if (!$first) {
                 echo ", ";
              }
              echo $like["display_name"];
              $first = false; // All other users have their nicknames comma prefixed
            }
            ?>
            like this

          </li><?php

      }
  ?></ul><?php

} else {
?>
  <form method="post">
    <input type="mail" name="email"/>
    <input type="password" name="password"/>
    <input type="submit" value="Log in!"/>
  </form>
<?php
}
?>

<a href ="registration.php">Sign up</a> 
<p>
<a href="upload.php">Upload Page </a>



<?php include "footer.php" ?>


ADDALBUM.PHP

<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

if ($_SERVER['REQUEST_METHOD'] == "POST") {
  $statement = $conn->prepare(
      "insert into Sheela_gallery_album(name, owner_id) values(?,?)");
  $statement->bind_param("si", $_POST["album_name"], $_SESSION["user"]["id"]);
  $statement->execute();
}

?>

<form method="post">
   <p>Here you can create a new album, it's basically a group of images that are to be uploaded</p>
   <label>Enter album name</label>
   <input type="text" name="album_name"/>
   <input type="submit"/>
</form>

LAURI-ADDALBUM.PHP

<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $statement = $conn->prepare(
        "insert into lauri_gallery_album(name, owner_id) values(?,?)");
    if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); // check all the errors!
    $statement->bind_param("si", $_POST["album_name"], $_SESSION["user"]["id"]);
    if (!$statement->execute()) die("Execute failed (" . $conn->errno . ") " . $conn->error);	// check all the errors!
    header("Location: album.php?id=" . mysqli_insert_id($conn)); // This will redirect to newly created album page
}
?>

<form method="post">
   <p>Here you can create a new album, it's basically a group of images that are to be uploaded</p>
   <label>Enter album name</label>
   <input type="text" name="album_name"/>
   <input type="submit"/>
</form>

ALBUM.PHP

<?php
include "header.php";
require_once "config.php";

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
?>

Back to landing page <a href="index.php">here</a>.
Upload images <a href="upload.php">here</a>

Images of album:

ss<?php

// To show images of the album
$statement = $conn->prepare(
"select Sheela_gallery_image.hash, Sheela_gallery_image.created " .
"from Sheela_gallery_image " .
"where Sheela_gallery_image.album_id = ? " .
"order by Sheela_gallery_image.created desc");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement->bind_param("i", $_GET["id"]);
$statement->execute();
?><ul><?php
  foreach ($statement->get_result() as $row) {
	?><li><img src="thumbnails/<?=$row['hash']?>"
  title="<?=$row['name'];?>"/> uploaded <?=$row['created']?></li><?php
  }
?></ul>

LAURI-ALBUM.PHP

<?php
include "header.php";
require_once "config.php";

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);
?>

Back to landing page <a href="index.php">here</a>.
Upload images <a href="upload.php">here</a>

Images of album:
 
<?php

// To show images of the album
$statement = $conn->prepare(
"select lauri_gallery_image.hash, lauri_gallery_image.created " .
"from lauri_gallery_image " .
"where lauri_gallery_image.album_id = ? " .
"order by lauri_gallery_image.created desc");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement->bind_param("i", $_GET["id"]);
$statement->execute();
?><ul><?php
  foreach ($statement->get_result() as $row) {
	?><li><img src="thumbnails/<?=$row['hash']?>"
  title="<?=$row['name'];?>"/> uploaded <?=$row['created']?></li><?php
  }
?></ul>

COMMOM.PHP

<?php

function show_likes($image_id) {
  $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
  if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);

  $statement = $conn->prepare("
     select id
     from Sheela_gallery_like
     where image_id = ? and user_id = ?");
  $statement->bind_param("ii", $image_id, $_SESSION["user"]["id"]);
  $statement->execute();

  $result = $statement->get_result(); // Consume the results of the executed query
  
  // Here we will check if user already likes this image
  if ( $result->fetch_array() ) {
    // we got a row -> user already likes this image
    echo '<button onClick="unlike(' . $image_id . ');">Unlike!</button>';
  } else {
    // or if no rows -> user hasn't liked it yet
    echo '<button onClick="like(' . $image_id . ');">Like!</button>';
  }

  $statement = $conn->prepare(
    "SELECT Sheela_gallery_user.display_name " .
    "FROM Sheela_gallery_like " .
    "JOIN Sheela_gallery_user ON Sheela_gallery_like.user_id = Sheela_gallery_user.id " .
    "WHERE Sheela_gallery_like.image_id = ?");
  if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);

  $statement->bind_param("i", $image_id);
  $statement->execute();


  $first = true; // First user shall not have comma prefixed
  foreach ($statement->get_result() as $like) {
    if (!$first) {
     echo ", ";
    }
    echo $like["display_name"];
    $first = false; // All other users have their nicknames comma prefixed
  }
};

?>

LAURI-COMMON.PHP

<?php

function show_likes($image_id) {
  $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
  if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);

  $statement = $conn->prepare("
     select id
     from lauri_gallery_like
     where image_id = ? and user_id = ?");
  $statement->bind_param("ii", $image_id, $_SESSION["user"]["id"]);
  $statement->execute();

  $result = $statement->get_result(); // Consume the results of the executed query
  
  // Here we will check if user already likes this image
  if ( $result->fetch_array() ) {
    // we got a row -> user already likes this image
    echo '<button onClick="unlike(' . $image_id . ');">Unlike!</button>';
  } else {
    // or if no rows -> user hasn't liked it yet
    echo '<button onClick="like(' . $image_id . ');">Like!</button>';
  }

  $statement = $conn->prepare(
    "SELECT lauri_gallery_user.display_name " .
    "FROM lauri_gallery_like " .
    "JOIN lauri_gallery_user ON lauri_gallery_like.user_id = lauri_gallery_user.id " .
    "WHERE lauri_gallery_like.image_id = ?");
  if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);

  $statement->bind_param("i", $image_id);
  $statement->execute();


  $first = true; // First user shall not have comma prefixed
  foreach ($statement->get_result() as $like) {
    if (!$first) {
     echo ", ";
    }
    echo $like["display_name"];
    $first = false; // All other users have their nicknames comma prefixed
  }
};

?>

CONFIG.PHP

<?php
// This is site specific configuration! Do not commit this to Git!
define("DB_SERVER", "localhost");
define("DB_USER",   "test");
define("DB_PASS",   "t3st3r123");
define("DB_NAME",   "test");
define("DB_PREFIX", "Sheela_");
?>

DELETEALBUM.PHP

<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);


$statement = $conn->prepare(
	"delete from Sheela_gallery_album where id = ?");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); // check all the errors!
$statement->bind_param("i", $_GET["id"]);
if (!$statement->execute()) die("Execute failed (" . $conn->errno . ") " . $conn->error);	// check all the errors!
header("Location: index.php");

FOOTER.PHP

</div>
    <footer>
      <ul>
        <li>Phone: +372 1234 4567</li>
        <li><a href="http://facebook.com">Visit us on Facebook!</a></li>
      </ul>
    </footer>
  </body>
</html>

HEADER.PHP

<?php
session_set_cookie_params(0, '/~ssumathi', 'enos.itcollege.ee', 0, 1);
session_start();

?>


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <meta name="description" content="Introduction to this Image_Gallery">
    <title>This goes into the titlebar</title>
    <link type="text/css" rel="stylesheet" href="css/style.css"/>
    <script type="text/javascript"src="js/main.js"></script>
  </head>
  <body>
  <div id ="content">

LIKE.PHP

<?php

// like.php?image_id=123 will attempt to add like to an image for currenty logged in user
session_start();
require_once "config.php";
require_once "common.php";

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);

$statement = $conn->prepare("
    insert into Sheela_gallery_like (image_id, user_id)
    values (?, ?)");
$statement->bind_param("ii", $_GET["image_id"], $_SESSION["user"]["id"]);
$statement->execute();

show_likes($_GET["image_id"]); // This will simply return a fragment of HTML
?>

LOGOUT.PHP

<?php
session_start();
session_destroy();
unset($_SESSION["user"]);
header('Location: index.php'); // This will redirect back to index

REGISTRATION.PHP

<?php
require_once "config.php";
include "header.php";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    $statement = $conn->prepare(
        "INSERT INTO `Sheela_gallery_user` (`email`, `password_salt`, `password_hash`, `display_name`) " .
        "VALUES (?, ?, ?, ?)");
    if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    $salt = substr(str_shuffle(
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
    $statement->bind_param("ssss",
        $_POST["email"],
        $salt,
        sha1($salt . $_POST["password"]),
        $_POST["display_name"]);
    if ($statement->execute()) {
        header("Location: index.php");
    } else {
        if ($statement->errno == 1062) {
            echo "This e-mail is already registered";
       } else {
            die("Execute failed: (" . $statement->errno . ") " . $statement->error);
       }
    }
}
?>
<form method="post"><!-- This form is submitted to the same reg.php file with POST method -->
  <ul>
    <li>e-mail: <input type="mail" name="email" value="<?=@$_POST['email'];?>" required/></li>
    <li>password: <input type="password" name="password" pattern="[a-zA-Z0-9]{8,16}" title="Password has to be at least 8 characters" required/></li>
    <li>nickname: <input type="text" name="display_name" placeholder="cute honeybunny" pattern="[a-z]{3,10}" required/></li>
  </ul>
  <input type="submit"/>
</form>

UPLOAD.PHP

<?php
include "header.php";
require_once "config.php";
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

if (array_key_exists("uploaded_image", $_FILES)) {
    if ($_FILES["uploaded_image"]["error"] == 1) die("Too big image!"); // File size check
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimetype = finfo_file($finfo, $_FILES["uploaded_image"]["tmp_name"]);
    if (strpos($mimetype, "image/") != 0) // This is basically mimetype.startswith("image/")
        die("Go away! Only images allowed!");
    $checksum = sha1(file_get_contents(
        $_FILES["uploaded_image"]["tmp_name"])) . "." .
        pathinfo($_FILES["uploaded_image"]["name"], PATHINFO_EXTENSION);

    // Keep the original image in uploads/ folder
    if (!file_exists("uploads/" . $checksum)) {
        copy(
          $_FILES["uploaded_image"]["tmp_name"],
          "uploads/" . $checksum);
    }
	
	// Generate thumbnail, this assumes you have created thumbnails/ folder and set permissions to 777
	if (!file_exists("thumbnails/" . $checksum)) {
		$im = new Imagick("uploads/" . $checksum);
		$im->thumbnailImage(128, 0); // Width of 128px and automatically determine height based on aspect ratio
		$im->writeImage("thumbnails/" . $checksum);
	}
	
	// Generate smaller version of the image
	if (!file_exists("small/" . $checksum)) {
		$im = new Imagick("uploads/" . $checksum);
		$im->thumbnailImage(960, 0); // Width of 960px and automatically determined height
		$im->writeImage("small/" . $checksum);
	}
	
    // TODO: Check that specified album is owned by the currently logged in user (SQL select query!)
    // something like this, if you find a matching row the upload permission is granted:
    // select * from Sheela_gallery_album where owner_id = $_SESSION["user]["id"] and id = $_POST['album_id']

    // These four lines are the new stuff!
    $statement = $conn->prepare("insert into `Sheela_gallery_image` (`album_id`, `name`, `hash`) values (?,?,?)");
    $statement->bind_param("iss", $_POST["album_id"], $_FILES["uploaded_image"]["name"], $checksum);
    $statement->execute();

    ?>
    <p>Mimetype was: <?= $mimetype; ?></p>
    <p>Original was: <a href="uploads/<?=$checksum;?>"><?=$checksum;?></a>
	<p>960px was: <a href="small/<?=$checksum;?>"><?=$checksum;?></a>

	<p>Thumbnail was: <a href="thumbnails/<?=$checksum;?>"><?=$checksum;?></a>

    <p>Filename was: <?=$_FILES["uploaded_image"]["name"];?></p>
    <p>File stored at: <?=$_FILES["uploaded_image"]["tmp_name"];?></p>
<?php
}
?>

<form method="post" enctype="multipart/form-data">
	<select name="album_id">
    <?php
    $statement = $conn->prepare("select id, name from Sheela_gallery_album where owner_id = ?");
	$statement->bind_param("i", $_SESSION["user"]["id"]);
	$statement->execute();
	foreach ($statement->get_result() as $row) {
		?>
			<option value="<?=$row['id']?>"><?=$row['name']?></option>
		<?php
		}
	?>
    </select>
  Select file for upload: <input id="file" type="file" name="uploaded_image" accept="image/*">
  <input type="submit"/>
</form>

UNLIKE.PHP

<?php

// unlike.php?image_id=123 will attempt to remove a like
session_start();
require_once "config.php";
require_once "common.php";

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);

$statement = $conn->prepare("
    delete from lauri_gallery_like
    where image_id = ? and user_id = ?
    limit 1");
$statement->bind_param("ii", $_GET["image_id"], $_SESSION["user"]["id"]);
$statement->execute();
show_likes( $_GET["image_id"]);

?>

LAURI-MAIN.JS

function like(image_id) {
  var request = new XMLHttpRequest();
  request.open('GET', 'like.php?image_id=' + image_id, true);
 
  // This is an example of callback
  request.onload = function() {
    // This function runs once response has been received
    if (request.status >= 200 && request.status < 400) {
      document.querySelector("#likes_" + image_id).innerHTML =
        request.responseText;
    }
  };
 
  // This will only start the request
  request.send();
}


function unlike(image_id) {
  var request = new XMLHttpRequest();
  request.open('GET', 'unlike.php?image_id=' + image_id, true);

  // This is an example of callback
  request.onload = function() {
    // This function runs once response has been received
    if (request.status >= 200 && request.status < 400) {
      document.querySelector("#likes_" + image_id).innerHTML =
        request.responseText;
    }
  };

  // This will only start the request
  request.send();
}

CSS-STYLE.CSS

ul.thumbnails {
	list-style: none;
}

ul#thumbnails li {
	float: left;
	display: block;
	width: 160px;

LAURI-Index.php

<?php
include "header.php";
require_once "config.php";

$SQL_IMAGES = "
     select
        lauri_gallery_image.id,
        lauri_gallery_image.hash,
        lauri_gallery_image.created
     from
        lauri_gallery_image
     join
        lauri_gallery_album
     on
        lauri_gallery_album.id = lauri_gallery_image.album_id
     where
        lauri_gallery_album.owner_id = ?
     order by
        lauri_gallery_image.created desc
     limit 2";

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("Connection to database failed:" . $conn->connect_error);

// Here we check if user is attempting to log in
if ($_SERVER['REQUEST_METHOD'] == "POST") {
  $statement = $conn->prepare(
      "select * from lauri_gallery_user where email = ? and " .
      "password_hash = SHA1(CONCAT(password_salt, ?))");
  $statement->bind_param("ss", $_POST["email"], $_POST["password"]);
  $statement->execute();
  $results = $statement->get_result();
  $row = $results->fetch_assoc();
  if (!$row)
	  echo "Login failed!";
  $_SESSION["user"] = $row; // Set user as logged in
}

// Here we check if the user is logged in
if ($user = @$_SESSION["user"]) { // Extra lazy hack, use $user instead of $_SESSION["user"] from now on
  ?>
  <h1>Hello <?=$user["display_name"];?></h1>
  <p>
  Add albums <a href="addalbum.php">here</a>.
  Upload images <a href="upload.php">here</a>.
  </p>
  My albums:
  <?php
  // Here we list user's albums
  $statement = $conn->prepare("select * from lauri_gallery_album where owner_id = ?");
  $statement->bind_param("i", $user["id"]);
  $statement->execute();
  ?><ul><?php
      foreach ($statement->get_result() as $row) {
        ?><li><a href="album.php?id=<?=$row['id']?>"><?=$row['name'];?></a>
		<a href="deletealbum.php?id=<?=$row['id']?>">[Delete]</a>
		</li><?php
      }
  ?></ul>
  
  My uploads: 
  
  <?php

  // To show images of the user
  $statement = $conn->prepare($SQL_IMAGES);
  if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
  $statement->bind_param("i", $user["id"]);
  $statement->execute();
  ?><ul class="thumbnails"><?php
      foreach ($statement->get_result() as $row) {
        ?><li>
            <img src="thumbnails/<?=$row['hash']?>" title="<?=$row['name'];?>"/>
            uploaded <?=$row['created'] ?>
            <div id="likes_<?=$row["id"]?>">
            <?php
            require_once "common.php";
            show_likes($row["id"]); // show_likes function is defined in common.php
            ?>
            like this
            </div>

          </li><?php
      }
  ?></ul><?php

} else {
?>
  <form method="post">
    <input type="mail" name="email"/>
    <input type="password" name="password"/>
    <input type="submit" value="Log in!"/>
  </form>
<?php
}
?>