skip to Main Content

I am working on a site at the moment with PHP and Twitter Bootstrap.

If I put session_start() first then the layout messes up because Bootstrap requires <!DOCTYPE html> first.

If I put <!DOCTYPE html> then I cant use sessions.

Index.php – sessions fail here :

<!DOCTYPE html>
<?php 
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);

  require_once('../php/init.php');

  if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $errors = [];

    if (empty($_POST['username'])) array_push($errors, 'A username is required');
    if (empty($_POST['password'])) array_push($errors, 'A password is required');

    if (empty($errors)) {
      echo 'No Errors';

      if (login($username, $password)) {
        echo 'Logged In';
      }
    }

  } 

?>

index.php – layout fails here:

<?php 

  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);

  require_once('../php/init.php');

  if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $errors = [];

    if (empty($_POST['username'])) array_push($errors, 'A username is required');
    if (empty($_POST['password'])) array_push($errors, 'A password is required');

    if (empty($errors)) {
      echo 'No Errors';

      if (login($username, $password)) {
        echo 'Logged In';
      }
    }

  } 

?>

<!DOCTYPE html>

init.php:

<?php

if (session_id() == "" || !isset($_SESSION)) {
    session_start();
}

require 'database/connect.php';
require 'functions.php';

Any help is appreciated

Many Thanks

Jacob

2

Answers


  1. Chosen as BEST ANSWER
    <?php 
    
      code...
    
    ?>
    <!DOCTYPE html>
    

    Turns out it doesnt like whitespace. The above worked. The below didnt work.

    <?php 
    
      code...
    
    ?>
    
    <!DOCTYPE html>
    

  2. I think it is better if you provided a sample of your code to understand the problem correctly. Using session_start before the DOCTYPE should not cause a problem but I will try to write a solution based on my understanding.

    You can put like this having both on the same line with no spaces before or after.

    <?php session_start(); ?><!DOCTYPE html>
    

    It is better if you have a function that is responsible for header part

    header() {
        include 'header.php';
    }
    
    bootstrap() {
        session_start();
        header();
        body();
        footer();
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search