0

I'm trying to password protect my webpage with php using a separate access.php that goes as follows:

<?php
    session_start();
    //access.php
    //put sha1() encrypted password here - example is 'hello'
    $password = 'thepassword';

    session_start();
    if (!isset($_SESSION['loggedIn'])) {
        $_SESSION['loggedIn'] = false;
    }

    if (isset($_POST['password'])) {
        if ($_POST['password'] == $password) {
            $_SESSION['loggedIn'] = true;
        } else {
            die ('Incorrect password');
        }
    }

    if (!$_SESSION['loggedIn']): ?>

    <html><head><title>Login</title></head>
      <body>
        <p>You need to login</p>
        <form method="post">
          Password: <input type="password" name="password"> <br />
          <input type="submit" name="submit" value="Login">
        </form>
      </body>
    </html>

    <?php
    exit();
    endif;
    ?>

And then doing a

<?php require('access.php'); ?>

In the header of my webpage I'm trying to protect but I keep getting this error message:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /directory/example.com/index.php:60) in /directory/example.com/access.php on line 2

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /directory/example.com/index.php:60) in /directory/example.com/access.php on line 2'

Line 60 is where I require access.php

I've seen other posts with this same error but I simply don't know what I'm doing wrong here since other solutions haven't quite worked. Thanks in advance for the help!

Kamerov
  • 109
  • 1
  • 4
  • 11
  • Trying to implement what this article does https://stackoverflow.com/questions/286938/what-is-the-best-way-to-password-protect-folder-page-using-php-without-a-db-or-u – Kamerov Jul 30 '18 at 23:04
  • Did you use `session_start` twice intentionally? Regardless, if any of those previous 59 lines output anything, you won't be able to start the session here. – Don't Panic Jul 30 '18 at 23:07
  • if Line 60 is where you require `access.php` and the error literally tells you to look at "access.php on line 2", then that's your clue. That line is your `session_start`, so where in index.php before line 60 did you already start sending output? – Mike 'Pomax' Kamermans Jul 30 '18 at 23:07
  • @PaulCrovella This helped me thanks! Turns out all I needed to do was require access.php BEFORE ANY html code. – Kamerov Jul 30 '18 at 23:16

0 Answers0