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

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.  
  8. //////////////////////////////////////////////////////////////////
  9. // Login Support Functions                                      //
  10. //////////////////////////////////////////////////////////////////
  11.  
  12. function LoginForm($url)
  13. // Present a login form
  14. {
  15.     // Reference: http://designikx.wordpress.com/2010/04/07/pure-css-div-based-form-design-form-layout/
  16.     $myArray[0] = array("test" => "", "message" => "Username must be entered");
  17.     ?>
  18.    
  19.    
  20.     <div id="myform">
  21.     <form name="loginForm" action="<?php echo $url; ?>" onsubmit="return login_form(this)" method="post">
  22.     <h1>Login Window</h1>
  23.     <p>Welcome to the background image selector website</p>
  24.    
  25.     <label>Username
  26.     <span>Its Your Name</span>
  27.     </label>
  28.     <input id="username" type="text" name="username"/>
  29.  
  30.     <label>Password
  31.     <span>Enter Your Password</span>
  32.     </label>
  33.     <input id="password" type="text" name="password"/>
  34.     <button type="submit">Login</button>
  35.     </form>
  36.     </div>
  37.     < ?php
  38. }
  39.  
  40. function SelectValidUser()
  41. // Present list of valid users for login
  42. {
  43. ?>
  44.     <div id="myformsupport">
  45.     <h1>Login List</h1>
  46.     <p>Load one of these valid user credentials into login window</p>
  47.     <ul>
  48.     <li><button onclick="load_login(‘Ron Fredericks’)">Load</button>Ron Fredericks</li>
  49.     <li><button onclick="load_login(‘Tommy Tuba’)">Load</button>Tommy Tuba</li>
  50.     <li><button onclick="load_login(‘Admin’)">Load</button>Admin</li>
  51.     </ul>
  52.     </div>
  53. < ?php
  54. }
  55.  
  56. function ProcessLoginForm($um)
  57. {
  58.     if (isset($_REQUEST[‘username’]) && isset($_REQUEST[‘password’]))
  59.     {   
  60.         // Attempt to login
  61.         $user = $um->login($_REQUEST[‘username’], $_REQUEST[‘password’]);
  62.         // Login failed, try again     
  63.         if(!$user)
  64.         {
  65.             PutHeader(HEADING);
  66.             PutErrorMessage ("Invalid login, try selecting a user from the list…");
  67.             Redirect("HP_login.php", 5);
  68.             PutFooter(FOOTER);
  69.         } else {
  70.             // login was succesful
  71.             return true;
  72.         }
  73.     }
  74.     // login was either not successful or no login info was requested
  75.     return false;
  76. }
  77.  
  78.  
  79. //////////////////////////////////////////////////////////////////
  80. // Upload Image Support Functions                               //
  81. //////////////////////////////////////////////////////////////////
  82.  
  83. function GetImageForm($url)
  84. // Present a login form
  85. {
  86.     // Reference: http://designikx.wordpress.com/2010/04/07/pure-css-div-based-form-design-form-layout/
  87.     ?>
  88.    
  89.     <div id="mygetimageform">
  90.     <form name="form1" method="post" enctype="multipart/form-data" action="<?php echo $url; ?>">
  91.     <h1>Load New Background Image Window</h1>
  92.     <p>Welcome to the background image selector website</p>
  93.    
  94.     <input type="file" name="file" id="file" size="40"/>
  95.     <button type="submit" name="Submit" value="Submit">Load Image</button>
  96.     </form>
  97.     </div>
  98.     < ?php
  99. }
  100.  
  101. function DisplayValidImageTypes()
  102. // Present list of valid file types for image upload
  103. {
  104.     global $validext;
  105.  
  106.     echo ‘<div id="myformsupport">’;
  107.     echo ‘<h1>Valid File Types</h1>’;
  108.     echo ‘<p>Choose a file to load with one of these valid extensions:</p>’;
  109.     echo ‘<ul>’;
  110.     foreach ($validext as $key => $value) {
  111.         echo "<li>$value [$key]</li>";
  112.     }
  113.     echo ‘</ul>’;
  114.     echo ;
  115.  
  116. }
  117.  
  118. function UploadFile($origin, $dest, $tmp_name)
  119. // reference: function GetImageForm($url)
  120. {
  121.     global $validext;
  122.     $origin = strtolower(basename($origin));
  123.     $fulldest = $dest.$origin;
  124.     $filename = $origin;
  125.     $fileext = (strpos($origin,‘.’)===false?:‘.’.substr(strrchr($origin, "."), 1));
  126.     $validflag = false;
  127.     foreach($validext as $ext=>$type) {
  128.       if ($fileext === $ext) {
  129.           $validflag = true;
  130.           break;
  131.       }
  132.     }
  133.     if (!$validflag) {
  134.       PutErrorMessage("Error: invalid file extension [$fileext]");
  135.       return false;
  136.       }
  137.    
  138.     for ($i=1; file_exists($fulldest); $i++) {
  139.      $fileext = (strpos($origin,‘.’)===false?:‘.’.substr(strrchr($origin, "."), 1));
  140.      $filename = substr($origin, 0, strlen($origin)-strlen($fileext)).‘['.$i.']‘.$fileext;
  141.      $fulldest = $dest.$filename;
  142.     }
  143.    
  144.     if (move_uploaded_file($tmp_name, $fulldest))  return $filename;
  145.      
  146.     return false;
  147. }
  148.  
  149. function DeleteImageFiles($directory, $days)
  150. // delete files from a diectory,
  151. // return number of files deleted,
  152. // $directory must be: 1) a relative address and 2) not the same directory as the php file, for safety
  153. {
  154.         $count = 0;
  155.         if (($days >= 0) && ($directory == IMAGE_DIR) && (dirname(__FILE__) != $directory) ) {
  156.             $files = glob($directory."*");
  157.             $seconds = $days * 24 * 60 * 60;
  158.             foreach($files as $file) {
  159.                 $filemtime=filemtime ($file);
  160.                 if(is_file($file) && time()-$filemtime>= $seconds) {
  161.                     $count++;
  162.                     unlink($file);
  163.                 }
  164.             }   
  165.         }
  166.         return $count;
  167. }
  168.  
  169. function ProcessUploadForm()
  170. // reference: function GetImageForm($url)
  171. {
  172.     $msg= "";
  173.     if (isset($_POST[‘Submit’]) && isset($_FILES["file"]["name"])) {
  174.         if (empty($_FILES["file"]["name"])) {
  175.             PutErrorMessage("You did not select an image for landing page, please try again…");
  176.             Redirect(‘HP_uploadImage.php’, 5);
  177.             die();
  178.         }
  179.    
  180.         // process file name requested on client’s computer as a result of client’s use of the ‘browse’ button
  181.         if ($_FILES["file"]["error"] > 0) {
  182.             $msg .= "Error: " . $_FILES["file"]["error"] . "
  183. ";
  184.         }
  185.         else {
  186.             // file found
  187.             $fileCnt = DeleteImageFiles(IMAGE_DIR, 0)// remove old images
  188.             if (DEBUG) {
  189.             $msg .= "$fileCnt prior images removed from " . IMAGE_DIR . " image directory
  190. ";
  191.             $msg .=  "Upload: " . $_FILES["file"]["name"] . "
  192. ";
  193.             $msg .=  "Type: " . $_FILES["file"]["type"] . "
  194. ";
  195.             $msg .=  "temp: "  . $_FILES["file"]["tmp_name"] . "
  196. ";
  197.             $msg .=  "Size: " . round($_FILES["file"]["size"] / 1024, 2) . " Kb
  198. ";
  199.             }
  200.             $result = UploadFile($_FILES["file"]["name"], IMAGE_DIR, $_FILES["file"]["tmp_name"]);
  201.             if ($result) {
  202.                 if (DEBUG) {
  203.                     $msg .=  "Result: " . IMAGE_DIR . $result."
  204. ";
  205.                 }
  206.                 ?>
  207.                 <script>
  208.                 imgLink = "< ?php echo IMAGE_DIR . $result ; ?>";
  209.                 update_background_image(imgLink);
  210.                 </script>
  211.         < ?php
  212.             }
  213.             else {
  214.                 $msg .=  "Upload was not successful
  215. ";
  216.             }
  217.         }
  218.     }
  219.     return $msg;
  220. }
  221.  
  222.  
  223. //////////////////////////////////////////////////////////////////
  224. // Page Display Functions                                      //
  225. //////////////////////////////////////////////////////////////////
  226.  
  227. function PutHeader($heading, $left="", $right="")
  228. // Initialize web page structure and display heading
  229. {
  230.     echo "<div id=’container’>";
  231.     echo "<div id=’header_ctr’><span id=’header_lft’></span>$heading<span id=’header_rt’>".GetButtons()."</span></div>";
  232.     echo "<div id=’body’>";
  233. }
  234.  
  235. function PutFooter($footer)
  236. // Complete web page structure and display footer
  237. {
  238.     echo "</div>";
  239.     echo "<div id=\"footer\">$footer</div>";
  240.     echo "</div>";
  241.     ?>
  242.     <script type="text/javascript">
  243.     // place google analytics code to the bottom of each page
  244.     // UA-8108355-1 is for LectureMaker
  245.       var _gaq = _gaq || [];
  246.       _gaq.push([‘_setAccount’, ‘UA-8108355-1′]);
  247.       _gaq.push([‘_trackPageview’]);
  248.    
  249.       (function() {
  250.         var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
  251.         ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
  252.         var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
  253.       })();
  254.     </script> 
  255.     < ?php 
  256. }
  257.    
  258. function PutErrorMessage($msg)
  259. // Manage display format for error messages
  260. {
  261.         if (!empty($msg)) {
  262.             echo "<p class=’myerror’>$msg";
  263.         }
  264. }
  265.  
  266. function Redirect($url, $waitSeconds = 0)
  267. // Redirect to another web page
  268. {
  269.     //header("Location: $url"); // Rewrite the header
  270.     echo "<meta http-equiv=’refresh’ content=’$waitSeconds;url=$url’/>";
  271.     echo "<div id=\"timeMsg\">Click here if website does not load in <span>$waitSeconds</span> seconds
  272. <a href=\"$url\">$url</a></div>";
  273.     ?>   
  274.     <script>
  275.     count_down(‘#timeMsg’, ‘span’);
  276.     </script>
  277.    
  278.     < ?php
  279.     PutFooter(FOOTER);
  280.     die ();
  281. }
  282.  
  283. function GetButtons()
  284. // Dislplay user options as buttons when logged in
  285. {
  286.     $msg="";
  287.     if (isset($_SESSION["zhuser"]) && !empty($_SESSION["zhuser"])) {
  288.         $msg .= "<button onclick=\"javascript:open_window(‘HP_login.php’, ‘_self’);\">Log Out";
  289.         $msg .= "<button onclick=\"open_window(‘HP_landingPage.php’, ‘_self’);\">Landing Page</button>";
  290.         $msg .= "<button onclick=\"open_window(‘HP_uploadImage.php’, ‘_self’);\">New Image</button>";
  291.     }
  292.     //var_dump($_SESSION);
  293.     return $msg;
  294.  
  295. }
  296.  
  297. function GetCurrentPage()
  298. // Return current web page
  299. {
  300.     return basename($_SERVER[‘PHP_SELF’]);
  301. }
  302.  
  303. ?>

Create JavaScript Functions Page

Code (javascript)
  1. // JavaScript Document
  2. // HP_functions.js
  3. // Author: Ron Fredericks, LectureMaker LLC
  4. // Last Updated: 7/10/2013
  5.  
  6. function count_down(msgTag, msgSpan)
  7. {
  8.     // display the count down of seconds within the text when time is greater than 0
  9.     var sec = $(msgTag+" "+msgSpan).text() || 0;
  10.     var timer = setInterval(function() {
  11.        $(msgTag+" "+msgSpan).text(–sec);
  12.        if (sec < = 0) {
  13.           $(msgTag).fadeOut(‘fast’);
  14.           clearInterval(timer);
  15.        }
  16.     }, 1000);
  17. }
  18.  
  19. function load_login(user)
  20. // stuff Login Form with valid user credentials
  21. {
  22.     if (user == "Ron Fredericks") {
  23.         $(‘#username’).focus(function() {
  24.         this.value="Ron Fredericks";
  25.         });
  26.         $(‘#username’).focus();
  27.         $(‘#password’).focus(function() {
  28.         this.value="rf";
  29.         });
  30.         $(‘#password’).focus();   
  31.     }
  32.     else if (user == "Tommy Tuba") {
  33.         $(‘#username’).focus(function() {
  34.         this.value="Tommy Tuba";
  35.         });
  36.         $(‘#username’).focus();
  37.         $(‘#password’).focus(function() {
  38.         this.value="tt";
  39.         });
  40.         $(‘#password’).focus();           
  41.     }
  42.     else if (user == "Admin") {
  43.         $(‘#username’).focus(function() {
  44.         this.value="Admin";
  45.         });
  46.         $(‘#username’).focus();
  47.         $(‘#password’).focus(function() {
  48.         this.value="aStrongPassword";
  49.         });
  50.         $(‘#password’).focus();   
  51.     }
  52. }
  53.  
  54. function login_form(form)
  55. {
  56.     var x=form.username;
  57.     if (!x.value) {
  58.         alert("Username must be filled out");
  59.         x.focus();
  60.         return false;
  61.     }
  62.     var y=form.password;
  63.     if (!y.value) {
  64.         alert("Password must be filled out");
  65.         y.focus();
  66.         return false;
  67.     }   
  68.     return true;
  69. }
  70.  
  71. function open_window(url, target)
  72. // Open a browser window
  73. //      url is web address
  74. //      target specified the attribute or name of the window
  75. //          _blank – URL is loaded into a new window. This is default
  76. //          _parent – URL is loaded into the parent frame
  77. //          _self – URL replaces the current page
  78. //          _top – URL replaces any framesets that may be loaded
  79. //          name – The name of the window
  80. {
  81.     window.open(url, target);
  82. }
  83.  
  84. function update_background_image(imgLink)
  85. // update css body background image
  86. {
  87.         $("body").css("background", "url(‘" + imgLink + "’)");
  88. }
  89.  
  90. function update_id_text(id, text)
  91. // update css id text
  92. {
  93.         //$(div).css(id, text);
  94.         $("#"+id).text(text);
  95. }
  96.  

Create CSS Style Sheet

Code (css)
  1. @charset "utf-8";
  2. /* CSS Document */
  3. /* File: HP_main.css */
  4. /* Author: Ron Fredericks, LectureMaker LLC */
  5. /* Last Updated: 7/10/2013 */
  6.  
  7. p{font-size:14px;margin:0;padding:0;}
  8. h1{font-size:18px;margin:0;padding:0;}
  9.  
  10. #myform
  11. {
  12. width:400px;
  13. border:2px solid grey;
  14. padding:14px;
  15. margin:0 auto;
  16. }
  17.  
  18. #mygetimageform
  19. {
  20. width:400px;
  21. border:2px solid grey;
  22. padding:14px;
  23. margin:0 auto;
  24. }
  25.  
  26. #myformsupport
  27. {
  28. width:400px;
  29. padding:14px;
  30. margin:0 auto;
  31. }
  32.  
  33. .mystyle
  34. {
  35. border-bottom:1px solid grey;
  36. padding:5px 0 5px 0;
  37. margin:0 0 10px 0;
  38. }
  39.  
  40. .myerror
  41. {
  42. font-size:16px;
  43. width:350px;
  44. padding:5px 5px 5px 5px;
  45. color:red;
  46. background-color:white;
  47. }
  48.  
  49. #timeMsg
  50. {
  51. font-size:16px;
  52. width:350px;
  53. padding:5px 5px 5px 5px;
  54. background-color:white;
  55. }
  56.  
  57. #myform label
  58. {
  59. font-size:13px;
  60. float:left;
  61. width:200px;
  62. text-align:right;
  63. display:block;
  64. }
  65.  
  66. #myform span
  67. {
  68. font-size:11px;
  69. color:grey;
  70. width:200px;
  71. text-align:right;
  72. display:block;
  73. }
  74.  
  75. #myform input
  76. {
  77. border:1px solid grey;
  78. font-family:verdana;
  79. font-size:12px;
  80. color:grey;
  81. height:16px;
  82. width:150px;
  83. margin:5px 0 20px 10px;
  84. }
  85.  
  86. #myform button
  87. {
  88. clear:both;
  89. margin-left:150px;
  90. background:grey;
  91. color:#FFFFFF;
  92. border:solid 1px #666666;
  93. font-size:12px;
  94. cursor:pointer;
  95. }
  96.  
  97. #myformsupport button
  98. {
  99. clear:both;
  100. margin-left:5px;
  101. margin-right:5px;
  102. background:grey;
  103. color:#FFFFFF;
  104. border:solid 1px #666666;
  105. font-size:12px;
  106. cursor:pointer;
  107. }
  108.  
  109. #myformsupport ul
  110. {
  111. margin-left:-25px;
  112. list-style-image:url("HP_arrow.gif")
  113. }
  114.  
  115. html,
  116. body {
  117. margin:0;
  118. padding:0;
  119. height:100%;
  120. }
  121.  
  122. #container {
  123. min-height:100%;
  124. position:relative;
  125. }
  126.  
  127. #header_ctr {
  128. color:white;
  129. text-align:center;
  130. background:#333;
  131. padding:10px;
  132.  
  133. }
  134.  
  135. #header_lft {
  136. color:white;
  137. float:left;
  138. background:#333;
  139. }
  140.  
  141. #header_rt {
  142. color:white;
  143. float:right;
  144. background:#333;
  145. }
  146.  
  147. #body {
  148. padding:10px;
  149. padding-bottom:20px;   /* Height of the footer */
  150. }
  151.  
  152. #footer {
  153. color:white;
  154. text-align:center;
  155. position:absolute;
  156. bottom:0;
  157. width:100%;
  158. height:20px;   /* Height of the footer */
  159. background:#333;
  160. }
  161.  
  162. #header a, #header a:visited, #footer a, #footer a:visited {
  163. color: #eee;
  164. }

