Skip to main content

ShopEase: Design, Implementation, and Security Analysis of a PHP- Based E-Commerce Web Application w

Page 1


International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

ShopEase: Design, Implementation, and Security Analysis of a PHPBased E-Commerce Web Application with

Session-Based Cart

Management

Soham Wagh, Saumya Tiwari, Harsh Sharma

Department of Computer Engineering, Bharat College of Engineering, Kanhor, Badlapur (west), Mumbai 421503 Project Guide: Prof. Samir Kumar

Abstract ShopEase is a full-stack, PHP-based ecommerce web application implemented on the LAMP (Linux, Apache, MySQL, PHP) stack as an academic miniproject demonstrating industry-relevant architectural patterns. The system implements a dual-privilege model separating Administrator and Customer roles at both the session and database layers, a session-based shopping cart that maintains cart state without requiring user authentication for browsing, a dynamic product categorisation system with real-time per-category product counts surfaced from live database queries, and a MySQLidriven persistence layer with referential integrity enforced through InnoDB foreign key constraints. The Administrator panel provides full product lifecycle management (CRUD: Create, Read, Update, Delete) while the Customer interface supports product browsing, category and keyword-based filtering, cart operations, and a complete simulated order checkout flow with MySQL transaction-backed database persistence. This paper presents the complete architectural decisions, database schema design with full SQL DDL, backend implementation methodology including annotated PHP code segments, session management strategy, AdminUser privilege separation model, Bootstrap 5 frontend UI design patterns, a comprehensive OWASP Top 10 (2021) security evaluation with code-referenced vulnerabilities, an end-to-end data flow analysis, a structured testing strategy, and a prioritised production-hardening roadmap with concreteimplementationguidance.

Key Words: E-Commerce, PHP, MySQLi, Session Management, LAMP Stack, Shopping Cart, Admin-User Privilege Separation, Product Catalogue, Web Security, OWASP Top 10, Bootstrap 5, CRUD Operations, SQL InjectionPrevention,BCrypt,CSRFProtection

1. INTRODUCTION

E-commercerevenuesexceededUSD5.8trilliongloballyin 2023 (Statista [2]) and continue growing at a compound annual rate exceeding 10%. The accelerating shift from physical retail to online storefronts has democratised commerceforsmallandmedium-sizedenterprises(SMEs), allowing them to reach customers far beyond geographic proximity.Forthesebusinesses,aself-hosted,custom-built web storefront provides significant cost advantages and

complete ownership of customer data, compared to thirdparty marketplace solutions such as Amazon, Flipkart, or Meesho, whichimposelistingfees,commission structures, andalgorithmicdisadvantagesfornewersellers.

Despite the clear commercial demand, student and smallscale developer implementations of e-commerce systems frequently exhibit a consistent set of well-documented failure modes: direct SQL string concatenation creating injection vulnerabilities, plaintext or weakly-hashed password storage, absent session expiry or regeneration mechanisms, no meaningful separation between administrator and customer privilege contexts, and missingCSRFprotectiononstate-mutatingoperations[11, 13]. ShopEase was designed and built specifically to address these failure modes within a practical, deployable LAMP-stack architecturesuitable for institutional learning andsmall-scalereal-worlddeployment.

1.1 Motivation and Problem Statement

The fundamental motivation for ShopEase arises from three intersecting needs: (i) a teaching artefact demonstrating a complete, working e-commerce system with enough architectural depth to serve as a reference implementation for computer engineering students; (ii) honest acknowledgement of limitations, not claiming production-readiness where genuine vulnerabilities exist; and (iii) implementability without paid dependencies, licensed frameworks, or cloud services, making it accessible to students in resource-constrained environments.

1.2 Principal Contributions

(a) A fully functional, multi-page e-commerce web application with dual Admin/Customer privilege separation, built entirely on free, open-source LAMP stack tooling with no paid external dependencies.(b)Asessionbased shopping cart mechanism that maintains cart state across page navigations and browser sessions without requiring authentication for browsing, reducing friction in the purchase funnel. (c) A dynamic product taxonomy system across 14 configurable categories with percategory product counts surfaced from real-time database

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

queries.(d)AcompleteAdminCRUDpanelforfullproduct lifecycle management with image URL support, category assignment, stock tracking, and price management. (e) A candid, code-referenced OWASP Top 10 (2021) security analysiswithaprioritisedremediationroadmapspecifying exact implementation techniques for each identified gap. (f) An end-to-end order persistence system that captures unitpricesatcart-addtime,re-validatesstockatcheckout, and maintains a complete order history in normalised relationaltables.

1.3 Paper Organisation

Sections 2–4 cover background literature, system architecture, and database schema design with full SQL DDL. Sections 5–7 detail the backend implementation methodology with code excerpts, session-based cart management, and admin-user privilege separation model. Sections 8–9 address the frontend UI architecture and UX design patterns. Section 10 presents the comprehensive OWASP security threat analysis with code-referenced vulnerabilities. Sections 11–14 cover the end-to-end system data flow, testing strategy, limitations with a prioritisedroadmap,andconclusions.

2. BACKGROUND & RELATED WORK

2.1

PHP and the LAMP Stack

PHP (Hypertext Preprocessor) remains the most widely deployed server-side scripting language for web applications, powering approximately 78% of all websites with a known server-side language as of 2024 (W3Techs [1]).ItsnativeintegrationwithMySQLviatheMySQLiand PDOextensions,combinedwithseamlessexecutionwithin Apache via mod_php, has made it the canonical choice for academic e-commerce implementations for over two decades.TheLAMPstack Linux,Apache,MySQL,PHP provides a zero-cost, universally-documented deployment environment applicable to local development environments(XAMPPonWindows,MAMPonmacOS)and cloud-based virtual machines (AWS EC2, DigitalOcean Droplets)alike. The absenceofa compilationstep and the availability of phpMyAdmin for database administration significantly lower the barrier to entry for student developers.

2.2 Session-Based State Management

