PHP Demo Program


Ron Fredericks writes: I am LectureMaker’s video platform technologist. So I thought I would demonstrate some of my sample code in building a simple website demo.

The demo consists of three pages that feature the following code

  • PHP programming with OO and model-view-controller (MVC) architecture
  • SQL file to create a new table and load some sample user data
  • PHP sessions and OO MySQL Data Manager
  • Use of CSS style sheet and tags for web page layout and forms management
  • Use of JavaScript and jQuery functions and project library
  • A RESTful API allowing users to move data between the three pages

Visit the running project’s website here:
www.lecturemaker.com/test/HP_login.php

Download a copy of the project’s source code from GitHub:
https://github.com/RonFredericks/PHP_Demo_Project

Overview

Build a 2-3 page website with a single page view concept with JavaScript mvc and REST service. The concept of the site is to choose your background. After login the user can select a file to upload and that becomes the background image of the landing page. Page 1 is login with at least 3 different users who can login. Page 2 is landing page which will show the image uploaded and page 3 is upload the background image you like. Page 2 and 3 should have a logout button.

Overview of the Project

Overview of the Project

FAQ

What is OOP?
Object Oriented Programming, or OOP, invokes the use of classes to organize the data and structure of an application:

  • Objects: instances of a class
  • Inheritance: ability to pass characteristics and behaviors from a base class
  • Access Modifiers: ability to protect data and methods
  • Interfaces: a form of abstract class that acts as a model for creating a derived class
  • PHP 5 Built-in Classes: Standard PHP Library (SPL), mysqli, PDO, SQLite, XML support, relfection, Iterator interface, magic methods, objects passed by reference
  • Design Patterns: a reusable set of solutions that solve practical problems

What is MVC?
Model–View–Controller (MVC) is an architectural pattern used in software engineering:

  • Model handles database logic. Code in the model connects to the database and provides an abstraction layer.
  • Controller represents the business (application) logic i.e. all our ifs and else.
  • View provides the presentation logic i.e our HTML/XML/JSON code.

What is REST?
Representational state transfer (REST) is a predominant web API design model for distributed systems. PHP examples include:

  • Use FORM tag with GET or POST to send data to another web page.
  • Use cURL to set the URL, create array of POST data, set options such as return XML data, and make request.
  • Create a POST request by opening a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen().

Design Methodology

See the figure above “Overview of the Project” where each web page is shown, along with the MySQL database supporting privileged access to the main project’s feature: to upload a new background image.

To start the project code I started with a basic development environment:

  • WampServer: a Windows, Apache, MySQL, and PHP development environment. I chose this platform to run my test code because I can development the code directly within the Apache Localhost service without the delay of a repeated ftp style upload.
  • Adobe’s DreamWeaver code editor: I use this code editing tool to highlight, format, and check my CSS, HTML, PHP, and JavaScript code. Because I save my files directly into the WampServer, the workflow is fairly efficient.

With this flexible coding environment I create three documents initially: the PHP login page, the CSS file, and a sql field definitions file using a tool called phpmyadmin hosted on my WampServer. I work back and forth between the login page, the CSS file, and the SQL definitions to get the look and feel I have visualized within my wireframe design. I add user fields into my SQL table to manage login storage. And as I start to see a pattern to the JavaScript and PHP support needs for this project: I prepare to add PHP classes, PHP support functions, and JavaScript code into new files as the code is development.

Create Login Page, CSS Stylesheet and SQL file

Create Landing Page

Create Image Upload Page

Create PHP Initialize File

Create Database Class

Create User Class

Create User Manager Class