Define MySQL Data

Code (sql)
  1.  
  2. /* Prepare MySQL Table for use in project */
  3. /* File: HP_InitializeMySQL.sql           */
  4. /* Author: Ron Fredericks, LectureMaker LLC */
  5. /* Last Update: 7/10/2013 */
  6.  
  7. DROP TABLE IF EXISTS `users`;
  8.  
  9. CREATE TABLE `users` (
  10.   `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  11.   `username` varchar(60) NOT NULL,
  12.   `password` varchar(32) NOT NULL,
  13.   `email` varchar(60) NOT NULL,
  14.   `is_admin` int(1) NOT NULL DEFAULT ‘0’,
  15.   `session` varchar(32) NOT NULL,
  16.   PRIMARY KEY  (`id`),
  17.   UNIQUE KEY `username` (`username`)
  18. ) ENGINE=MyISAM;
  19.  
  20. INSERT INTO users (`username`, `password`, `email`, `is_admin`) VALUES
  21. ( "Ron Fredericks", md5("rf"), "your@domain.com", 0 ),
  22. ( "Tommy Tuba", md5("tt"), "your@domain.com", 0 ),
  23. ("Admin", md5("aStrongPassword"), "your@domain.com", 1);

Misc. Components

HP_arrow.gif

Arrow used in css li tag

Arrow used in css li tag

HP_paper.gif

Initial css background image

Initial css background image

Technorati Tags: , , , , ,

About Ron Fredericks

Ron Fredericks has a vision for using massive video content in the cloud to promote new ideas and generate new income streams for his clients. He is the Co-founder and new media technical evangelist at LectureMaker LLC. Ron has developed a streaming video distribution platform for corporate users with several plug-ins for eCommerce, data analytics, tagged video topics, massive file sharing across user devices, and secure access to name a few. Ron uses a video studio to cross-over from engineer to artist while capturing live events for educational reuse, generating green screen video clips for promotional marketing, and producing animated visual art for use in UI projects. Ron is a public speaker, blogger, and journalist promoting technology for his clients while using his video recording experience and video distribution product.
This entry was posted in PHP, Software Platforms and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(Spamcheck Enabled)