login script issue

Hi guys,

I am learning php and mysql and am a begginer. Everything works fine on my local server, but when I upload it to my live server http://www.immystudios.com/login.php the login script gives some errors.

Below is the error I am getting

Warning: Cannot modify header information - headers already sent by (output started at /homepages/40/d666957300/htdocs/Student/login.php:6) in /homepages/40/d666957300/htdocs/Student/login.php on line 58

This is my login.php

<!--
Login Page
this file also contains html form with two input box which will take user email and user password entered by user and then after submitting the form, the php code will match that user email and password combination in database and when it finds both results in table then it will start a session and allow user to access home page else it will show appropriate message.
-->

<?php
define("TITLE", "Login | G.A.K One Stop Eletrical & Plumbing");
include('includes/header.php');

 ob_start();
 session_start();
 require_once 'dbconnect.php';
 
 // it will never let you open (login) page if session is set
 if ( isset($_SESSION['user'])!="" ) {
  header("Location: home.php");
  exit;
 } 
 
 $error = false;
 
 if( isset($_POST['btn-login']) ) { 
  
  // prevent sql injections/ clear user invalid inputs
  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);
  
  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  // prevent sql injections / clear user invalid inputs
  
  if(empty($email)){
   $error = true;
   $emailError = "Please enter your email address.";
  } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
   $error = true;
   $emailError = "Please enter valid email address.";
  }

  if(empty($pass)){
   $error = true;
   $passError = "Please enter your password.";
 }
  
  // if there's no error, continue to login
  if (!$error) {
   
   $password = hash('sha256', $pass); // password hashing using SHA256
  
   $res=mysqli_query($conn, "SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
   $row=mysqli_fetch_array($res, MYSQLI_BOTH);
   $count = mysqli_num_rows($res); // if uname/pass correct it returns must be 1 row
   
   if( $count == 1 && $row['userPass']==$password ) {
    $_SESSION['user'] = $row['userId'];
    header("Location: home.php");
   } else {
    $errMSG = "Incorrect Credentials, Try again...";
   }
    
  }
  
 }


?>

    <div id = "register">
          <h2>Sign In.</h2>

          <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off" id = "register-form">
          
                    <?php
                     if ( isset($errMSG) ) {
                       $errMSG;            
                      }
                    ?>            

                    <label for = "email">Your email </label>
                   <input type="email" id ="email" name="email"  placeholder="Your Email" value="<?php echo $email; ?>" maxlength="40" />
                      
                      <span class="text-danger"><p class = "error"><?php echo $emailError; ?></p></span>
                   
                  
                    <label for = "password">Your Password </label> 
                   <input type="password" id = "pass" name="pass" placeholder="Your Password" maxlength="15" />
                     
                      <span class="text-danger"><p class = "error"><?php echo $passError; ?></p></span>
                 
                  
                  
                    <input type="submit" class="button submit" name="btn-login" > 
                 
                  
                   <a href="register.php">Sign Up Here...</a> 
                   </form>
      </div> 
        

        <?php 
        include('includes/footer.php');
         ?>
  
<?php ob_end_flush();  ?>

This is my header.php

<?php
	$company_Name = "G.A.K";
	include('includes/arrays.php');
?>

<!DOCTYPE html>
<html>
<head>
	<title><?php echo TITLE; ?></title>
	<link href="assets/styles.css" rel="stylesheet">
</head>

<body id = "final-example">
	<div class ="wrapper">

		<div id = "banner">
			<a href="index.php" title = "Return to Home">
				<img src = "img/banner.png" alt = "Franklin's Fine Dining">
			</a>
		</div><!-- banner -->

		<div id = "nav">
				<?php include('includes/nav.php'); ?>
		</div><!-- nav -->

	<div class = "content">

 

I would greatly appreciate some assistance in fixing this. Thanks

Headers can only be sent before anything is output to the browser. Likewise, you are using constant variables incorrectly, you are declaring constants when you do defines. Constants by design are not changed, so things like a page title, is not a constant.

