User talk:Ebarrier

From ICO wiki
Revision as of 01:08, 6 June 2016 by Ebarrier (talk | contribs)
Jump to navigationJump to search

Config

<?php
//Specific configuration
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "student");
define("DB_NAME", "webshop");
?>

PDO server connection

<?php
try {
    $conn = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.';charset=utf8', DB_USER, DB_PASS);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

Header session start

<?php
// Set session variables
session_start();
if (!array_key_exists("cart", $_SESSION)) {
    $_SESSION["cart"] = array();
    // Here we store product -> count mapping
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="description" content="Etienne's webshop">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Etienne's webshop</title>
</head>

<body>

Footer JSscript

<script src="js/myJS.js"></script>
</body>

<footer>
    <div class="footer">
        <a href="http://www.itcollege.ee">itcollege.ee</a>
        <p>For any question, please contact us!</p>
    </div>
</footer>

</html>

Log out - destroy session

<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]);
}
session_destroy();
//unset($_SESSION["userid"]);
header("Location: index.php");
?>

Registration - Hash password

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

if($_SERVER['REQUEST_METHOD'] != "POST") {
    header("index.php");
}

$validFields = true;

if($_POST["username"] == null || preg_match("[\w.]{1,64}", $_POST["username"]) != 1) {
    $validFields = false;
    echo "<p>Your username is missing or invalid</p>";
}

if($_POST["email"] == null || preg_match("^[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,}$", $_POST["email"]) != 1) {
    $validFields = false;
    echo "<p>Your email is missing or invalid</p>";
}

if($_POST["password1"] == null || preg_match(".{8,256}", $_POST["password1"]) != 1 || $_POST["password1"] !== $_POST["password2"]) {
    $validFields = false;
    echo "<p>Your password is missing or invalid</p>";
}

if($_POST["firstname"] == null || preg_match("[-a-zA-z]{1,30}", $_POST["firstname"]) != 1) {
    $validFields = false;
    echo "<p>Your firstname is missing or invalid</p>";
}

if($_POST["lastname"] == null || preg_match("[-a-zA-z]{1,30}", $_POST["lastname"]) != 1) {
    $validFields = false;
    echo "<p>Your lastname is missing or invalid</p>";
}

if($validFields) {
    //Statement to create user in DB
    $statement = $conn->prepare(
    "INSERT INTO `user` (
        `username`,
        `email`,
        `password`,
        `fname`,
        `lname`)
    VALUES (:username, :email, :hashed_password, :firstname, :lastname)"); //the :arguments will be replaced below

    if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); //check if an error happens

    //We bind all the parameters
    $statement->bindParam(':username', $_POST["username"]);
    $statement->bindParam(':email', $_POST["email"]);
    $statement->bindParam(':hashed_password', password_hash($_POST["password"], PASSWORD_DEFAULT));
    $statement->bindParam(':firstname', $_POST["firstname"]);
    $statement->bindParam(':lastname', $_POST["lastname"]);

    //We execute the statement to create user with POST values
    if ($statement->execute()) {
      echo "Registration successful. Thank you! <br> <a href=\"index.php\">Go back to main page</a>";
    } else {
        if ($statement->errorCode() == 1062) {
          //This is result in 200 OK
          echo "This e-mail or username is already registered";
        } else {
          //This will result in 500 internal server error
            die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo()); //check if an error happens
          }
    }
}
?>

Log in - Check password

//function to check if the email or username provided match the password
function checkCredentials($dbFieldToCheck, $conn, $username, $password) {
    $statement = $conn->prepare("
        SELECT id, password 
        FROM user 
        WHERE ".$dbFieldToCheck." = :credential");
    if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); 
    $statement->bindParam(':credential', $username);
    if (!$statement->execute()) die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo());
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    if(password_verify($password, $row["password"])) {
        return $row["id"];
    }
    return false;
}

