Creating the App Startup Files for Your Web App

By Paul McFedries

All web apps perform a number of chores at the beginning of any task. On the back end, these initialization chores include starting a user session and connecting to the database, and on the front end the startup includes outputting the app’s common HTML (especially the <head> section) and including the app’s common components, such as a header and footer.

Rather than repeating the code for these startup chores in every file, you should create two files — one for the back end initialization and one for the front end’s common code — and then include the files as you begin each web app task.

Creating the back-end initialization file

When performing any task, a typical web app must first run through a number of back-end chores, including the following:

  • Setting the error reporting level
  • Starting a session for the current user, if one hasn’t been started already
  • Creating a token for the session
  • Including common files, such as a file of constants used throughout the app
  • Connecting to the database, if the app uses server data

You should store this file in your web app’s private/common/ directory.:

<?php
  // Make sure we see all the errors and warnings
  error_reporting(E_ALL | E_STRICT);

  // Start a session
  session_start();

  // Have we not created a token for this session,
  // or has the token expired?
  if (!isset($_SESSION['token']) || time() > $_SESSION['token_expires']){
    $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(16));
    $_SESSION['token_expires'] = time() + 900;
    $_SESSION['log_id'] = 1;
  }

  // Include the app constants
  include_once 'constants.php';

  // Connect to the database
  $mysqli = new MySQLi(HOST, USER, PASSWORD, DATABASE);

  // Check for an error
  if($mysqli->connect_error) {
    echo 'Connection Failed!
       Error #' . $mysqli->connect_errno
        . ': ' . $mysqli->connect_error;
    exit(0);
  }
?>

This code cranks up the error reporting to 11 for the purposes of debugging, starts a new session, creates a session token (if needed), includes the constants file (which contains the database credentials), and then connects to the database and creates a MySQLi object. Note, too, that $_SESSION['log_id'] was set to 1, but this is temporary.

You want to use error_reporting(E_ALL | E_STRICT) when you’re developing your web app because you want the PHP processor to let you know when something’s amiss, either as an error (E_ALL) or as non-standard PHP code (E_STRICT). However, you certainly don’t want your app’s users to see these errors or warnings, so when you’re ready for your web app to go live, edit initialization.php to follow this statement:

error_reporting(E_ALL | E_STRICT)

with these statements:

ini_set(&apos;display_errors&apos;, 0);
ini_set(&apos;log_errors&apos;, 1);
ini_set(&apos;error_log&apos;, &apos;../private/logs/error_log&apos;);

These statements configure PHP to not display errors onscreen, but to log them to a file, the name and path of which is specified in the final statement.

Creating the front-end common files

Each page of your web app has a common structure. For example, the top part of each page includes the following elements:

  • The DOCTYPE and the <html> tag
  • The head element, including the <meta> tags, page title, CSS <link> tags, and JavaScript <script> tags
  • An event handler for jQuery’s ready event
  • The <body> tag
  • Common page elements, such as the <header>, <nav>, and <main> tags

Here’s an example, which is named public/common/top.php:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FootPower! | <?php echo $page_title ?></title>
  <link href="css/styles.css" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
     
    });
  </script>
</head>
<body>
  <header role="banner">
  </header>
  <main role="main">
    <article role="contentinfo">
      <header class="article-header" role="banner">
        <div class="header-title">
          <h1><?php echo $page_title ?></h1>
        </div>
      </header>

In this code, note that the page title is given by the following inline PHP:

<?php echo $page_title ?>

The idea here is that each page will set the $page_title variable just before including top.php, which enables you to define a custom title for each page. For example, the home page might do this:

<?php
  $page_title = 'Home';
  include_once 'common/top.php';
?>

Note that this same title also gets inserted in the page header element, within the <h1> tag.

Most web apps also include a sidebar — defined by an <aside> tag — that includes info common to all pages, such as a description of the app, instructions for using the app, the latest app news, or a newsletter sign-up form. For this sidebar, create a separate file called, say, public\common\sidebar.php and include your code:

<aside role="complementary">
  Your sidebar text and tags go here
</aside>

Finally, you need a file to handle the common elements that appear at the bottom of each page, including the </main> closing tag, a footer, and the </body> and </html> closing tags. For this code, create a separate file called, say, public\common\bottom.php and add your code:

</main>
  <footer role="contentinfo">
      Copyright <?php echo date('Y'); ?> Your Name
  </footer>
  <script src="js/data.js"></script>
  <script src="js/user.js"></script>
</body>
</html>

The footer uses the PHP statement echo date('Y') to output the current year for the Copyright notice. This file also adds references to the app’s two external JavaScript files: data.js and user.js. Adding these at the bottom of the page (instead of the usual place in the page’s head section) ensures that your JavaScript code can work with the elements added to the page on the fly.

Building the app home page

With the initialization files in place, it’s time to build the skeleton for the app’s home page. At the moment, this page is nothing but PHP:

="code"><?php
  include_once '../private/common/initialization.php';
  $page_title = 'Home';
  include_once 'common/top.php';
?>
Main app content goes here
<?php
  include_once 'common/sidebar.php';
  include_once 'common/bottom.php';
?>

Save this file as index.php in the web root directory.