session_start (): Can not start session when headers already sent

6

I receive this warning that does not allow me to continue:

  

Warning: session_start (): Can not start session when headers already sent in C: \ xampp \ htdocs \ bancoinfocial \ index.php on line 45

     

Notice: Undefined variable: _SESSION in C: \ xampp \ htdocs \ bancoinfocial \ principal.php on line 3

And this is my code:

index.php

<div id="principal" hidden>
    <?php
    session_start();
    require_once("principal.php");
    ?>
</div>

principal.php

<div>
<?php
echo $_SESSION['fullname'];
?>
</div>

That is, I invoke principal.php from index.php where you can not log in by headers already sent even though it is the first instruction that I execute in each invocation of the session_start() method.

    
asked by Alejandro Martinez Delgado 19.04.2018 в 15:41
source

4 answers

7

session_start() is a function that sends several HTTP headers depending on the configuration, that can not be executed after content has been written (because then the headers can not be modified).

You have <div> in your HTML code that precede the PHP% session_start and that is what is causing the problem. session_start should go first, before anything is written. So you must move it at the beginning of everything to avoid that error:

<?php session_start(); ?>
<div id="principal" hidden>
<?php
require_once("principal.php");
?>
</div>
    
answered by 19.04.2018 / 15:51
source
6

The problem is because you are doing div in your html before validating the session. In PHP the session_start(); must go before anything else. Even before div .

Try the following:

index.php

<?php
    session_start(); 
?>
<div id="principal" hidden>
    <?php
        require_once("principal.php");
    ?>
</div>
    
answered by 19.04.2018 в 15:51
1

To make it work you have to move the session session_start to the beginning of the index.php.

Index.php

<?php
        session_start();
?>
<div id="principal" hidden>
    <? 
        $_SESSION['fullname'] = "Delcio";
        require_once("principal.php");
    ?>
</div>

principal.php

<div>
    <?php
        echo $_SESSION['fullname'];
    ?>
</div>
  

Remember that so you can paint on the div what the session variable has   $ _SESSION ['fullname']; You must remove the hidden from the div.

    
answered by 19.04.2018 в 16:07
0

possibly the problem is in the PHP version you are using. If you have PHP 7.2, lower it to 7.1 which is a much more stable version.

It also enjoys most of the great advances that 7.2 especially the speed of execution.

I had the same problem when I changed in cPanel from version 5.4 to 7.2, when I changed it to 7.1 everything went back to normal.

If there is no powerful reason to use version 7.2, change to 7.1.

I hope this helps.

    
answered by 05.09.2018 в 00:49