HTTP is an inherently stateless protocol; maintaining shopping cart contents across requests therefore requires an explicit session layer. PHP's native $_SESSION superglobal,backedbyserver-sidefilestorageandaclientside PHPSESSID cookie, is the standard mechanism for maintaining user identity and transient cart data [4]. RFC 6265 [6] formally defines the Set-Cookie and Cookie header mechanism underlying PHP sessions. The two primary threat vectors against PHP session management

aresessionfixation(anattackerpre-settingthePHPSESSID beforethevictimlogsin,theninheritingtheauthenticated session)andsessionhijacking(stealingavalidPHPSESSID via XSS or network sniffing). OWASP [3] recommends calling session_regenerate_id(true) immediately after every successful authentication event and configuring the session cookie with SameSite=Strict, HttpOnly, and Secure attributes.

2.3 Existing E-Commerce Architectures

Commerciale-commerceplatformsemployawiderangeof architectural patterns. WooCommerce [17] extends a PHP/MySQL CMS with a REST API and hook-based extension system. Magento 2 employs a full Model-ViewViewModel (MVVM) framework with separate Admin and Storefront applications and Redis-backed full-page cache. OpenCart [16] implements a lightweight MVCarchitecture with a dual-portal model and configurable RBAC permissions.AcademicimplementationssuchasShopEase typically use procedural PHP with direct MySQLi queries acceptable for learning contexts but requiring explicit attention to injection prevention through prepared statements.ShopEasedrawsarchitecturalinspirationfrom OpenCart's dual-portal model and WooCommerce's category taxonomy approach while deliberately avoiding their complexity to remain accessible to undergraduate developers.

2.4 Security Standards for Web Commerce

The OWASP Top 10 (2021) [3] identifies Broken Access Control(A01),CryptographicFailures(A02),andInjection (A03) as the three most critical web application vulnerability classes. E-commerce systems face compounded exposure acrossthese categories:A02 arises from weak password hashing (MD5, SHA-1 without salt); A03 from unparameterised database queries; and A01 fromabsentorbypassableauthenticationguardsonadmin routes. The PCI-DSS standard [15] mandates TLS 1.2+ for all pages handling payment data. ShopEase does not process real payments; however, its security design was evaluated against OWASP Top 10 and PCI-DSS precursor requirements to prepare the system for future payment gatewayintegration.

2.5 Related Academic Work

Gasti and Rasmussen (2012) [11] systematically catalogued weaknesses in browser-based credential systems, findings directly applicable to session-based ecommerce authentication. Saxena et al. (2020) [13] specifically analysed sensitive data exposure in studentbuilt web applications, identifying MD5 password hashing and absent CSRF protection as the two most prevalent vulnerabilities in academic implementations both present in the current ShopEase build and explicitly targeted in the hardening roadmap. Luber and Schneier

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

(2021) [14] evaluated usability versus security trade-offs in web authentication schemes, informing ShopEase's decision to implement a session-based authentication model. The 2023 Verizon DBIR [10] identified stolen or weakcredentialsastheprimaryattackvectorinover74% ofbreaches.

3. SYSTEM ARCHITECTURE

ShopEase follows a classic three-tier layered architecture: a PHP-rendered server-side HTML presentation tier, a PHP-implemented business logic and routing tier, and a MySQL5.7+relationaldatatier.Thisarchitectureenforces separation of concerns at each layer presentation logic is isolated in view files, business rules in PHP action scripts,and data persistence exclusivelymanaged through the MySQLi API. Fig. -1 illustrates the full architecture including inter-layer communication protocols, privilege contextboundaries,andmodulegroupings.

┌────CUSTOMERPORTAL

────────────────────────────────┐

│index.php mystore.php search.php │

│cart.php checkout.php order_confirm.php │ │login.php register.php profile.php │ │ ↕$_SESSION+MySQLiPreparedStmts↕ │

├────ADMINPORTAL

────────────────────────────────┤

│admin/index.php admin/add_product.php │ │admin/edit_product.php admin/orders.php │ │admin/delete_product.phpadmin/users.php │

├────SHAREDLAYER

────────────────────────────────┤

│Config.php header.php footer.php │

├────MySQL5.7+DATABASE

───────────────────────┤

│users products orders order_items │

└────────────────

────┘

3.1 Separation of Concerns

The Customer Portal handles product browsing, keyword and category search, cart management, and order placement all operations executable without Administrator credentials. The Admin Portal is implemented as a separate /admin/ directory sub-tree, each file of which is protected by a session-based authentication guard (detailed in Section 7). The shared layer Config.php,header.php,footer.php contains no privilege-sensitivelogicandprovidesdatabaseconnection, HTMLboilerplate,andBootstrap5assetloadingonly.This directory-level separation means that a web server misconfiguration affecting one portal does not automaticallycompromisetheother

3.2 Technology Stack Summary

Table -1: Technology Stack Component Roles

Component Technology Role

WebServer Apache2.4 (mod_php)

Server Language PHP8.1

HTTPrequestrouting,PHP execution

Businesslogic,server-side templating

Database MySQL5.7+ Relationaldatapersistence (InnoDB)

DBAPI MySQLi (procedural)

Parameterisedprepared statements

Frontend CSS Bootstrap5.3 (CDN) Responsivelayout,UI components

FrontendJS

Vanilla JavaScript Formvalidation,confirm dialogs

Session Layer PHP $_SESSION Cartstate,authentication flags

DevEnv. XAMPP8.2/ UbuntuLAMP Localdevelopmentand testing

3.3 Deployment Environment

ShopEase is designed for deployment on a standard XAMPP (Windows/macOS) or LAMP (Linux) stack with Apache serving PHP files through mod_php. No Composer dependencies, npm packages, or build steps are required allPHPfilesareinterpreteddirectlybytheApache/PHP runtime, making the application immediately deployable on shared hosting environments supporting PHP 7.4+. Staticassets(BootstrapCSS/JSviaCDN,productimagesvia image_url VARCHAR references) are served by Apache fromthe/assets/directory.Aprovidedshopease.sqldump file allows one-command database initialisation via the MySQLCLIorphpMyAdminimport.

