0

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?

Script47
  • 14,230
  • 4
  • 45
  • 66
  • If `header.php` outputs anything then you cannot set a session. `session_start()` has to be the first output – Cfreak Jun 18 '18 at 17:02
  • Don't close and reopen php (`?>`) after including the header.php. You're echoing white space in the body because of your line breaks. – Devon Bessemer Jun 18 '18 at 17:02
  • Just use one `` when you need to echo something that is **outside** PHP, like HTML and stuff like that. Also, `$loginpass` is defined **inside** an `if` closure, so you should try to use there and not after that block is closed, as it should only be inside the scope of that `if`. – Alejandro Iván Jun 18 '18 at 17:04
  • @AlejandroIván `session_name` is not required. – Script47 Jun 18 '18 at 17:10
  • @Script47 true, but he should always use it anyway. – Alejandro Iván Jun 18 '18 at 17:11
  • @AlejandroIván why should you '*always*' use it when it is not required? – Script47 Jun 18 '18 at 17:12
  • @Script47 basically when you mix different sites on the same server (shared hosting?), weird things can happen. I just consider it a good practice, it will take a couple seconds to write and can avoid potentially great issues. – Alejandro Iván Jun 18 '18 at 17:14

1 Answers1

0

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();
J Quest
  • 593
  • 2
  • 17