0

Edit: I fixed it, the problem was the spaces before <?php. Thanks for the comments.

Sessions are working on all pages except index.php

The error: session_start(): Cannot start session when headers already sent in /home/site/public_html/connection.php on line 13

connection.php:

<?php

try {
$db=new PDO('mysql:host=localhost;dbname=testdb','testuser','123456');
$db->exec("SET CHARACTER SET utf8"); }
catch(PDOExpception $e) {
echo $e->getMessage(); }

ob_start(); session_start(); # (line 13)

?>

index.php:

<?php
include 'connection.php'; include 'seo.php';
$connect_site=$db->prepare("SELECT * FROM site WHERE id=?");
$connect_site->execute(array(1));
$site=$connect_site->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE HTML>
<html>
<head>
...
  • 1
    Possible duplicate of https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php – 04FS Jun 04 '19 at 11:44
  • 1
    session_start should go first. – Jonnix Jun 04 '19 at 11:47
  • The error message talks about line 13 in connection.php, but what you have shown us does not even appear to have 13 lines - unless you have trailing whitespace/newlines _after_ the `?>`. Remove that `?>`, it is not necessary at the very end of a script file - and that it frequently causes errors like this, which is why most coding guidelines recommend that anyway. – 04FS Jun 04 '19 at 11:48
  • @Jonnix I tried it, still same. –  Jun 04 '19 at 11:49
  • 1
    If you moved it, you should have gotten at least a slightly different error message. – Jonnix Jun 04 '19 at 11:50
  • @04FS I tried that too, nothings change –  Jun 04 '19 at 11:52
  • Why are you trying to pick up the session only after making the database connection to begin with? If _that_ throws an exception and you output it in this place, ob_start afterwards will be to late anyway, in that case session_start will always fail here. – 04FS Jun 04 '19 at 11:56
  • You can also try and use `headers_sent` to figure out where the headers got sent. – 04FS Jun 04 '19 at 11:57

2 Answers2

0

You have to put always the

session_start();

At the start of all your codes. Nothing had to go before whatever it is :)

Enjoy coding !

SuRo
  • 38
  • 11
  • It's already at the top of all pages. All the pages are contains similar code structure like start of index.php But the other pages runs well, index.php doesn't. –  Jun 04 '19 at 11:59
  • But on you're code it's not in first so try it out, when i say first it's the first line of all. – SuRo Jun 04 '19 at 12:04
0

Change your code in connection.php

<?php ob_start(); session_start();  ?>
<?php
    try {
      $db=new PDO('mysql:host=localhost;dbname=testdb','testuser','123456');
      $db->exec("SET CHARACTER SET utf8"); }
    catch(PDOExpception $e) {
      echo $e->getMessage(); 
    }
?>
Alok Mali
  • 2,821
  • 2
  • 16
  • 32