Basic E-commerce site development part-3

The way to manage the website that was implemented in the previous tutorials has shown in this tutorial. Follow the steps to complete task of this tutorial.

Step-1:

Change the user type to admin from the users table of the database.

Step-2:

Create add_page.php file under html folder with the following.


<?php

require('./includes/config.php');
// If the user isn't logged in as an administrator, redirect them:
redirect_invalid_user('user_admin');
// Require the database connection:
require(MYSQL);
// Include the header file:
$page_title = 'Add a Site Content Page';
include('./includes/header.php');
// For storing errors:
$add_page_errors = array();
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check for a title:
if (!empty($_POST['title'])) {
$t = escape_data(strip_tags($_POST['title']), $dbc);
} else {
$add_page_errors['title'] = 'Please enter the title!';
}

// Check for a category:
$category = $_POST['category'];
if (is_array($category))
{
for ($i=0;$i<sizeof($category);$i++)
{
$cat = $category[$i];
}
}

else { // No category selected.
$add_page_errors['category'] = 'Please select a category!';
}

// Check for a description:
if (!empty($_POST['description'])) {
$d = escape_data(strip_tags($_POST['description']), $dbc);
} else {
$add_page_errors['description'] = 'Please enter the description!';
}

// Check for the content:
if (!empty($_POST['content'])) {
$allowed = '<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>';
$c = escape_data(strip_tags($_POST['content'], $allowed), $dbc);
} else {
$add_page_errors['content'] = 'Please enter the content!';
}

if (empty($add_page_errors)) { // If everything's OK.
// Add the page to the database:
$q = "INSERT INTO pages (categories_id, title, description, content) VALUES ($cat, '$t', '$d', '$c')";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
// Print a message:
echo '<div class="alert alert-success"><h3>The page has been added!</h3></div>';
// Clear $_POST:
$_POST = array();
// Send an email to the administrator to let them know new content was added?
} else { // If it did not run OK.
trigger_error('The page could not be added due to a system error. We apologize for any inconvenience.');
}
} // End of $add_page_errors IF.
} // End of the main form submission conditional.
// Need the form functions script, which defines create_form_input():
require('./includes/form_functions.php');

?>

<h1>Add a Site Content Page</h1>
<form action="add_page.php" method="post" accept-charset="utf-8">
<fieldset><legend>Fill out the form to add a page of content:</legend>
<div class="form-group">
<label for="status" class="control-label">Status</label>
<select name="status" class="form-control"><option value="draft">Draft</option>
<option value="live">Live</option>
</select></div>

<?php

create_form_input('title', 'text', 'Title', $add_page_errors);
// Add the category drop down menu:
echo '<div class="form-group';
if (array_key_exists('category', $add_page_errors)) echo ' has-error';

/*

echo '"><label for="category" class="control-label">Category</label>
<select name="category" class="form-control">
<option>Select One</option>';

*/



// Allow for multiple categories:
echo '"><label for="category" class="control-label">Category</label>
<select name="category[]" class="form-control" multiple size="5">';
// Retrieve all the categories and add to the pull-down menu:
$q = "SELECT id, category FROM categories ORDER BY category ASC";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
// Check for stickyness:
if (isset($_POST['category']) && ($_POST['category'] == $row[0]) ) echo ' selected="selected"';
echo ">$row[1]</option>\n";
}

echo '</select>';
if (array_key_exists('category', $add_page_errors)) echo '<span class="help-block">' . $add_page_errors['category'] . '</span>';
echo '</div>';
create_form_input('description', 'textarea', 'Description', $add_page_errors);
create_form_input('content', 'textarea', 'Content', $add_page_errors);
?>
<input type="submit" name="submit_button" value="Add This Page" id="submit_button" class="btn btn-primary" />
</fieldset>
</form>
<script type="text/javascript" src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
tinyMCE.init({

// General options
selector : "#content",
width : 800,
height : 400,
browser_spellcheck : true,
plugins: "paste,searchreplace,fullscreen,hr,link,anchor,image,charmap,media,autoresize,autosave,contextmenu,wordcount",
toolbar1: "cut,copy,paste,|,undo,redo,removeformat,|hr,|,link,unlink,anchor,image,|,charmap,media,|,search,replace,|,fullscreen",
toolbar2: "bold,italic,underline,strikethrough,|,alignleft,aligncenter,alignright,alignjustify,|,formatselect,|,bullist,numlist,|,outdent,indent,blockquote,",

// Example content CSS (should be your site CSS)
content_css : "/test3/html/css/bootstrap.min.css",
});

