How to Use Bootstrap with PHP

How to Use Bootstrap with PHP

Approximately 18 million websites were using the Bootstrap framework by the end of the year 2018. More and more websites have started using the framework in 2019 and the numbers are expected to rise. In fact, Bootstrap has become the most loved choice of developers when building powerful web applications. Bootstrap Laravel and PHP templates also make it simpler for users to build complex and powerful web apps. 

PHP is a server-side programming language, which means that you will need a local server to run PHP code. Developers who use Bootstrap with PHP will be able to enjoy plenty of benefits. Here is a step by step guide on how you can use the Bootstrap framework with PHP. 

Prerequisite

  • Basic knowledge of Bootstrap, HTML and PHP
  • Text Editor
  • A server to run PHP files ( You can install local servers to use your computer as a server by using XAMPP or WAMP) 

Getting Started

Two separate methods can be used to include PHP with Bootstrap. 

Locally Downloading the Files

You can visit https://getbootstrap.com/docs/4.3/getting-started/download/ to locally download the files. After downloading the files, addbootstrap.min.css file in the <head> and bootstrap.min.js in the <body> .  Some jQuery functionalities like tabs and dropdowns are dependent on popper.js and jQuery. So, you will need to include jquery.min.js and popper.min.js before you load bootstrap.min.js. 

Using CDN

CSS

Copy the following code to the <head> of your HTML file. 

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

JS

The JS functionalities of tabs, dropdowns, and other Bootstrap components depend on popper.js and jQuery. So, you will need to include both popper.js and jQuery before loading Bootstrap JavaScript file to ensure proper functioning. 

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

We will be using the CDN method in this example. Initially, you will need to create an index.php file on a new folder within the local server and include Bootstrap CDN into it. 

 <!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>  
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

All Bootstrap components that includes buttons, tabs, and more will be available for use. In addition, you can also integrate PHP functionalities as per your project requirements. 

 How to create a simple PHP form with the Bootstrap framework.  A simple PHP form that is built with Bootstrap will look like this. 


The code for designing a UI for the form is given below. 

 
 <form role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <div class="form-group row">
        <label for="inputEmail" class="col-sm-2 col-form-label">Email</label>
        <div class="col-sm-10">
          <input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email">
        </div>
      </div>
      <div class="form-group row">
        <label for="inputUser" class="col-sm-2 col-form-label">User Name</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="inputUser" name="user" placeholder="Username">
        </div>
      </div>
      <div class="form-group row">
        <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" id="inputPassword" name="password" placeholder="Password">
        </div>
      </div>
      <div class="form-group row">
        <div class="offset-sm-2 col-sm-10">
          <input type="submit" value="Sign in" name="submit" class="btn btn-primary"/>
        </div>
      </div>
    </form>

The role attribute in the code is used for accessibility while the method attribute is used to specify the method. Two different types of methods are used in PHP, Get and Post. The former method is used when you want to add the value in the input field to the URL to retrieve data. While, the latter method is used to send input field value for processing. 

The action attribute can be used to indicate the PHP file’s URL. THe PHP and HTML code are to be written in the exact same file, which is indicated by the htmlspecialchars($_SERVER["PHP_SELF"]. ($_SERVER["PHP_SELF"] is the variable in the context and is used to return the filename of the script that is currently being executed. The first part, htmlspecialchars serves the crucial purpose of converting <,>, and other special characters into HTML entities. 

The Bootstrap form we created will look like this.

Username, Email Id, and Password are the input fields of the form. You can also see a submit button ( Sign in) with the form. 

The next step is to validate if there are any inputs in the fields and give a suitable feedback to users. The following code will help you to do that. 

  $email= $_POST['email'];
  $name= $_POST['user'];
  $password = $_POST['password'];

The variable email in the code is used to assign the email. The other variables, username and password are used to assign username and password respectively.

if (isset($_POST['submit'])) {
    // Check if name has been entered
    if (empty($_POST['user'])) {
        $errName = 'Please enter your user name';
    }
    // Check if email has been entered and is valid
    else if (empty($_POST['email'])) {
        $errEmail = 'Please enter a valid email address';
    }
    // check if a password has been entered and if it is a valid password
    else if (empty($_POST['password']) || (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0)) {
        $errPass = '<p class="errText">Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit</p>';
    } 
    else {
        echo "The form has been submitted";
    }
}

If there are no inputs in any one of the fields, an error message should be delivered to the user. Users who do not set password as per preset criterions and the ones who do not enter a valid email id will also receive an error message.

If the username, password, and email are all valid and entered into the respective fields accurately, the following result will appear on the screen of users devices.

The entire code you will need to design a simple Bootstrap Form is given below.

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>Document</title>
</head>
<body>
  <?php
    $email= $_POST['email'];
    $name= $_POST['user'];
    $password = $_POST['password'];    
    if(isset($_POST['submit'])) {
      // Check if name has been entered
      if(empty($_POST['user'])) {
        $errName= 'Please enter your user name';
      }
      // Check if email has been entered and is valid
      else if(empty($_POST['email'])) {
        $errEmail = 'Please enter a valid email address';
      }
      // check if a password has been entered and if it is a valid password
      else if(empty($_POST['password']) || (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["password"]) === 0)) {
        $errPass = '<p class="errText">Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit</p>';
      } else {
        echo "The form has been submitted";
      }
    }
  ?>
  <div class="container">
    <form role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <div class="form-group row">
        <label for="inputEmail" class="col-sm-2 col-form-label">Email</label>
        <div class="col-sm-10">
          <input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email">
          <?php echo $errEmail; ?>
        </div>
      </div>
      <div class="form-group row">
        <label for="inputUser" class="col-sm-2 col-form-label">User Name</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="inputUser" name="user" placeholder="Username">
          <?php echo $errName; ?>
        </div>
      </div>
      <div class="form-group row">
        <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" id="inputPassword" name="password" placeholder="Password">
          <?php echo $errPass; ?>
        </div>
      </div>
      <div class="form-group row">
        <div class="offset-sm-2 col-sm-10">
          <input type="submit" value="Sign in" name="submit" class="btn btn-primary"/>
        </div>
      </div>
    </form>
  </div>
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

Leave a Reply

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