PHP会话无法在实时服务器上启动[重复]

This question already has an answer here:

Currently i have a php login script which uses session's, it work's fine on my localhost but not on my 1&1 live server.

<?php include 'header.php'; ?>


<?php

// start session
session_start();

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

if (isset($_POST['submit'])) {

// save username and password inputted values from form
$loginuser = trim($_POST['username']);
$loginpass = trim($_POST['password']);


 if($loginstatement = $connect->prepare("SELECT password FROM users WHERE 
 username = ?")) {

$loginstatement -> bind_param("s", $loginuser);
$loginstatement -> execute();
$loginstatement -> bind_result($result);
$loginstatement -> fetch();
$loginstatement -> close();

}

if(password_verify($loginpass, $result)) {
 session_start();
 $_SESSION['username'] = $loginuser; // save session in variable
 header("location: index.php");
 } else {
 echo '<script>';
 echo 'alert("invalid credentials")';
 echo '</script>';
 }


}

// close connection

$connect->close();

?>

the code executes just fine, but it doesn't seem to be starting the session?

</div>

You can't create a session after output, for that you have to put session_start(); on the very top of your script.

In your situation, there are two possible reasons why it's not working

  1. If your include output any data or has closed <?php ?> tags
  2. Your current script has already been closed before you call session_start();