</script>
<!-- /TinyMCE -->
<?php /* PAGE CONTENT ENDS HERE! */

// Include the footer file to complete the template:
include('./includes/footer.html');
?>

Step-3:

Add some recods in category table. Create category.php file under html folder and add the following content.


<?php

require('./includes/config.php');
// The config file also starts the session.
// Require the database connection:
require(MYSQL);
// Validate the category ID:
if (filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
$cat_id = $_GET['id'];
// Get the category title:
$q = 'SELECT category FROM categories WHERE id=' . $cat_id;
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) !== 1) { // Problem!
$page_title = 'Error!';
include('./includes/header.php');
echo '<div class="alert alert-danger">This page has been accessed in error.</div>';
include('./includes/footer.html');
exit();
}

// Fetch the category title and use it as the page title:
list($page_title) = mysqli_fetch_array($r, MYSQLI_NUM);
include('./includes/header.php');
echo '<h1>' . htmlspecialchars($page_title) . '</h1>';
// Get the pages associated with this category:
$q = 'SELECT id, title, description FROM pages WHERE categories_id=' . $cat_id . ' ORDER BY date_created DESC';
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) { // Pages available!
// Fetch each record:

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
// Display each record:
echo '<div><h4><a href="page.php?id=' . $row['id'] . '">' . htmlspecialchars($row['title']) . '</a></h4><p>' . htmlspecialchars($row['description']) . '</p></div>';
} // End of WHILE loop.
} else { // No pages available.
echo '<p>There are currently no pages of content associated with this category. Please check back again!</p>';
}
} else { // No valid ID.
$page_title = 'Error!';
include('./includes/header.php');
echo '<div class="alert alert-danger">This page has been accessed in error.</div>';
} // End of primary IF.
// Include the HTML footer:
include('./includes/footer.html');
?>

Step-4:

Create page.php file under html folder and add the following content.


<?php

require('./includes/config.php');
// The config file also starts the session.
// Require the database connection:
require(MYSQL);
$_SESSION['user_id'] =12;
$_SESSION['user_not_expired'] = true;
// Validate the category ID:
if (isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
$page_id = $_GET['id'];
// Get the page info:
$q = 'SELECT title, description, content FROM pages WHERE id=' . $page_id;
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) !== 1) { // Problem!
$page_title = 'Error!';
include('./includes/header.php');
echo '<div class="alert alert-danger">This page has been accessed in error.</div>';
include('./includes/footer.html');
exit();
}

// Fetch the page info:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$page_title = $row['title'];
include('includes/header.php');
echo '<h1>' . htmlspecialchars($page_title) . '</h1>';
// Display the content if the user's account is current:
if (isset($_SESSION['user_not_expired'])) {
$user_id = $_SESSION['user_id'];

// Show the page content:
echo "<div>{$row['content']}</div>";
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['notes']) && !empty($_POST['notes'])) {
$notes = $_POST['notes'];
$q = "REPLACE INTO notes (user_id, page_id, note) VALUES ($user_id, $page_id, '" . escape_data($notes, $dbc) . "')";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) > 0) {
echo '<div class="alert alert-success">Your notes have been saved.</div>';
}
}
}
// Get the existing notes, if any:
echo '<form id="notes_form" action="page.php?id=' . $page_id . '" method="post" accept-charset="utf-8">
<fieldset><legend>Your Notes</legend>
<textarea name="notes" id="notes" class="form-control">';
if (isset($notes) && !empty($notes)) echo htmlspecialchars($notes);
echo '</textarea><br>
<input type="submit" name="submit_button" value="Save" id="submit_button" class="btn btn-default" />
</fieldset>
</form>';
} elseif (isset($_SESSION['user_id'])) { // Logged in but not current.

echo '<div class="alert"><h4>Expired Account</h4>Thank you for your interest in this content, but your account is no longer current. Please <a href="renew.php">renew your account</a> in order to view this page in its entirety.</div>';
echo '<div>' . htmlspecialchars($row['description']) . '</div>';
} else { // Not logged in.
echo '<div class="alert">Thank you for your interest in this content. You must be logged in as a registered user to view this page in its entirety.</div>';
echo '<div>' . htmlspecialchars($row['description']) . '</div>';
}
} else { // No valid ID.
$page_title = 'Error!';
include('includes/header.php');
echo '<div class="alert alert-danger">This page has been accessed in error.</div>';
} // End of primary IF.