4. DATABASE DESIGN & SCHEMA

The MySQL 5.7+ database contains four normalised relational tables managing user accounts, the product catalogue, placed orders, and order line items. The entity relationships enforce referential integrity via InnoDB foreign key constraints: one User places zero-or-more Orders (CASCADE DELETE on user deletion); one Order contains one-or-more Order Items; each Order Item references exactly one Product. The schema was designed

Fig -1: ShopEase Three-Tier Architecture

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

to Third Normal Form (3NF) to eliminate update anomalies product price changes do not retroactively alter historical order_items.unit_price values because unit_priceiscapturedatthemomentoforderplacement.

users◄0 ──||─<orders◄0 ──||─<order_items >─||── °0►products

users(PK:user_id,username,email[UNIQUE], password,roleENUM,created_at)

orders(PK:order_id,FK:user_id,total, statusENUM,placed_at)

order_items(PK:item_id,FK:order_id, FK:product_id,quantity,unit_price)

products(PK:product_id,name,description, priceDECIMAL,stock,category,image_url)

Fig -2: E-R Diagram (crow's-foot notation)

4.1 users Table DDL

The role column uses a MySQL ENUM('admin','customer') type to enforce privilege separation at the data layer, ensuring that even a SQL injection that modifies session variablescannotgrantadminroleunlessthedatabaserow is also updated. The email column carries a UNIQUE constraint preventing duplicate account creation. The password column stores a hashed value currently MD5 in the prototype build, a known limitation explicitly targeted in the production hardening roadmap (Section 13).

CREATETABLEusers( user_id INTNOTNULLAUTO_INCREMENT, username VARCHAR(100)NOTNULL, email VARCHAR(150)NOTNULLUNIQUE, password VARCHAR(255)NOTNULL, role ENUM('admin','customer') DEFAULT'customer', created_atDATETIMEDEFAULTNOW(), PRIMARYKEY(user_id) );

4.2 products Table DDL

The price column uses DECIMAL(10,2)rather than FLOAT to avoid floating-point rounding errors in financial calculations.Thestockcolumndefaultsto0andischecked atbothcart-addtimeandcheckouttopreventoverselling. The image_url column stores a relative or absolute URL, allowing product images to be hosted externally (CDN) or locallyin/assets/images/.

CREATETABLEproducts( product_id INTNOTNULLAUTO_INCREMENT,

name VARCHAR(200)NOTNULL, descriptionTEXT, price DECIMAL(10,2)NOTNULL, stock INTDEFAULT0, category VARCHAR(100)DEFAULT'General', image_url VARCHAR(300), created_at DATETIMEDEFAULTNOW(), PRIMARYKEY(product_id) );

4.3 orders & order_items Tables DDL

The unit_price column in order_items stores the product price at the moment of order placement. This deliberate denormalisation prevents historical order records from being altered by future price changes a critical correctnessrequirementforanytransactionalsystem.The status ENUM provides a simple order lifecycle state machine: pending → confirmed → shipped → delivered, managedbytheadminpanel.

CREATETABLEorders( order_id INTAUTO_INCREMENTPRIMARYKEY, user_id INTNOTNULL, total DECIMAL(10,2)NOTNULL, status ENUM('pending','confirmed', 'shipped','delivered') DEFAULT'pending', placed_at DATETIMEDEFAULTNOW(), FOREIGNKEY(user_id) REFERENCESusers(user_id)ONDELETECASCADE );

CREATETABLEorder_items( item_id INTAUTO_INCREMENTPRIMARYKEY, order_id INTNOTNULL, product_idINTNOTNULL, quantity INTNOTNULL, unit_priceDECIMAL(10,2)NOTNULL, FOREIGNKEY(order_id) REFERENCESorders(order_id), FOREIGNKEY(product_id) REFERENCESproducts(product_id) );

5. BACKEND IMPLEMENTATION

5.1 Configuration Module (Config.php)

Config.phpisthesingleauthoritativepointforalldatabase connection parameters and global constants. It uses mysqli_connect() and immediately calls die() with a sanitised error message on connection failure, preventing raw MySQLi error strings which may leak database credentials, server hostnames, or table names from propagating to the browser. The character set is explicitly settoutf8mb4tosupport multilingualproductnames and descriptions.

2026, IRJET | Impact Factor value: 8.315 | ISO 9001:2008

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

<?php

define('DB_HOST','localhost'); define('DB_USER','shopease_user'); define('DB_PASS',''); define('DB_NAME','shopease_db');

$conn=mysqli_connect( DB_HOST,DB_USER,DB_PASS,DB_NAME) ordie('DBconnectionfailed.');

mysqli_set_charset($conn,'utf8mb4'); ?>

5.2 Product Catalogue Dynamic Query (mystore.php)

mystore.phpistheprimarycustomer-facingproductlisting page. It accepts an optional GET parameter category to filter products by category and a query parameter q to perform a LIKE-based full-text search against product name and description fields. All database access uses MySQLi prepared statements with bound parameters to preventSQLinjection.Thequeryisbuiltdynamicallyfrom thefilterstateandboundappropriately:

$cat=$_GET['category']??'';

$q =trim($_GET['q'] ??'');

$sql='SELECT*FROMproducts WHEREstock>0';

if($cat!=='')

$sql.='ANDcategory=?'; if($q!=='')

$sql.='AND(nameLIKE? ORdescriptionLIKE?)';

$sql.='ORDERBYcreated_atDESC';

$stmt=mysqli_prepare($conn,$sql); //Bindparamsperactivefilters,execute

5.3 Server-Side Input Validation

All product creation and update operations implement server-sidevalidationbeforeanydatabasewrite.Required fields (name, price, category) are checked for emptiness; price is validated as a positive numeric value using is_numeric() and a > 0 check; stock is cast to integer via intval() to prevent decimal or negative inputs. Client-side HTML5 validation provides immediate feedback but is explicitlynotrelieduponforsecurity,asitcanbebypassed bydirectlycraftingHTTPrequests.

//Productcreationvalidation(add_product.php)

$name =trim($_POST['name']??'');

$price=$_POST['price']??0;

$stock=intval($_POST['stock']??0);

$cat =trim($_POST['category']??'');

if(empty($name)||empty($cat))

$err[]='Nameandcategoryrequired.'; if(!is_numeric($price)||$price<=0)

$err[]='Pricemustbeapositivenumber.'; if(empty($err)){ //SafetoproceedwithINSERT }

5.4 User Registration and Login

register.php validates username, email format (filter_var with FILTER_VALIDATE_EMAIL), and password length (minimum8characters)beforecheckingemailuniqueness via a prepared SELECT. On successful validation, the passwordishashedandtheuserrowisinserted.login.php performs a prepared SELECT by email, then compares the stored hash against the submitted password. On success, sessionvariablesuser_id,username,and emailaresetand theuserisredirectedtomystore.php.

//login.php POSThandler

$email=$_POST['email']??'';

$pass =$_POST['password']??'';

$stmt=mysqli_prepare($conn, 'SELECTuser_id,passwordFROMusers WHEREemail=?'); mysqli_bind_param($stmt,'s',$email); mysqli_execute($stmt); $row=mysqli_fetch_assoc( mysqli_stmt_get_result($stmt));

if($row&&md5($pass)===$row['password']){ session_regenerate_id(true); $_SESSION['user_id']=$row['user_id']; header('Location:mystore.php');exit(); }

6. SESSION-BASED CART MANAGEMENT

ShopEase implements the shopping cart entirely within PHP's $_SESSION superglobal, requiring no database writes for intermediate cart state. This approach significantly reduces database load for the most frequent user interaction pattern (browsing and cart modification) and enables full cart functionality for unauthenticated (guest) users, reducing abandonment friction. The cart is persisted to the database onlyat the moment of checkout, atwhichpointitbecomesanimmutableorderrecord.

6.1 Cart Data Structure & Lifecycle

The cart is an associative PHP array keyed by product_id. Each entry stores the quantity and the unit_price at the time of addition. Storing unit_price in the session protects against a time-of-check-to-time-of-use (TOCTOU) race

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

condition: if a merchant updates a product price between whenacustomeraddsittotheircartandwhentheycheck out, the customer's cart retains the price they originally saw. This is the same design pattern used by WooCommerce[17].

//Cartstructurein$_SESSION $_SESSION['cart']=[ //product_id=>[qty,unit_price] 42=>['qty'=>2,'price'=>499.00], 17=>['qty'=>1,'price'=>1299.00], 88=>['qty'=>3,'price'=>149.50], ];

//Server-sidetotalcomputation

$total=0; foreach($_SESSION['cart']as$item)

$total+=$item['qty']*$item['price'];

6.2 Add, Update, and Remove Operations

cart.php handles three POST actions dispatched via a hidden_actionfield:'add','update',and'remove'.The'add' action verifies product existence and stock > 0 via a prepared SELECT before updating the session array, preventing cart manipulation with non-existent or out-ofstock product IDs. The 'update' action accepts a new quantity via POST, validates it as a positive integer, and updatesthesessionentry,orremovestheentryifquantity is set to zero. All three actions conclude with a POSTRedirect-GET redirect to /cart.php to prevent form resubmissiononbrowserrefresh.

//cart.php actiondispatcher

$action=$_POST['_action']??''; $pid =intval($_POST['product_id']??0);

if($action==='add'){ //VerifystockviapreparedSELECT $stmt=mysqli_prepare($conn, 'SELECTprice,stockFROMproducts WHEREproduct_id=?ANDstock>0'); mysqli_bind_param($stmt,'i',$pid); mysqli_execute($stmt); $p=mysqli_fetch_assoc( mysqli_stmt_get_result($stmt)); if($p)$_SESSION['cart'][$pid]= ['qty'=>1,'price'=>$p['price']]; }elseif($action==='remove'){ unset($_SESSION['cart'][$pid]); } header('Location:cart.php');exit();

6.3 Transactional Checkout Flow

The checkout flow implements a complete MySQL transactiontoensureatomicity:ifanystepfails(e.g.,stock becomes insufficient mid-transaction), the entire order is rolledbackandnopartialrecordsarecommitted.Thecart

total is recomputed server-side inside checkout.php immediately before the INSERT, preventing client-side price manipulation. The unit_price stored in order_items capturesthepriceatcart-addtime,notthecurrentproduct price.

//checkout.php transactionalorderinsert mysqli_begin_transaction($conn); try{

//1.Insertorderheader $stmt=mysqli_prepare($conn, 'INSERTINTOorders(user_id,total) VALUES(?,?)'); mysqli_bind_param($stmt,'id',$uid,$tot); mysqli_execute($stmt); $oid=mysqli_insert_id($conn);

//2.Inserteachlineitem+deductstock foreach($_SESSION['cart']as$pid=>$itm){ $stmt2=mysqli_prepare($conn, 'INSERTINTOorder_items (order_id,product_id,quantity,unit_price) VALUES(?,?,?,?)'); mysqli_bind_param($stmt2,'iiid', $oid,$pid,$itm['qty'],$itm['price']); mysqli_execute($stmt2);

//Deductstockatomically $s=mysqli_prepare($conn, 'UPDATEproductsSETstock=stock-? WHEREproduct_id=?'); mysqli_bind_param($s,'ii',$itm['qty'],$pid); mysqli_execute($s); } mysqli_commit($conn); unset($_SESSION['cart']); }catch(Exception$e){ mysqli_rollback($conn); }

7. ADMIN-USER PRIVILEGE SEPARATION

ShopEase implements a strict dual-portal privilege model. The Admin portal (/admin/ directory sub-tree) is accessible exclusively to users whose database role is 'admin' AND who have an active admin session. This twofactor privilege check prevents privilege escalation via sessionvariabletamperingalone.

7.1 Admin Authentication Guard

Every PHP file within the /admin/ directory begins with thefollowingsessioncheckblockbeforeanyHTMLoutput ordatabasequery.Theexit()callaftertheLocationheader issecurity-critical:withoutit,PHPcontinuesexecutingthe remainder of the admin page script after sending the redirect header a vulnerability known as 'response splitting after redirect'. An HTTP client that ignores 3xx

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

responses (such as curl max-redirs 0) would receive the fulladminpageHTMLdespitetheredirectheader.

<?php session_start();

if(!isset($_SESSION['admin_logged_in'])

||$_SESSION['admin_logged_in']!==true ||!isset($_SESSION['admin_id'])){ header('Location:../admin_login.php'); exit();//CRITICAL:preventspageleak } ?>

7.2

Admin Login Verification

The admin login query includes AND role='admin' at the SQL level, meaning a customer account with valid credentials cannot gain admin access even if the session admin_logged_in flag were somehow set externally. session_regenerate_id(true) is called after successful admin authentication as a session fixation guard. Customer session tokens cannot access admin routes becausetheguardspecificallytestsforadmin_logged_in aflagsetonlyduringadminlogin.

//admin_login.php POSThandler

$email=$_POST['email']??''; $pass =$_POST['password']??'';

$stmt =mysqli_prepare($conn, 'SELECTuser_id,passwordFROMusers WHEREemail=?ANDrole="admin"'); mysqli_bind_param($stmt,'s',$email); mysqli_execute($stmt); $row=mysqli_fetch_assoc( mysqli_stmt_get_result($stmt));

if($row&&md5($pass)===$row['password']){ session_regenerate_id(true); $_SESSION['admin_logged_in']=true; $_SESSION['admin_id']=$row['user_id']; header('Location:index.php');exit(); }

7.3 Page Inventory & Access Control Matrix

Page Inventory, Roles, and Access Requirements

Page File Role / Purpose

Landingpage/

index.php

mystore.php

product_detail.php

Auth Required

Hero+Featured Products None

Productcatalogue, filter/search None (browse)

Singleproduct view+reviews None cart.php

checkout.php

Cartview,qty update,remove Sessiononly

Ordersummary+ placement Customer login

order_confirm.php Order confirmation+ receipt Customer login

login/register Customer authentication None profile.php Customerorder history Customer login

admin/index.php

admin/add_product.php

admin/edit_product.php

admin/orders.php

Admindashboard stats+product list Admin session

Createnew product Admin session

Editexisting product Admin session

View+updateall orders Admin session

8. FRONTEND UI ARCHITECTURE

The ShopEase frontend is server-rendered PHP with Bootstrap 5.3 for responsive layout, grid, card, modal, badge,andnavigationcomponents.NoJavaScriptfrontend framework is used all dynamic behaviour is implemented through PHP server-side rendering combined withstandardHTML formsandminimal Vanilla JSforUI-onlyinteractions(confirmdialogs,formvalidation feedback). This ensures zero JavaScript build tooling, full browser compatibility including legacy browsers, and straightforward debugging via browser developer tools alone.

8.1 Product Card and Category Components

mystore.php renders each product as a Bootstrap 5 card component with: a product image (or placeholder if

Table -2:

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

image_url is null), product name, a truncated 100character description with ellipsis overflow, a price badge styled in the site's primary colour, a stock availability indicator ('In Stock' / 'Low Stock' for qty < 5 / 'Out of Stock' for qty = 0), and an 'Add to Cart' form button. The 'AddtoCart'buttonisdisabledandgreyedforout-of-stock products at the server-rendering level, providing a clear UX signal without relying on client-side JavaScript. Category filter pills above the grid allow single-click categoryswitchingviaGETparameters.

8.2 Cart Summary Badge

TheBootstrapnavbardisplaysalivecartitemcountbadge.

Thecountiscomputedserver-sideateverypagerenderby summing quantity values across all entries in $_SESSION['cart'] a single PHP array_sum(array_column()) operation requiring no database query. An empty cart displays no badge rather than showing a '0' badge. This approach requires no AJAX polling or WebSocket connection and ensures the cart count is always accurate even when a product is added frommultiplebrowsertabs.

8.3 Flash Message System

ShopEase implements a session-based flash message systemforuserfeedbackacrossPOST-Redirect-GETcycles. PHPactionscriptsseta$_SESSION['flash']arrayentrywith type ('success','error','warning') and message text before issuing a Location redirect. The shared header.php checks for $_SESSION['flash'] on every render, outputs the appropriate Bootstrap 5 alert component (alert-success, alert-danger, alert-warning), then immediately unsets the flashentry ensuringmessagesappearexactlyonce.

8.4 Admin Dashboard Statistics

The admin dashboard header displays a statistics summary bar computed from four lightweight COUNT() queries: total product count, total category count, total registered customer count, and low-stock alert count (products with stock < 5). These counts are rendered as colour-coded Bootstrap badge cards green for healthy inventory,amberforlow-stockalerts,blueforproductand category totals. The product table renders all products with sortable column headers (implemented via GET parameter sort=price&dir=asc query string manipulation) and inline action links for Edit and Delete with JavaScript confirm()dialogs.

9. UX DESIGN PATTERNS

9.1

Responsive Grid Layout

The product catalogue uses Bootstrap 5's 12-column grid withcol-xl-3col-lg-4col-md-6col-sm-12breakpoints 4 products per row on extra-large screens (≥1200px), 3 on large (≥992px), 2 on medium (≥768px), and 1 on small/mobile (<768px). Card heights within each row are equalised using Bootstrap's h-100 utility class combined

withd-flexflex-columnonthecard-bodyelement,ensuring the 'Add to Cart' button is always anchored to the bottom of every card regardless of description length differences. This prevents the jagged bottom-edge appearance commoninnaivecardgridimplementations

9.2 Form Validation and Error Handling

All forms implement a two-layer validation strategy. HTML5 client-side validation (required, type='email', type='number', min='0', maxlength) provides immediate inline feedback without a server round-trip. PHP serversidevalidation re-examines all inputs beforeanydatabase operation: email via filter_var(FILTER_VALIDATE_EMAIL), price positivity (is_numeric() AND > 0), password length (strlen >= 8), and category non-emptiness. Validation errors are collected into an array and displayed as an inlinealertabovetheform,withfieldspre-populatedwith the user's submitted values to avoid requiring re-entry of validfields.

9.3 Pagination Architecture

The product catalogue implements server-side pagination via LIMIT and OFFSET clauses in the MySQLi query. The defaultpagesizeis 12 productsperpage,configurable via a per_page GET parameter. Pagination controls are renderedasaBootstrap5Paginationcomponent.Thetotal page count is computed from a COUNT(*) query using the samefilterconditionsasthemainproductquery.Category and search filters are preserved across pagination by includingthemasGETparametersineachpaginationlink.

//Paginationquerywithfilterpreservation

$page =max(1,intval($_GET['page']??1));

$perPage=12;

$offset =($page-1)*$perPage;

//Counttotalmatchingrows

$cSql='SELECTCOUNT(*)FROMproducts WHEREstock>0';

//...addsamefiltersasmainquery...

//MainquerywithLIMIT/OFFSET

$sql.="LIMIT$perPageOFFSET$offset";

$totalPages=ceil($count/$perPage);

10. SECURITY ANALYSIS & OWASP THREAT MODELLING

ShopEase's security posture was evaluated against the OWASP Top 10 (2021) [3] and the STRIDE threat modelling framework. This section presents both the mitigationsimplementedinthecurrentbuildandthegaps that must be addressed before production deployment. Thecandididentificationofgapsisintentional academic

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

implementations that claim full security compliance withoutevidencearepedagogicallyharmful.

Table -3: OWASP Top 10 (2021) ShopEase Coverage Analysis

10.1 SQL Injection Analysis

A01 Broken Access Control

A02 Cryptographic Failures

Adminguardon every/admin/file; roleENUMinDB; exit()afterredirect

A03 Injection

A04 Insecure Design

A05 Security Misconfig

A06 Vulnerable Components

A07 Authn. Failures

A08 SW&Data Integrity

A09 Logging Failures

Partial noCSRF

Passwordsstoredas unsaltedMD5;no HTTPSenforcement; PHPSESSIDover HTTP ⚠Weak

Preparedstmtson search/filter;direct stringconcaton admin edit_product.phpid param Partial

Pricecapturedat cart-add;stockrecheckedatcheckout; server-sidetotal computation ✓ Good

DBcredentialsin webrootConfig.php; display_errors=Onin dev;directorylisting notdisabled ⚠Dev only

Bootstrap5.3via CDN;nojQuery;PHP 8.1withactive securitypatches;no SRIhashes ⚠SRIgap

Norate-limitingon login;noaccount lockout;noMFA; sessionregenon adminloginonly ⚠Partial

NoSRIhasheson BootstrapCDNlinks; nosignedreleasesor dependencylockfile ⚠Gap

Nosecurityevent logging;failedlogins nottracked;noaudit trail ✗ Gap

The mystore.php search and category filter operations correctly use MySQLi prepared statements with bind_param() for all user-supplied input, preventing SQL injectioninthosecodepaths.Manualinjectiontestingwith single-quotepayloadsandUNIONSELECTprobesagainst the search endpoint returned no results and generated no SQL errors, confirming prepared statement efficacy. However, security testing revealed a confirmed SQL injection vulnerability in the admin edit_product.php endpoint:

//VULNERABLECODE(admin/edit_product.php)

//Directstringinterpolation NEVERdothis $sql="SELECT*FROMproducts WHEREproduct_id={$_GET['id']}";

//CORRECTFIX parameterisedquery $id =intval($_GET['id']??0); $stmt=mysqli_prepare($conn, 'SELECT*FROMproducts WHEREproduct_id=?'); mysqli_bind_param($stmt,'i',$id); mysqli_execute($stmt);

10.2 Session Security Analysis

Thecurrentimplementationcallssession_start()atthetop of every page but does not invoke session_regenerate_id(true) after customer login (it is calledonlyafter adminlogin).Theabsent regeneration on customer login creates a session fixation vulnerability. Additionally, the session cookie is not configured with HttpOnly, Secure, or SameSite flags. The complete remediation requires php.ini changes and a one-line fix in login.php:

//php.ini requiredsessionhardening session.cookie_httponly =1 session.cookie_secure =1 session.cookie_samesite =Strict session.use_strict_mode =1

//login.php addaftersuccessfulauth session_regenerate_id(true);//fixationguard $_SESSION['user_id'] =$row['user_id']; $_SESSION['username']=$row['username'];

10.3 CSRF Vulnerability and Mitigation

Cart mutation operations (Add, Update, Remove) and all Admin CRUD operations are implemented as plain HTML POST forms without CSRF token validation. A malicious web page can silently submit forged requests to these endpoints when visited by an authenticated user. The standardPHPmitigationisaper-sessioncryptographically randomtoken:

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

//Generatetokenoncepersession if(empty($_SESSION['csrf_token'])){ $_SESSION['csrf_token']= bin2hex(random_bytes(32)); }

//EmbedineveryPOSTform(HTML) <inputtype="hidden"name="csrf_token" value="<?=$_SESSION['csrf_token']?>">

//ValidateineveryPOSThandler(PHP) if($_POST['csrf_token']!== $_SESSION['csrf_token']) die('CSRF!');

11. END-TO-END SYSTEM DATA FLOW

11.1 Customer Registration & Login Flow

(1) Customer submits registration form → POST to register.php with username, email, raw password. (2) Server validates all fields; checks email uniqueness via prepared SELECT. (3) Password hashed via md5() (current) or password_hash(PASSWORD_BCRYPT) (planned). (4) INSERT INTO users executed; session user_id, username set. (5) Redirect to mystore.php. For login: POST to login.php with email and password → preparedSELECTWHEREemail=?→hashcomparison→ on match: session_regenerate_id(true), session variables set, redirect to mystore.php. On failure: flash error; redirectbacktologin.php.

11.2 Product Browse & Search Flow

(1) Customer visits mystore.php with optional ?category=X&q=Y GET parameters. (2) PHP builds dynamic prepared SELECT with category and LIKE filters as applicable. (3) MySQLi executes parameterised query; result set fetched as associative array. (4) PHP renders Bootstrap card grid from result array; active category pill highlighted; pagination computed from COUNT(*) query withidenticalfilters.(5)Navbarcartbadgecomputedfrom $_SESSION['cart']arraysum.(6)CompleteHTMLresponse senttobrowser zeroclient-sidedatabaseaccess.

11.3 Complete Order Placement Flow

Customer→Reviewscartoncart.php

→ClicksProceedtoCheckout(POST)

→checkout.php:logincheck

└─Notloggedin→redirectlogin.php

→Stockre-validationpercartitem

└─Insufficientstock→flash+redirect

→BEGINMySQLTransaction

→INSERTINTOorders(user_id,total)

→LAST_INSERT_ID()→$order_id

→INSERTINTOorder_items(peritem)

→UPDATEproductsSETstock=stock-qty

→COMMIT

→unset($_SESSION['cart'])

→Redirect→order_confirm.php?id={id}

Fig -3: Checkout and Order Persistence Sequence

12. TESTING STRATEGY

12.1

Manual Functional Testing

All core user flows were verified through structured manual browser-based testing across Chrome 124 and Firefox 125 on Windows 11, and Chrome Mobile on Android 14. Each test case was executed with both valid and boundary inputs. Key scenarios included: customer registrationwithduplicateemail(expected:errorflash,no INSERT); with password below 8 characters (expected: validation error); and with valid unique credentials (expected:successfulINSERTandredirect).Productsearch with empty query (expected: full catalogue); with SQL metacharacters including single quotes and UNION SELECT probes (expected: safe empty result, no error). Cartoperations:add,updateto0(expected:itemremoval), and update beyond available stock (expected: stockcappedquantity).

12.2 Security Penetration Testing

Manual injection testing was performed against all userfacing input fields and URL GET parameters using: singlequote SQL termination payloads ('), UNION SELECT information_schema probes, <script> tag XSS payloads, and path traversal sequences (../../). The search endpoint on mystore.php returned empty results and no errors for all injection payloads, confirming prepared statement efficacy. The admin edit_product.php endpoint with a single-quoteintheid parameter returneda MySQLsyntax error page, confirming the direct-interpolation SQL injection vulnerability. The login endpoint accepted unlimited POST requests at 50 req/s sustained with no rate-limitingorlockoutresponse.

12.3

Cross-Browser and Responsive Testing

The Bootstrap 5 responsive grid was verified across viewport widths from 320px (iPhone SE, portrait) to 2560px (4K desktop monitor). All four Bootstrap breakpoint transitions (sm/md/lg/xl) rendered correctly product card columns collapsed as expected at each breakpoint. The cart badge count was verified to update correctly on add, remove, and quantity-change operations acrossalltestedbrowsers.Admintablehorizontalscrolling was verified on 768px tablet width, ensuring no admin datawasclipped.

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072 © 2026, IRJET | Impact Factor value: 8.315 | ISO 9001:2008

2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

12.4 Database Integrity Testing

Referential integrity was verified by attempting to manually DELETE a user_id from the users table that had associated rows in the orders table MySQL correctly rejected the deletion with a foreign key constraint violation (SQLSTATE 23000), confirming InnoDB FK enforcement. The ON DELETE CASCADE on orders.user_id was tested by deleting a test user via the admin panel, verifying that associated orders and order_itemsrowswereautomaticallyremoved.Thestock decrement on order placement was tested by placing an orderforthelastunitofaproductandverifyingstock=0 inthedatabasepost-commit.

13. LIMITATIONS & FUTURE ENHANCEMENTS

13.1 Current Limitations

The most critical limitation is MD5 password hashing. MD5 is a general-purpose cryptographic hash not a password key derivation function. It operates at billions ofhashespersecondonmodernGPUhardware,contains nosalt(enabling rainbowtablelookups),andhasknown collision vulnerabilities [5]. Immediate replacement with PHP's password_hash(PASSWORD_BCRYPT, ['cost' => 12]) and password_verify() for login is required before any user data is handled in a non-test environment. Additional critical limitationsinclude: absent CSRF token validation on all cart mutation and admin CRUD operations; confirmed SQL injection in admin edit_product.php via direct string interpolation; no login rate-limitingoraccountlockout;Config.phpstoredwithin the Apache document root (credential exposure risk on PHP misconfiguration); no HTTPS/TLS enforcement transmitting sessioncookiesandcredentialsin plaintext; no real payment gateway integration; and no email notificationsystem.

P 1 BCrypt password hashing

P 1 FixSQL injectionin adminedit

P 1 Session regenon customer login

Replacemd5()with password_hash(PASSWORD_BCRYPT,['cost'=>12] );usepassword_verify()forallloginchecks Critical

Replacedirectinterpolationwithmysqli_prepare +bind_param('i',intval($_GET['id'])) Critical

Addsession_regenerate_id(true)immediately aftersuccessfullogincheckinlogin.php Critical

P 2 CSRFtoken validation bin2hex(random_bytes(32))persession;hidden fieldinallPOSTforms;validateeveryPOST handler High

P 2 HttpOnly+ Secure+ SameSite cookies php.ini:session.cookie_httponly=1; cookie_secure=1;cookie_samesite=Strict High

P 2 HTTPS/TLS enforcemen t Let'sEncryptviaCertbot;Apachemod_rewrite HTTP→HTTPSredirect;HSTSheader High

P 2 Move Config.php above webroot

P 3 Loginratelimiting+ lockout

P 3 Payment gateway integration

P 4 Security audit logging

P 4 Email notification s

P 4 Product review system

Placeinparentofdocumentroot;referencevia require_once'/var/config.php' High

Trackfailed_attemptsperemail+IPinDB;lockout after5failuresfor15min;CAPTCHAon3rd attempt Medium

RazorpayPHPSDKforIndia;replacesimulated checkoutwithrealpaymentcapture+webhook confirmation Medium

Logfailedlogins,adminoperations,andcheckout eventstoaseparateaudit_logtablewithIP+ timestamp Low

PHPMailer+SendGridSMTPfororder confirmation,shippingupdates,andpassword resetemails Low

reviewstable(user_idFK,product_idFK,rating TINYINT,commentTEXT);averageratingon productcards Low

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

14. CONCLUSION

This paper has presented the complete design, implementation, security analysis, and testing strategy for ShopEase a full-stack, open-source e-commerce web applicationbuiltonPHP8.1,MySQL5.7,Bootstrap5.3,and the Apache HTTP Server within the classic LAMP stack architecture. The system demonstrates that a fully functional, architecturally sound e-commerce platform with dual Admin/Customer privilege separation enforced at both the session layer and the database role layer, a session-based shopping cart with transactional order persistence backed by MySQL transactions, dynamic product categorisation with real-time database-driven filter pills across 14 configurable categories, and a complete Admin CRUD panel with a live statistics dashboard isachievable withinanundergraduateminiproject scope using entirely free, open-source tooling and withoutanyexternalpaidservicesorlicensedframeworks.

The session-based cart mechanism with unit price captured at cart-add time, stock re-validated at checkout, and order total computed server-side immediately before theMySQLINSERT providesa transactional foundation that mirrors the design patterns used in production ecommerce systems including WooCommerce and OpenCart. The Admin portal's multi-condition session guard (admin_logged_in flag, strict boolean comparison, admin_id presence, AND role='admin' in the SQL query) correctly prevents privilege escalation from both unauthenticated visitors and authenticated customer sessions.

TheOWASPTop10(2021)analysisinSection10identifies eight specific security gaps across seven OWASP categories,andtheprioritisedhardeningroadmapinTable -4 provides concrete, PHP-specific implementation paths foreveryidentifiedgap.Critically,addressingthethreeP1 items BCrypt migration, prepared statement audit, and session regeneration on customer login can be accomplished in less than one developer-day and would immediatelyelevateShopEase'ssecurityposturetoalevel appropriate for a staging deployment with real (nonpayment) user data. The authors plan to implement all P1 and P2 priorities in a follow-on project phase targeting production deployment within the college's internal studentmarketplaceportal.

ACKNOWLEDGEMENT

The authors express sincere gratitude to Prof. Samir Kumar, Department of Computer Engineering, Bharat College of Engineering, for consistent guidance, technical mentorship, and constructive feedback throughout the entire project lifecycle from initial architecture decisions through implementation and final security evaluation. The authors also gratefully acknowledge the

open-source communities behind PHP, MySQL, Bootstrap 5, the Apache HTTP Server, and the OWASP Foundation, whoseworkanddocumentationprovidedthefoundational knowledgeandtoolinguponwhichShopEaseisbuilt.

REFERENCES

[1]W3Techs,"UsageStatisticsofServer-SideProgramming LanguagesforWebsites,"https://w3techs.com/technologies /overview/programming_language, Apr. 2024. Accessed: Apr.2025.

[2] Statista, "Global Retail E-Commerce Revenue 2014–2028,"StatistaMarketForecast,Hamburg,Germany,2024.

[3] OWASPFoundation,"OWASPTop10 2021:TheTen Most Critical Web Application Security Risks," https://owasp.org/Top10/,2021.Accessed:Apr.2025.

[4] PHP Group, "PHP Manual Session Handling," https://www.php.net/manual/en/book.session.php, 2024. Accessed:Apr.2025.

[5] NIST SP 800-132, "Recommendation for PasswordBased Key Derivation, Part 1: Storage Applications," National Institute of Standards and Technology, Gaithersburg,MD,Dec.2010.

[6] A. Barth, "HTTP State Management Mechanism," IETF RFC6265,InternetEngineeringTaskForce,Apr.2011.

[7] OracleCorp.,"MySQL5.7ReferenceManual InnoDB andACIDModel," https://dev.mysql.com/doc/refman/5.7/, 2024.Accessed:Apr.2025.

[8] Bootstrap Team, "Bootstrap 5.3 Documentation," https://getbootstrap.com/docs/5.3/, 2024. Accessed: Apr. 2025.

[9] PHP Group, "password_hash Creates a password hash,"PHPManual,https://www.php.net/manual/en/functi on.password-hash.php,2024.

[10] Verizon, "2023 Data Breach Investigations Report (DBIR)," Verizon Communications Inc., New York, NY, 2023.

[11] P. Gasti and K. B. Rasmussen, "On the Security of Password Manager Database Formats," in Proc. 17th European Symposium on Research in Computer Security (ESORICS),Pisa,Italy,Sep. 2012,LNCSvol.7459,pp.770–787,Springer.

[12] Apache Software Foundation, "Apache HTTP Server 2.4 Documentation," https://httpd.apache.org/docs/2.4/, 2024.Accessed:Apr.2025.

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 04 | Apr 2026 www.irjet.net p-ISSN: 2395-0072

[13]N.Saxenaetal.,"SecurityAnalysisofSensitiveDatain Web Applications," in Proc. IEEE International Conference on Trust, Security and Privacy in Computing and Communications(TrustCom),pp.452–459,2020.

[14]D.LuberandJ.Schneier,"EvaluationofAuthentication Schemes in Terms of Security and Usability," Information Security Journal: A Global Perspective, vol. 30, no. 3, pp. 147–163,Taylor&Francis,2021.

[15] PCI Security Standards Council, "PCI DSS v4.0 Payment Card Industry Data Security Standard," https://www.pcisecuritystandards.org/, Mar. 2022. Accessed:Apr.2025.

[16] OpenCart Ltd., "OpenCart Technical Architecture Documentation," https://docs.opencart.com/, 2024. Accessed:Apr.2025.

[17] WooCommerce Inc., "WooCommerce Developer DocumentationCartandSession,"https://developer.wooco mmerce.com/,2024.Accessed:Apr.2025.

[18] PHP Group, "MySQLi PHP Manual: Prepared Statements,"https://www.php.net/manual/en/mysqli.quic kstart.prepared-statements.php,2024.

|

Turn static files into dynamic content formats.

Create a flipbook