//we call the function above twice (for email and for username)
$row1 = checkCredentials('email', $conn, $_POST["username/email"], $_POST["password"]);
$row2 = checkCredentials('username', $conn, $_POST["username/email"], $_POST["password"]);

//if one of the function calls above is succesful, user is logged in, otherwise we ask him to try again or to sign up
if($row1) { //if the key-value pair user_id-password exists
    $_SESSION["userid"] = $row1; // This just stores user row number
    header('Location:'.$_SERVER['HTTP_REFERER']); //This will redirect back to index.php
} elseif($row2) {
    $_SESSION["userid"] = $row2;
    header('Location:'.$_SERVER['HTTP_REFERER']);
} else { ?>
  <p>It looks like you are not known sorry. Please <a href="registration.php">sign up</a>  to enjoy our services or go back to <a href="index.php">main page</a>.</p>

Form validation

<div class="content">
    <h2>Create your account</h2>

    <form method="post" action="regsubmit.php">
      <div>
        <label for="username">Username</label>
        <input type="text" 
            name="username" 
            id="username" 
            pattern="[\w\.]{1,64}"
            placeholder="your username"
            title="Numbers, letters (case sensitive), underscore and dot are allowed. 64 characters max" required/>
      </div> 

      <div>
        <label for="email">E-mail</label>
        <input type="email" 
            name="email"
            id="email"
            placeholder="your email" required/>
      </div>    

      <div>
        <label for="password1">Password</label>
        <input type="password" 
            name="password1" 
            id="password1" 
            pattern=".{8,256}"
            placeholder="type a password"
            title="8 characters minimum" required/>
      </div>

      <div>
        <label for="password2">Repeat password</label>
        <input type="password" 
            name="password2" 
            id="password2" 
            onkeyup="checkPass(); return false;"
            placeholder="retype your password"
            pattern=".{8,256}" required/>
            <span id="confirmMessage" class="confirmMessage"></span>
      </div>

      <div>
        <label for="firstname">First-name</label>
        <input type="text" 
            name="firstname" 
            id="firstname" 
            pattern="[-a-zA-z]{1,30}"
            placeholder="your firstname"
            title="Only letters" required/>
      </div> 

      <div>
        <label for="lastname">Last-name</label>
        <input type="text" 
            name="lastname" 
            id="lastname" 
            pattern="[-a-zA-z]{1,30}"
            placeholder="your lastname"
            title="Only letters" required/>
      </div> 

      <div>
        <input type="submit" value="Sign-up"/>
      </div>
      
    </form>

    <div id="backToMain">
        <a href="index.php">Go back to main page</a>
    </div>
</div>

Profile form

if($_SESSION["userid"] != null && $_SERVER['REQUEST_METHOD'] == "POST") {
    $statement0 = $conn->prepare("
    UPDATE `user` 
    SET username=:username, 
        email=:email, 
        fname=:fname, 
        lname=:lname, 
        gender=:gender, 
        phonecode=:phonecode, 
        phonenum=:phonenum, 
        dob=:dob, 
        address=:address, 
        city=:city, 
        postal_code=:postalcode, 
        countryname=:countryname
    WHERE id = :userid");
    if (!$statement0) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    $statement0->bindParam(':username', $_POST["username"]);
    $statement0->bindParam(':email', $_POST["email"]);
    $statement0->bindParam(':fname', $_POST["firstname"]);
    $statement0->bindParam(':lname', $_POST["lastname"]);
    $statement0->bindParam(':gender', $_POST["gender"]);
    $statement0->bindParam(':phonecode', $_POST["phonecode"]);
    $statement0->bindParam(':phonenum', $_POST["phonenum"]);
    $statement0->bindParam(':dob', $_POST["dob"]);
    $statement0->bindParam(':address', $_POST["address"]);
    $statement0->bindParam(':city', $_POST["city"]);
    $statement0->bindParam(':postalcode', $_POST["postalcode"]);
    $statement0->bindParam(':countryname', $_POST["country"]);
    $statement0->bindParam(':userid', $_SESSION["userid"]);
    if (!$statement0->execute()) die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo());
} else {
    header("index.php");
}

$statement1 = $conn->prepare("
    SELECT username, email, fname, lname, gender, phonecode, phonenum, 
        dob, address, city, postal_code, countryname
    FROM `user`
    WHERE id = :userid");
if (!$statement1) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement1->bindParam(':userid', $_SESSION["userid"]);
if (!$statement1->execute()) die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo());
$row1 = $statement1->fetch(PDO::FETCH_ASSOC);
?>

<div class="content">
    <h2>My profile</h2>

    <form method="post">
        <div>
            <label for="username">Username</label>
            <input type="text" 
                name="username" 
                id="username" 
                value="<?php echo $row1["username"];?>"
                pattern="[\w\.]{1,64}"
                placeholder="your username"
                title="Numbers, letters (case sensitive), underscore and dot are allowed. 64 characters max" required/>
        </div> 

        <div>
            <label for="email">E-mail</label>
            <input type="email" 
                name="email" 
                id="email" 
                value="<?php echo $row1["email"];?>" 
                placeholder="your email" required/>
        </div>    

        <div>
            <label for="firstname">First name</label>
            <input type="text" 
                name="firstname" 
                id="firstname" 
                value="<?php echo $row1["fname"];?>" 
                pattern="[-a-zA-z]{1,30}"
                title="Only letters"
                placeholder="your first name" required/>
        </div> 

        <div>
            <label for="lastname">Last name</label>
            <input type="text" 
                name="lastname" 
                id="lastname" 
                value="<?php echo $row1["lname"];?>"
                pattern="[-a-zA-z]{1,30}"
                title="Only letters"
                placeholder="your last name" required/>
        </div>
        
        <a href="changepass.php">Change password</a>

        <div>
            <label for="gender">Gender</label><br>
            <?php
            if ($row1["gender"] == null) { ?>
                <input type="radio" name="gender" value="male"> Male
                <input type="radio" name="gender" value="female"> Female
            <?php
            }
            elseif ($row1["gender"] == "male") { ?>
                <input type="radio" name="gender" value="male" checked> Male
                <input type="radio" name="gender" value="female"> Female
            <?php
            } 
            else { ?>
                <input type="radio" name="gender" value="male" > Male
                <input type="radio" name="gender" value="female" checked> Female
            <?php
            } ?>
        </div>

        <div>
            <label for="phonenumber">Phone number</label>
            <select name="phonecode" id="phonecode" onchange="" size="1">
                <?php
                $statement2 = $conn->query('
                    SELECT phonecode 
                    FROM country 
                    GROUP BY phonecode 
                    ORDER BY phonecode');
                if ($row1["phonecode"] == 0) {
                    echo "<option value=\"null\">-</option>";
                }
                else {
                    echo "<option value=".$row1["phonecode"].">+".
                        $row1["phonecode"]."</option>";
                }
                while($row2 = $statement2->fetch(PDO::FETCH_ASSOC)) {
                    echo "<option value=".$row2["phonecode"].">+".
                        $row2["phonecode"]."</option>";
                }
                
                if ($row1["phonenum"] == 0) { ?>
                    <input type="text" 
                        name="phonenum" 
                        id="phonenum" 
                        value="-" 
                        pattern="[0-9]*"
                        title="Only numbers"
                        placeholder="phone number"/>                
                <?php
                }
                else { ?>
                    <input type="text" 
                        name="phonenum" 
                        id="phonenum" 
                        value="<?php echo $row1["phonenum"];?>" 
                        pattern="[0-9]*"
                        title="Only numbers"
                        placeholder="phone number"/>
                <?php
                }
                ?>
            </select>
        </div>
        
        <div>
            <label for="dob">Date of birth</label>
                <?php
                if($row1["dob"] == "0000-00-00") { ?>
                    <input type="text" 
                        name="dob" 
                        min="(Date('Y')-90)-01-01"
                        pattern="[19|20][0-9]{2}-[0|1][0-9]-[0-3][0-9]"
                        title="The date format must be YYYY-MM-DD"
                        placeholder="yyyy-mm-dd">
                <?php
                }
                else { ?>
                    <input type="text" 
                        name="dob" 
                        value="<?php echo $row1["dob"]; ?>" 
                        min="(Date('Y')-90)-01-01"
                        pattern="(19|20)[0-9]{2}-(0|1)[0-9]-[0-3][0-9]"
                        title="The date format must be YYYY-MM-DD"
                        placeholder="yyyy-mm-dd">
                <?php
                }
                ?>
        </div>
        
        <fieldset>
            <legend>Address of residence:</legend>
            <div>
                <label for="address">Street</label>
                    <?php
                    if($row1["address"] == null) { ?>
                        <input type="text" 
                            name="address" 
                            id="address" 
                            placeholder="your address"/>
                    <?php
                    }
                    else { ?>    
                        <input type="text" 
                            name="address" id="address" 
                            value="<?php echo $row1["address"];?>" 
                            placeholder="your address"/>
                    <?php
                    }
                    ?>
            </div>
            
            <div>
                <label for="city">City</label>
                    <?php
                    if($row1["city"] == null) { ?>
                        <input type="text" name="city" id="city" placeholder="your city"/>
                    <?php
                    }
                    else { ?>    
                        <input type="text" 
                            name="city" 
                            id="city" 
                            value="<?php echo $row1["city"];?>" 
                            placeholder="your city"/>
                    <?php
                    }
                    ?>
            </div>
            
            <div>
                <label for="postalcode">Postal code</label>
                    <?php
                    if($row1["postal_code"] == 0) { ?>
                        <input type="text" 
                            name="postalcode" 
                            id="postalcode" 
                            placeholder="your postal code"/>
                    <?php
                    }
                    else { ?>
                        <input type="text" 
                            name="postalcode" 
                            id="postalcode" 
                            value="<?php echo $row1["postal_code"];?>" 
                            placeholder="your postal code"/>
                    <?php
                    }
                    ?>
            </div>
            
            <div>
                <label for="country">Country</label>
                <select name="country" id="country" onchange="" size="1">
                    <?php
                    $statement3 = $conn->query('SELECT nicename FROM country');
                    if ($row1["countryname"] == "0") {
                        echo "<option value=\"null\">-</option>";
                    }
                    else {
                        echo "<option value=" . $row1["countryname"] . ">" . 
                            $row1["countryname"] . "</option>";
                    }
                    while ($row3 = $statement3->fetch(PDO::FETCH_ASSOC)) {
                        echo "<option value=" . $row3["nicename"] . ">" . 
                            $row3["nicename"] . "</option>";
                    }
                    ?>
                </select>
            </div>
        </fieldset>
        
        <div>
            <input type="submit" value="Save"/>
        </div>
      
    </form>
</div>

Last inserted id - Empty session var

if($_SESSION["userid"]==null) {
    header("index.php");
}

$statement = $conn->prepare("
    INSERT INTO `order` (user_id) 
    VALUES (:userid)");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement->bindParam(':userid', $_SESSION["userid"]);
if (!$statement->execute()) die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo());

$order_id = $conn->lastInsertId(); // This contains the ID for the inserted order
$_SESSION["orderid"] = $order_id;

// This inserts rows to order_item table
$statement = $conn->prepare("
    INSERT INTO order_item (order_id, product_id, count) 
    VALUES (:orderid,:productid,:productcount)");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
foreach ($_SESSION["cart"] as $product_id => $count) {
    $statement->bindParam(':orderid', $order_id);
    $statement->bindParam(':productid', $product_id);
    $statement->bindParam(':productcount', $count);
	if (!$statement->execute()) {
		die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo());
	}
}

// We reset shopping cart:
$_SESSION["cart"] = array();

Select Join

//Function to display better unset dates
function clearUnsetDate($inputDate) {
    if($inputDate=="0000-00-00 00:00:00") {
        echo "-";
    } else {
        echo $inputDate;
    }
}

$statement = $conn->prepare("
    SELECT
        `order`.`id` AS `orderid`,
        `order`.`created` AS `ordercreated`,
        `order`.`paid` AS `paymentdate`,
        `order`.`shipped` AS `shipmentdate`,
        `product`.`id` AS `productid`,
        `product`.`name` AS `productname`,
        `product`.`price` AS `productprice`,
        `order_item`.`count` AS `count`
    FROM `order_item`
    JOIN `order`
        ON `order_item`.`order_id` = `order`.`id`
    JOIN `product`
        ON `order_item`.`product_id` = `product`.`id`
    WHERE `order`.`user_id` = :userid
    ORDER BY `order`.`created` DESC");
if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
$statement->bindParam(':userid', $_SESSION["userid"]);
if (!$statement->execute()) die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo()); ?>

<div class="content">
    <h2>My orders</h2>
    <ul>
    <?php
    $prevOrderId = null;
    while ($result = $statement->fetch(PDO::FETCH_ASSOC)) { 
        //We display the orders by order id
        if($prevOrderId != $result["orderid"]) { ?>
            <br>
            <li>Order #: <?php echo $result["orderid"]; ?></li>
            <?php
            //We calculate the total price of the order
            $statement2 = $conn->prepare("
                SELECT order_item.count*product.price AS subTotal
                FROM product
                JOIN order_item
                ON product.id = order_item.product_id
                WHERE order_item.order_id = :orderId"); 
            if (!$statement2) die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
            $statement2->bindParam(':orderId', $result["orderid"]);
            if (!$statement2->execute()) die("Execute failed: (" . $statement->errorCode() . ") " . $statement->errorInfo());
            $orderAmount=null;
            while ($result2 = $statement2->fetch(PDO::FETCH_ASSOC)) {
                $orderAmount += $result2["subTotal"];
            }?>
            <ul>
                <li>Total: <?php echo $orderAmount; ?>€</li>
                    <form method="post" action="paymentpage.php">
                        <input type="hidden" name="orderid" id="orderid" value="<?php echo $result["orderid"]; ?>"/>
                        <?php 
                        if ($result["paymentdate"] == "0000-00-00 00:00:00") {
                            echo "<input type=\"submit\" value=\"Pay now\"/>";
                        } ?>
                    </form>
                <li>Order date: <?php clearUnsetDate($result["ordercreated"]); ?></li>
                <li>Paid date: <?php clearUnsetDate($result["paymentdate"]); ?></li>
                <li>Shipment date: <?php clearUnsetDate($result["shipmentdate"]); ?></li>
        <?php 
        } else { ?> 
            <ul> <?php 
        } ?>
                <li>
                    <a href="description.php/?id=<?php echo $result["productid"]; ?>">
                        <?php echo $result["productname"]; ?></a>
                        (<?php echo $result["productprice"]; ?>€)
                        : x<?php echo $result["count"]; ?>
                </li>
            </ul>
        <?php
        $prevOrderId = $result["orderid"];
    }
    ?>

Image upload with hash of picture's path

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

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);
	}

    //DB query
    $statement = $conn->prepare("
        INSERT INTO product (name, description, type, price, hash) 
        VALUES (:name, :desc, :type, :price, :hash)");
    $statement->bindParam(':name', $_POST["product_name"]);
    $statement->bindParam(':desc', $_POST["product_desc"]);
    $statement->bindParam(':type', $_POST["product_type"]);
    $statement->bindParam(':price', $_POST["product_price"]);
    $statement->bindParam(':hash', $checksum);
    if (!$statement->execute()) die("Execute failed: (" . $statement->errno . ") " . $statement->error);

    ?>
    <p>The product <?=$_POST["product_name"]?> has been added successfully!</p>

<?php
}
?>
<h1>Add a new product</h1>
<ul>
</ul>
<form method="post" enctype="multipart/form-data">
    <label for="product_name">Product name: </label>
    <input type="text" name="product_name" placeholder="Product name" required/><br>
    
    <label for="product_type">Product type: </label>
    <input type="text" name="product_type" placeholder="Product type" required/><br>
    
    <label for="product_price">Product price: </label>
    <input type="number" name="product_price" placeholder="Product price" min="0" required/><br>
    
    <label for="product_desc">Product description: </label><br>
    <textarea name="product_desc" rows="10" cols="50"></textarea><br>
    
    <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
    Select product picture (max 2M): 
    <input id="file" type="file" name="uploaded_image" accept="image/*"/><br>
    <input type="submit" value="Add product"/>
</form><br>

<?php
$statement = $conn->prepare("SELECT id, name, price FROM product");
//$result = $conn->query("SELECT id, name, price FROM product");
$statement->execute();

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    echo "<li><a href=\"description.php?id=" . $row["id"] . "\">" .  
        $row["name"] . "</a> " . $row["price"] . "eur</li>";
}
?>