echo '<script type="text/javascript">
var page_id = ' . $page_id . ';
</script>
<script src="js/favorite.js"></script>
<script src="js/notes.js"></script>';
// Include the HTML footer:
include('./includes/footer.html');
?>

Step-5:

Create add_pdf.php file under html folder and add the following content.


<?php


require('./includes/config.php');
// If the user isn't logged in as an administrator, redirect them:
redirect_invalid_user('user_admin');
// Require the database connection:
require(MYSQL);
// Include the header file:
$page_title = 'Add a PDF';
include('./includes/header.php');
// For storing errors:
$add_pdf_errors = array();
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check for a title:
if (!empty($_POST['title'])) {
$t = escape_data(strip_tags($_POST['title']), $dbc);
} else {
$add_pdf_errors['title'] = 'Please enter the title!';
}

// Check for a description:
if (!empty($_POST['description'])) {
$d = escape_data(strip_tags($_POST['description']), $dbc);
} else {
$add_pdf_errors['description'] = 'Please enter the description!';
}

// Check for a PDF:
if (is_uploaded_file($_FILES['pdf']['tmp_name']) && ($_FILES['pdf']['error'] === UPLOAD_ERR_OK)) {
// Get a reference:
$file = $_FILES['pdf'];
// Find the size:
$size = ROUND($file['size']/1024);
// Validate the file size (5MB max):
if ($size > 5120) {
$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
}

// Create the resource:
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
// Check the file:
if (finfo_file($fileinfo, $file['tmp_name']) !== 'application/pdf') {
$add_pdf_errors['pdf'] = 'The uploaded file was not a PDF.';
}

// Close the resource:
finfo_close($fileinfo);
// Move the file over, if no problems:
if (!array_key_exists('pdf', $add_pdf_errors)) {
// Create a tmp_name for the file:
$tmp_name = sha1($file['name']) . uniqid('',true);
// Move the file to its proper folder but add _tmp, just in case:
$dest = PDFS_DIR . $tmp_name . '_tmp';
if (move_uploaded_file($file['tmp_name'], $dest)) {
// Store the data in the session for later use:
$_SESSION['pdf']['tmp_name'] = $tmp_name;
$_SESSION['pdf']['size'] = $size;
$_SESSION['pdf']['file_name'] = $file['name'];

// Print a message:
echo '<div class="alert alert-success"><h3>The file has been uploaded!</h3></div>';
} else {
trigger_error('The file could not be moved.');
unlink ($file['tmp_name']);
}

} // End of array_key_exists() IF.
} elseif (!isset($_SESSION['pdf'])) { // No current or previous uploaded file.
switch ($_FILES['pdf']['error']) {
case 1:
case 2:
$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
break;
case 3:
$add_pdf_errors['pdf'] = 'The file was only partially uploaded.';
break;
case 6:
case 7:
case 8:
$add_pdf_errors['pdf'] = 'The file could not be uploaded due to a system error.';
break;
case 4:
default:
$add_pdf_errors['pdf'] = 'No file was uploaded.';
break;
} // End of SWITCH.
} // End of $_FILES IF-ELSEIF-ELSE.
if (empty($add_pdf_errors)) { // If everything's OK.
// Add the PDF to the database:
$fn = escape_data($_SESSION['pdf']['file_name'], $dbc);
$tmp_name = escape_data($_SESSION['pdf']['tmp_name'], $dbc);
$size = (int) $_SESSION['pdf']['size'];
$q = "INSERT INTO pdfs (title, description, tmp_name, file_name, size) VALUES ('$t', '$d', '$tmp_name', '$fn', $size)";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
// Rename the temporary file:
$original = PDFS_DIR . $tmp_name . '_tmp';
$dest = PDFS_DIR . $tmp_name;
rename($original, $dest);
// Print a message:
echo '<div class="alert alert-success"><h3>The PDF has been added!</h3></div>';
// Clear $_POST:
$_POST = array();
// Clear $_FILES:
$_FILES = array();
// Clear $file and $_SESSION['pdf']:
unset($file, $_SESSION['pdf']);
} else { // If it did not run OK.
trigger_error('The PDF could not be added due to a system error. We apologize for any inconvenience.');
unlink ($dest);
}

} // End of $errors IF.
} else { // Clear out the session on a GET request:
unset($_SESSION['pdf']);
} // End of the submission IF.
// Need the form functions script, which defines create_form_input():
require('includes/form_functions.php');
?><h1>Add a PDF</h1>
<form enctype="multipart/form-data" action="add_pdf.php" method="post" accept-charset="utf-8">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
<?php