Code (php)
  1. ////////////////////////////////// Create Login Page ///////////////////////
  2. < ?php
  3. // File: HP_login.php
  4. // Purpose: Initialize and start PHP session
  5. // Author: Ron Fredericks, LectureMaker LLC
  6. // Last Updated: 7/10/2013
  7. require_once ‘./HP_assets/HP_initialize.php’;
  8. ?>
  9. < !doctype html>
  10. "utf-8"/>
  11. Login Page
  12. "stylesheet" type="text/css" href="./HP_assets/HP_main.css"/>
  13. < ?php
  14. // Insure that prior users are logged out of this web service
  15. $um->logout();
  16. // Initiate page div layout and display heading
  17. PutHeader(HEADING);
  18. // Initiate login
  19. LoginForm("HP_uploadImage.php");
  20. SelectValidUser();
  21. // Complete page div layout and display footer
  22. PutFooter(FOOTER);
  23. exit();
  24. ?>
  25. ////////////////////////////////// Create Landing Page ///////////////////////
  26. < ?php
  27. // File: HP_landingPage.php
  28. // Purpose: Initialize and start PHP session
  29. // Author: Ron Fredericks, LectureMaker LLC
  30. // Last Updated: 7/10/2013
  31. require_once ‘./HP_assets/HP_initialize.php’;
  32. ?>
  33. < !doctype html>
  34. "utf-8"/>
  35. Landing Page
  36. "stylesheet" type="text/css" href="./HP_assets/HP_main.css"/>
  37. < ?php
  38. PutHeader(HEADING);
  39. if (!isset($user)) {
  40. PutErrorMessage("You must log in to view this page: ".basename($_SERVER[‘PHP_SELF’]));
  41. Redirect(‘HP_login.php’, 5);
  42. exit();
  43. }
  44. ?>
  45. < ?php
  46. PutErrorMessage(ProcessUploadForm());
  47. PutFooter(FOOTER);
  48. ?>
  49. ////////////////////////////////// Create Image Upload Page ///////////////////////
  50. < ?php
  51. // File: HP_uploadImage.php
  52. // Purpose: Initialize and start PHP session
  53. // Author: Ron Fredericks, LectureMaker LLC
  54. // Last Updated: 7/10/2013
  55. require_once ‘./HP_assets/HP_initialize.php’;
  56. ?>
  57. < !doctype html>
  58. "utf-8"/>
  59. Upload Image
  60. "stylesheet" type="text/css" href="./HP_assets/HP_main.css"/>
  61. < ?php
  62. // Attempt to process user login form $_POST
  63. if (ProcessLoginForm($um)) {
  64. // update user info on successful new login
  65. $user = $um->getSession();
  66. }
  67. PutHeader(HEADING);
  68. // Test for valid user, return to login page if user not valid
  69. if (!isset($user)) {
  70. PutErrorMessage("You must log in to view this page: ".basename($_SERVER[‘PHP_SELF’]));
  71. Redirect(‘HP_login.php’, 5);
  72. die();
  73. }
  74. ?>
  75. < ?php
  76. // Initiate image upload form
  77. GetImageForm("HP_landingPage.php");
  78. DisplayValidImageTypes();
  79. PutFooter(FOOTER);
  80. ?>
  81. ////////////////////////////////// Create PHP Initialize File ///////////////////////
  82. < ?php
  83. // File: HP_initialize.php
  84. // Initialize PHP environment
  85. // Author: Ron Fredericks, LectureMaker LLC
  86. // Last Updated: 7/10/2013
  87. define("HEADING", "Select Background Image Project");
  88. define("IMAGE_DIR", "./HP_images/");
  89. define("DEBUG", false); // set to true for more display messages
  90. error_reporting(-1); // set to (-1) to display all errors, (0) for no errors and (E_ALL ^ E_NOTICE) for default production
  91. global $validext; // define valid background image types as global
  92. $validext = array(".gif"=>"GIF image", ".jpeg"=>"JPEG image", ".jpg"=>"JPG image", ".png"=>"PNG image");
  93. // include the mySQL data management system
  94. require_once ‘./HP_assets/HP_UserManager.php’;
  95. require_once ‘./HP_assets/HP_miscFunctions.php’;
  96. //
  97. //session_start();
  98. $um = new UserManager();
  99. $user = $um->getSession();
  100. ////////////////////////////////// Create Database Class ///////////////////////
  101. < ?php
  102. // File: HP_Database.php
  103. // Purpose: Define a class to MySQL database connection class
  104. // Author: Ron Fredericks, LectureMaker LLC
  105. // Last Updated: 7/10/2013
  106. // References:
  107. // http://forum.zonehacks.com/threads/10-PHP-User-Management-System-using-Object-Oriented-Programming-and-MySQL
  108. // Object-Oriented PHP by Peter Lavin, No Starch Press, 2006
  109. class Database {
  110. private static $instances = 0; // make sure db connection is made only once, RDF
  111. /**
  112. * =============================================================
  113. * Change these values to work with your mysql database settings
  114. * =============================================================
  115. */
  116. private $db_host = ‘localhost’;
  117. private $db_user = ‘xxx’; // fill in these values with your credentials
  118. private $db_pass = ‘xxx’;
  119. private $db_name = ‘xxx’; // fill in your mySQL atabase name here
  120. private $where = array();
  121. private $variables = array();
  122. private $link;
  123. // see __call method below for implementaiton, RDF
  124. private $functions = array(
  125. ‘affected_rows’ => ‘mysql_affected_rows’,
  126. ‘client_encoding’ => ‘mysql_client_encoding’,
  127. ‘close’ => ‘mysql_close’,
  128. ‘connect’ => ‘mysql_connect’,
  129. ‘create_db’ => ‘mysql_create_db’,
  130. ‘data_seek’ => ‘mysql_data_seek’,
  131. ‘db_name’ => ‘mysql_db_name’,
  132. ‘db_query’ => ‘mysql_db_query’,
  133. ‘drop_db’ => ‘mysql_drop_db’,
  134. ‘errno’ => ‘mysql_errno’,
  135. ‘error’ => ‘mysql_error’,
  136. ‘escape_string’ => ‘mysql_escape_string’,
  137. ‘fetch_array’ => ‘mysql_fetch_array’,
  138. ‘fetch_assoc’ => ‘mysql_fetch_assoc’,
  139. ‘fetch_field’ => ‘mysql_fetch_field’,
  140. ‘fetch_lengths’ => ‘mysql_fetch_lengths’,
  141. ‘fetch_object’ => ‘mysql_fetch_object’,
  142. ‘fetch_row’ => ‘mysql_fetch_row’,
  143. ‘field_flags’ => ‘mysql_field_flags’,
  144. ‘field_len’ => ‘mysql_field_len’,
  145. ‘field_name’ => ‘mysql_field_name’,
  146. ‘field_seek’ => ‘mysql_field_seek’,
  147. ‘field_table’ => ‘mysql_field_table’,
  148. ‘field_type’ => ‘mysql_field_type’,
  149. ‘free_result’ => ‘mysql_free_result’,
  150. ‘get_client_info’ => ‘mysql_get_client_info’,
  151. ‘get_host_info’ => ‘mysql_get_host_info’,
  152. ‘get_proto_info’ => ‘mysql_get_proto_info’,
  153. ‘get_server_info’ => ‘mysql_get_server_info’,
  154. ‘info’ => ‘mysql_info’,
  155. ‘insert_id’ => ‘mysql_insert_id’,
  156. ‘list_dbs’ => ‘mysql_list_dbs’,
  157. ‘list_fields’ => ‘mysql_list_fields’,
  158. ‘list_processes’ => ‘mysql_list_processes’,
  159. ‘list_tables’ => ‘mysql_list_tables’,
  160. ‘num_fields’ => ‘mysql_num_fields’,
  161. ‘num_rows’ => ‘mysql_num_rows’,
  162. ‘pconnect’ => ‘mysql_pconnect’,
  163. ‘ping’ => ‘mysql_ping’,
  164. ‘query’ => ‘mysql_query’,
  165. ‘real_escape_string’ => ‘mysql_real_escape_string’,
  166. ‘result’ => ‘mysql_result’,
  167. ‘select_db’ => ‘mysql_select_db’,
  168. ‘set_charset’ => ‘mysql_set_charset’,
  169. ‘stat’ => ‘mysql_stat’,
  170. ‘tablename’ => ‘mysql_tablename’,
  171. ‘thread_id’ => ‘mysql_thread_id’,
  172. ‘unbuffered_query’ => ‘mysql_unbuffered_query’
  173. );
  174. function __construct()
  175. {
  176. if (Database::$instances == 0) {
  177. $this->link = @$this->connect($this->db_host, $this->db_user, $this->db_pass); // catch and hide error messages using "@", RDF
  178. if(!$this->link) {
  179. die("Database class: ".mysql_error(). " Error no: ".mysql_errno()); // Include all possible error messages in display, RDF
  180. }
  181. $this->select_db($this->db_name);
  182. Database::$instances = 1;
  183. }
  184. }
  185. function __destruct()
  186. {
  187. if($this->link) {
  188. Database::$instances == 0;
  189. mysql_close($this->link);
  190. unset($this->link); // Clear from memory, RDF
  191. }
  192. }
  193. // Manage undeclared functions
  194. public function __call($name, $arguments) {
  195. if(isset($this->functions[$name])) {
  196. return call_user_func_array($this->functions[$name], $arguments);
  197. }
  198. return FALSE;
  199. }
  200. }
  201. ////////////////////////////////// Create User Class ///////////////////////
  202. < ?php
  203. // File: HP_User.php
  204. // Purpose: User class to manage undefined data members
  205. // Author: Ron Fredericks, LectureMaker LLC
  206. // Last Updated: 7/10/2013
  207. // References:
  208. // http://forum.zonehacks.com/threads/10-PHP-User-Management-System-using-Object-Oriented-Programming-and-MySQL
  209. // Object-Oriented PHP by Peter Lavin, No Starch Press, 2006
  210. class User
  211. {
  212. private $userdata = array();
  213. public function checkPassword($pass)
  214. {
  215. if(isset($this->userdata[‘password’]) && $this->userdata[‘password’] == md5($pass)) {
  216. return true;
  217. }
  218. return false;
  219. }
  220. public function set($var, $value)
  221. {
  222. $this->userdata[$var] = $value;
  223. }
  224. public function get($var)
  225. {
  226. if(isset($this->userdata[$var])) {
  227. return $this->userdata[$var];
  228. }
  229. return NULL;
  230. }
  231. }
  232. ////////////////////////////////// Create User Manager Class ///////////////////////
  233. < ?php
  234. // File: HP_UserManager.php
  235. // Purpose: Create a class to manage user functions using a MySQL database
  236. // Author: Ron Fredericks, LectureMaker LLC
  237. // Last Updated: 7/10/2013
  238. // References:
  239. // http://forum.zonehacks.com/threads/10-PHP-User-Management-System-using-Object-Oriented-Programming-and-MySQL
  240. // Object-Oriented PHP by Peter Lavin, No Starch Press, 2006
  241. // Include the User and Database class files
  242. require_once "./HP_assets/HP_User.php";
  243. require_once "./HP_assets/HP_Database.php";
  244. class UserManager
  245. {
  246. private $db;
  247. // Create an instance of the database class and store it into a private variable
  248. public function UserManager()
  249. {
  250. $this->db = new Database();
  251. }
  252. public function createUser($username, $password, $email, $is_admin = FALSE)
  253. {
  254. if (isset($username) && isset($password) && isset($email)) { // Check for invalid function call, RDF
  255. $stmt = sprintf("INSERT INTO users (`id`, `username`, `password`, `email`, `is_admin`) VALUES (NULL, ‘%s’, ‘%s’, ‘%s’, ‘%d’)",
  256. $this->db->real_escape_string($username),
  257. md5($this->db->real_escape_string($password)), // A md5 hash of the user’s password will be stored in the database.
  258. $this->db->real_escape_string($email), // always escape data from public before storing in database
  259. $this->db->real_escape_string($is_admin));
  260. $result = $this->db->query($stmt);
  261. if ($result) return true;
  262. }
  263. return false;
  264. }
  265. public function updateUser($user)
  266. {
  267. // Normally I wouldn’t store session data in the database, but
  268. // it can be changed to track cookies if you plan to go that
  269. // route.
  270. $session = $user->get(‘session’);
  271. if (!$session) $session = 0;
  272. $stmt = sprintf("UPDATE users SET `username` = ‘%s’, `password` = ‘%s’, `email` = ‘%s’, `is_admin` = ‘%d’, `session` = ‘%s’ WHERE `id` = ‘%d’",
  273. $this->db->real_escape_string($user->get(‘username’)),
  274. $this->db->real_escape_string($user->get(‘password’)),
  275. $this->db->real_escape_string($user->get(‘email’)),
  276. $this->db->real_escape_string($user->get(‘is_admin’)),
  277. $this->db->real_escape_string($session),
  278. $this->db->real_escape_string($user->get(‘id’)));
  279. return $this->db->query($stmt);
  280. }
  281. public function deleteUser($user)
  282. {
  283. $userID = $this->db->real_escape_string($user->get(‘id’));
  284. return $this->db->query("DELETE FROM users WHERE `id` = ‘$userID’");
  285. }
  286. // Get users from the database and return a user object by id or username
  287. public function getUserByID($id)
  288. {
  289. if (isset($id)) { // Check for invalid function call, RDF
  290. // get the user by id from database
  291. $stmt = sprintf("SELECT * FROM users WHERE id = ‘%s’", $this->db->real_escape_string($id));
  292. $result = $this->db->query($stmt);
  293. if($result) {
  294. $user = new User(); // create a new user object
  295. $row = $this->db->fetch_assoc($result);
  296. foreach($row as $key => $value) { // loop through user table values
  297. $user->set($key, $value); // store them in the user object
  298. }
  299. return $user; // and return it
  300. }
  301. }
  302. return NULL;
  303. }
  304. public function getUserByName($name)
  305. {
  306. if (isset($name)) { // Check for invalid function call, RDF
  307. $stmt = sprintf("SELECT * FROM users WHERE username = ‘%s’", $this->db->real_escape_string($name));
  308. $result = $this->db->query($stmt) or trigger_error(mysql_error()." ".$stmt);
  309. if ($result && $this->db->num_rows($result) > 0) {
  310. $user = new User();
  311. $row = $this->db->fetch_assoc($result);
  312. foreach($row as $key => $value) {
  313. $user->set($key, $value);
  314. }
  315. return $user;
  316. }
  317. }
  318. return NULL;
  319. }
  320. // Get user by name, check the password, updates session info in the database, and return the user object
  321. public function login($username, $password)
  322. {
  323. if (isset($username) && isset($password)) { // Check for invalid function call, RDF
  324. $user = $this->getUserByName($username);
  325. if (isset($user) && $user->checkPassword($password)) {
  326. // start PHP session, RDF
  327. if(!isset($_SESSION)) session_start();
  328. $_SESSION[‘zhuser’] = $user->get(‘username’); // I normally use these for cookies
  329. $_SESSION[‘zhsess’] = md5($username.microtime()); // calculate md5 of username + current unix time
  330. $user->set(‘session’, $_SESSION[‘zhsess’]); // set the session in user object
  331. $this->updateUser($user); // update the user
  332. return $user; // and return the user object if we’re good
  333. }
  334. }
  335. return NULL;
  336. }
  337. public function logout()
  338. {
  339. if (isset($_SESSION)) {
  340. unset($_SESSION);
  341. }
  342. }
  343. // Check if a session exists and against what we have stored in the database, if they match we’re good
  344. public function getSession()
  345. {
  346. // start PHP session, RDF
  347. if (!isset($_SESSION)) session_start();
  348. if (isset($_SESSION[‘zhuser’]) && isset($_SESSION[‘zhsess’])) {
  349. $user = $this->getUserByName($_SESSION[‘zhuser’]);
  350. if (!$user) $this->logout();
  351. if ($user->get(‘session’) == $_SESSION[‘zhsess’]) {
  352. return $user;
  353. }
  354. }
  355. return NULL;
  356. }
  357. }

Create PHP Functions Page

Code (php)
  1. < ?php
  2. // File: HP_miscFunctions.php
  3. // Purpose: PHP Visual display and support functions
  4. // Author: Ron Fredericks, LectureMaker LLC
  5. // Last Updated: 7/11/2013
  6. //////////////////////////////////////////////////////////////////
  7. // Login Support Functions //
  8. //////////////////////////////////////////////////////////////////
  9. function LoginForm($url)
  10. // Present a login form
  11. {
  12. // Reference: http://designikx.wordpress.com/2010/04/07/pure-css-div-based-form-design-form-layout/
  13. $myArray[0] = array("test" => "", "message" => "Username must be entered");
  14. ?>
  15. "myform">
  16. "loginForm" action="" onsubmit="return login_form(this)" method="post">
  17. Login Window

  18. Welcome to the background image selector website

  19. Its Your Name
  20. "username" type="text" name="username"/>
  21. Enter Your Password
  22. "password" type="text" name="password"/>
  • < ?php
  • }
  • function SelectValidUser()
  • // Present list of valid users for login
  • {
  • ?>
  • "myformsupport">
  • Login List

  • Load one of these valid user credentials into login window

    • Ron Fredericks
    • Tommy Tuba
    • Admin