Header of site styling html

<div class="header row">
    <div class="col-2">&nbsp;</div>
    <h1 class="col-8"><img src="css/webshoplogo.png" alt="Etienne's Webshop" height="115"></h1>

    <?php
    if (array_key_exists("userid", $_SESSION) && $_SESSION["userid"] != NULL) {
        //If the $_SESSION["userid"] is set we say hello with his name
        //var_dump($_SESSION["userid"]); //This is just to show the content of $_SESSION variable
        $results = $conn->query("
            SELECT * 
            FROM user 
            WHERE id = " . $_SESSION["userid"]);
        $row = $results->fetch(PDO::FETCH_ASSOC);?>
        <div class="greeting col-1">
            <p>Hello <?=$row["fname"]?></p>
        </div>
        <div class="logOut col-1">
            <p><a href="logout.php">Sign out</a></p>
        </div>
    </div> <!--header row finishes here-->
    <div class="menu row">
        <ul class="menu">
            <li class="menu col-2"><a href=#></a>&nbsp;</li>
            <li class="menu col-2"><a href="profile.php">My profile</a></li>
            <li class="menu col-2"><a href="orders.php">My orders</a></li>
            <li class="menu col-2"><a href="cart.php">My cart</a></li>
            <li class="menu col-2"><a href="contact.php">Contact</a></li>
            <li class="menu col-2"><a href=#></a>&nbsp;</li>
        </ul>
    </div>
    <?php
    } else { //else we display the login page
        ?>
        <div class="loginButton col-1">
            <a href=# onclick="showLogin(); return false;">Log in</a>
            <div class="loginPanel" id="loginPanel" style="display:none">
                <form action="login.php" method="post">
                    <input class="loginField" type="text" name="username/email" placeholder="username or email" required/>
                    <input class="loginField" type="password" name="password" placeholder="password" required/>
                    <input id="loginPanelSubmit" type="submit" value="Log in!"/>
                </form>
            </div>
        </div>
        <div class="registration col-1">
            <p><a href="registration.php"> Sign up</a></p>
        </div>
    </div> <!--header row finishes here-->
    
    <div class="menu row">
        <ul class="menu">
            <li class="menu col-4"><a href=#></a>&nbsp;</li>
            <li class="menu col-2"><a href="cart.php">My cart</a></li>
            <li class="menu col-2"><a href="contact.php">Contact</a></li>
            <li class="menu col-4"><a href=#></a>&nbsp;</li>
        </ul>
    </div>

Change password

<div class="content">

    <?php
    if($_SESSION["userid"] != null && $_SERVER['REQUEST_METHOD'] == "POST") {
        $statement = $conn->prepare("SELECT id, password FROM user WHERE id = :userid");
        if (!$statement) die("Prepare failed: (" . $conn->errno . ") " . $conn->error); 
        $statement->bindParam(':userid', $_SESSION["userid"]);
        $statement->execute();
        if (!$statement->execute()) die("Execute failed: (" . $statement0->errno . ") " . $statement0->error);
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        
        if($_POST["newpass"] === $_POST["confirmnewpass"]) {
            if(password_verify($_POST["currentpass"], $row["password"])) {
                $statement1 = $conn->prepare("
                    UPDATE `user`
                    SET `password` = :pass
                    WHERE id = :userid");
                $statement1->bindParam(':pass', password_hash($_POST["newpass"], PASSWORD_DEFAULT));
                $statement1->bindParam(':userid', $_SESSION["userid"]);
                $statement1->execute();
                header("changepassconfirm.php");
            } 
            else {
                echo "<p>Sorry but your current password is not correct please try again</p>";
            }    
        }
        else {
            echo "<p>Sorry but there is a mistake in your new password, please try again</p>";
        }
        
    } 
    else {
        header("index.php");
    }

    ?>

<souce lang="html5">

Change your password

   <form method="post">
           <label for="currentpass">Enter your current password</label>
           <input type="password" name="currentpass" id="currentpass" placeholder="your current password" required/>
           <label for="newpass">Enter your new password</label>
           <input type="password" 
               name="newpass" 
               id="newpass" pattern=".{8,256}"
               placeholder="type a password"
               title="8 characters minimum" required/>
           <label for="confirmnewpass">Confirm your new password</label>
           <input type="password" 
               name="confirmnewpass" 
               id="confirmnewpass" 
               onkeyup="checkPass(); return false;"
               placeholder="retype your password"
               pattern=".{8,256}" required/>
           
       <input type="submit" value="Change password"/>
   </form>
       <a href="index.php">Go back to main page</a>

</source>

Cart

if ($_SERVER['REQUEST_METHOD'] == "POST") {
  // If method is POST, we update the cart. Else GET, just display the cart.
  $product_id = intval($_POST["id"]); //intval to make the value an integer
  if (array_key_exists($product_id, $_SESSION["cart"])) {
      $_SESSION["cart"][$product_id] += intval($_POST["count"]); //$_SESSION["cart"][$product_id] is a dictionnary.  [$product_id] is the key and the value is the count.
  } else {
      $_SESSION["cart"][$product_id] = intval($_POST["count"]);
  }

  if ($_SESSION["cart"][$product_id]<=0) {
    unset($_SESSION["cart"][$product_id]);
  }
}
?>

<div class="content">
    <h2>My cart</h2>

    <?php 
    $grantotal=0;
    if($_SESSION["cart"]==null) {
        echo "<h3>It is quite empty over here...</h3>";
    } else {
        echo"<h3>Products in your shopping cart</h3>";
        $statement = $conn->query('SELECT id, name, price FROM product');
        $statement or die("Connection to database failed:".$conn->connect_error); //if result is true, the second expression is not checked.
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
          $product_id= $row['id'];
          if (array_key_exists($row['id'], $_SESSION["cart"])) {
            $count = $_SESSION["cart"][$product_id];
            $grantotal =  $grantotal + $row['price']*$count;?>
            <li>
                <?php echo $count; ?> x <a href="description.php?id=<?php echo $product_id ?>">
                <?php echo $row['name'] ?></a>
                <?php echo $row['price'] ?>€ => 
                <?php echo $row['price']*$count, '€'; ?>
              <form method="post">
                <input type="hidden" name="id" value="<?php echo $product_id; ?>"/>
                <input type="hidden" name="count" value="-1"/>
                <input type="submit" value="Remove one"/>
              </form>
            </li>
          <?php    
          }
        }
        if($_SESSION["userid"]==null) {?>
            <p><em>You must log in or sign up to checkout</em></p>

        <?php 
        } elseif ($_SESSION["userid"]!=null) { ?>
            
            <br><br><p>
            <form method="post" action="placeorder.php">
                <?php echo 'Total price: ', $grantotal, '€';?>
                <br><input type="submit" value="Checkout =>"/>
                <p><em>When clicking "Checkout" you will be redirected on the bank card payment page</em></p>
            </form>
            </p>
        <?php
        }
    }
    ?>

    <div id="backToMain">
        <a href="index.php">Go back to main page</a>
    </div>
</div>

CSS

* {
    box-sizing: border-box;
    margin:0px;
}
.row::after {
    content: "";
    clear: both;
    display: block;
}
[class*="col-"] {
    float: left;
}

.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

html {
    font-family: Arial, Helvetica, sans-serif;
}

a {
    color: #0033CC;
    text-decoration:none;
}

.header {
    color: #000000;
    height: 125px;
    position: relative;
}

h1, h2, h3, h4 {
    text-align: center;
    padding: 0px 0px;
}

h1 {
    font-family: Georgia, serif;
}

h2, h3, h4 {
    font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
}

h2 {
    height: 2.2em;
    font-size: 3em;
    padding: 30px 0px;
}

h3 {
    height: 2em;
    font-size: 2em;
    padding: 15px 0px;
}

h4 {
    height: 1.5em;
    font-size: 1.5em;
    padding: 5px 0px;
    margin-top: 10px;
    margin-bottom: 20px;
}

.content {
    margin: 0em 10em;
}

.loginButton, .registration, .greeting, .logOut {
    max-width: 300px;
    text-align: center;
    padding: 40px 0px;
    height: 100%;
    font-size: 1.7em;
}

.loginButton:hover, .registration:hover {
    background-color: #C0C0C0;
}

.loginPanel {
    max-width: 100px;
    height: 100%;
    margin: 5px 0px 0px 0px;
    overflow:visible;
}

.loginField {
    max-width: 153px;
}

#loginPanelSubmit {
    margin: 0px 0px 0px -26px;
}

ul.menu {
    list-style-type: none;
    height: 60px;
    margin: 0;
    padding: 0;
}

li.menu {
    display: inline;
    height: 100%;
    background-color: #C0C0C0;
    text-align: center;
    padding: 15px 0px;
    font-size: 1.7em;
}

li.menu.col-2:hover {
    background-color: #B0B0B0;
}

div.img {
    border: 1px solid #ccc;
}

div.img:hover {
    border: 1px solid #777;
}

div.img img {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 15px;
    text-align: center;
}

.responsive {
    padding: 0 6px;
    float: left;
    width: 15%;
}

@media only screen and (max-width: 700px){
    .responsive {
        width: 49.99999%;
        margin: 6px 0;
    }
}

@media only screen and (max-width: 500px){
    .responsive {
        width: 100%;
    }
}

.clearfix:after {
    content: "";
    display: table;
    clear: both;
}

.pic {
    text-align: center;
}

footer, .footer, .addToCart {
    height: 120px;
    padding: 20px 0px;
    text-align: center;
}

.addToCart {
    height: 80px;
    padding-top: 20px;
    margin-top: 1em;
    text-align: center;
}

#backToMain {
    height: 70px;
    padding-top: 10px;
    margin-top: 1em;
    text-align: center;
}

JS

function checkPass() {
    //Store the password field objects into variables ...
    var pass1 = document.getElementById('password1');
    var pass2 = document.getElementById('password2');
    //Store the Confimation Message Object ...
    var message = document.getElementById('confirmMessage');
    //Set the colors we will be using ...
    var goodColor = "#66cc66";
    var badColor = "#ff6666";
    //Compare the values in the password field 
    //and the confirmation field
    if(pass1.value == pass2.value){
        //The passwords match. 
        //Set the color to the good color and inform
        //the user that they have entered the correct password 
        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords match"
    } else {
        //The passwords do not match.
        //Set the color to the bad color and
        //notify the user.
        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords do not match"
    }
} 

function showLogin() {
    var panelDisplay = document.getElementById('loginPanel');
    if (panelDisplay.style.display=='none') {
        panelDisplay.style.display='block';    
    } else {
        panelDisplay.style.display='none';    
    }   
}