create_form_input('title', 'text', 'Title', $add_pdf_errors);
create_form_input('description', 'textarea', 'Description', $add_pdf_errors);
// Add the file input:
echo '<div class="form-group';
// Add classes, if applicable:
if (array_key_exists('pdf', $add_pdf_errors)) {
echo ' has-error';
} else if (isset($_SESSION['pdf'])) {
echo ' has-success';
}

echo '"><br/><label for="pdf" class="control-label">PDF&nbsp;&nbsp;&nbsp;</label><input type="file" name="pdf" id="pdf">';
// Check for an error:
if (array_key_exists('pdf', $add_pdf_errors)) {
echo '<span class="help-block">' . $add_pdf_errors['pdf'] . '</span>';
} else { // No error.
// If the file exists (from a previous form submission but there were other errors),
// store the file info in a session and note its existence:
if (isset($_SESSION['pdf'])) {
echo '<p class="lead">Currently: "' . $_SESSION['pdf']['file_name'] . '"</p>';
}
 } // end of errors IF-ELSE.
echo '<span class="help-block">PDF only, 5MB Limit</span>
</div>';
?>
<input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-primary" />
</fieldset>
</form>
<?php // Include the HTML footer:
include('./includes/footer.html');
?>

Step-6:

Create pdf.php file under html folder and add the following content.


<?php

require('./includes/config.php');
// The config file also starts the session.
// Require the database connection:
require(MYSQL);
// Include the header file:
$page_title = 'PDFs';
include('./includes/header.php');
// Print a page header:
echo '<h1>PDF Guides</h1>';


// Get the PDFs:
$q = 'SELECT tmp_name, title, description, size FROM pdfs ORDER BY date_created DESC';
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) { // If there are some...
// Fetch every one:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
// Display each record:
echo '<div><h4><a href="view_pdf.php?id=' . htmlspecialchars($row['tmp_name']) . '">' . htmlspecialchars($row['title']) . ' </a> (' . $row['size'] . 'kb)</h4><p>' . htmlspecialchars($row['description']) . '</p></div>';
} // End of WHILE loop.
} else { // No PDFs!
echo '<div class="alert alert-danger">There are currently no PDFs available to view. Please check back again!</div>';
}
// Include the HTML footer:
include('./includes/footer.html');

?>

Step-7:

Create view_pdf.php file under html folder and add the following content.


<?php

require('./includes/config.php');
// Require the database connection:
require(MYSQL);
// Assume invalid info:
$valid = false;
// Validate the PDF ID:
if (isset($_GET['id']) && (strlen($_GET['id']) === 63) && (substr($_GET['id'], 0, 1) !== '.') ) {
// Identify the file:
$file = PDFS_DIR . $_GET['id'];
// Check that the PDF exists and is a file:
if (file_exists ($file) && (is_file($file)) ) {
// Get the info:
$q = 'SELECT id, title, description, file_name FROM pdfs WHERE tmp_name="' . escape_data($_GET['id'], $dbc) . '"';
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) === 1) { // OK!
// Fetch the info:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Indicate that the file reference is fine:
$valid = true;
// Only display the PDF to a user whose account is active:
if (isset($_SESSION['user_not_expired'])) {

// Send the content information:
header('Content-type:application/pdf');
header('Content-Disposition:inline;filename="' . $row['file_name'] . '"');
$fs = filesize($file);
header("Content-Length:$fs\n");
// Send the file:
readfile ($file);
exit();

} else { // Inactive account!

// Display an HTML page instead:
$page_title = $row['title'];
include('./includes/header.php');
echo "<h1>$page_title</h1>";

// Complete the page:
echo '<div>' . htmlspecialchars($row['description']) . '</div>';
include('./includes/footer.html');
} // End of user IF-ELSE.
} // End of mysqli_num_rows() IF.
} // End of file_exists() IF.
} // End of $_GET['id'] IF.

// If something didn't work...
if (!$valid) {
$page_title = 'Error!';
include('./includes/header.php');
echo '<div class="alert alert-danger">This page has been accessed in error.</div>';
include('./includes/footer.html');
}
?>

***Reference: Main code has taken from effortless e-commerce with PHP and MySQL book.