User talk:Ebarrier
From ICO wiki
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>
<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>
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>";
}
?>