I am not using a constant anymore, but I am still getting the same error

Your issue is sending headers after sending content.

How would I fix this?

My suggestion would to process all the php, such as login, registration, write to blog, etc…, at the top of the page.

For example here’s the top portion of my blog that I am current developing
[php]<?php
include_once ‘vendor/swiftmailer/swiftmailer/lib/swift_required.php’;
/*

  • Create Database Tables (if needed) and a constant PDO connection:
    /
    require_once “lib/includes/config.php”;
    use website_project\utilities\Validate;
    /
    Function folder of important and useful functions /
    include ‘lib/functions/functions.inc.php’;
    createTables(); // Create database tables if necessary:
    $data = [];
    $errMessage = FALSE;
    $register = filter_input(INPUT_POST, ‘action’);
    if (isset($register) && $register === ‘register’) {
    $data[‘name’] = filter_input(INPUT_POST, ‘name’);
    $data[‘email’] = filter_input(INPUT_POST, ‘email’);
    $data[‘password’] = filter_input(INPUT_POST, ‘password’);
    $data[‘confirmation’] = generateRandom();
    $valid = new Validate($data);
    $error = $valid->contentCheck();
    if (!is_array($error)) { // If it is not an array then send verification and save user data to database table:
    $result = send_email($data);
    if ($result) {
    registration($data, $pdo); // Save to db table mysimpleregistration calling registration function:
    }
    } else {
    $errMessage = TRUE;
    }
    }
    /
  • Login user
    /
    $login = filter_input(INPUT_POST, “action”);
    if (isset($login) && $login === ‘login’) {
    $failed = login($pdo); // Login function:
    }
    /
  • Logout user:
    /
    $logout = filter_input(INPUT_GET, ‘logout’);
    if (isset($logout) && $logout === ‘yes’) {
    logout();
    }
    /
  • Write to blog:
    /
    $submit = filter_input(INPUT_POST, ‘submit’);
    if (isset($submit) && $submit === “Submit”) {
    /
    Create a query using prepared statements /
    $query = ‘INSERT INTO mysimpleblog( userid, name, title, message, dateCreated) VALUES ( :userid, :name, :title, :message, NOW())’;
    /
    Prepared the Statement /
    $stmt = $pdo->prepare($query);
    /
    Excute the statement with the prepared values /
    $result = $stmt->execute([’:userid’ => $_SESSION[‘user’]->id, ‘:name’ => $_SESSION[‘user’]->name, ‘:title’ => filter_input(INPUT_POST, ‘title’), ‘:message’ => filter_input(INPUT_POST, ‘message’)]);
    /
    Check to see it was successfully entered into the database table. /
    if ($result) {
    header(“Location: index.php”);
    exit();
    } else {
    echo ‘Error, Something went wrong’;
    }
    }
    /
  • Display blog setup using PDO.
    /
    $query = ‘SELECT id, userid, name, title, message, dateCreated FROM mysimpleblog ORDER BY id DESC’;
    /
  • Prepare the query
    /
    $stmt = $pdo->prepare($query);
    /
  • Execute the query
    */
    $result = $stmt->execute();
    ?>
    <!doctype html>
Red-shouldered Hawk Blog
Welcome <?= isset($_SESSION['user']) ? $_SESSION['user']->name : NULL; ?> to Red-shouldered Hawk Blog!
[/php]

You can see the whole repository at https://github.com/Strider64/php_blog_complete_development and other repositories of mine (and others). I find it a great way of see how other people develop things in php and other web develop languages.

If you try to keep you php and html separated as much of possible with php usually at the top I think it would help you out tremendously. Just looking over your code it looks like mixing up php and HTML together or making it very confusing to keep it straight? I would suggest trying to your header just plain old HTML as much as possible with php only for displaying the or hiding links that members should only see for example. There are times when you have to intermingle PHP and HTML or develop functions or getting into OOP. Though most of the time when your are mixing php and HTML together it’s for displaying not processing code, but there are exceptions.

Sponsor our Newsletter | Privacy Policy | Terms of Service