How to include php files containing "session_start ()", "echo", etc. in another php file, without the error "headers already sent"?

0

I have already investigated here in the Stack about such an error, but I have not found a way to solve my specific problem.

I have a file saved as PHP that works like an "index", basically full of HTML. Halfway through the file structure, in body , I want to insert a hit counter on the site and an online user display. I made a PHP file for each of these two things and included (with "include") within this "index". However, the following error occurred:

"Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\wamp64\www\administrador\indexadmin.php:192) in C:\wamp64\www\administrador\usuariosonline.php on line 3
Call Stack
#   Time    Memory  Function    Location
1   0.0007  244648  {main}( )   ...\indexadmin.php:0
2   0.0050  265496  include( 'C:\wamp64\www\administrador\usuariosonline.php' ) ...\indexadmin.php:206
3   0.0050  265544  session_start ( )   ...\usuariosonline.php:3"

How to solve?

Here are the codes:

the "index.php" is this (no body):

<div class="col col-3">
<div class="visitassite">

    <h4>Visitas ao Site</h4>        

    <p>

    <?php include "totalvisitas.php"; ?>

    </p>
</div>
</div>


<div class="col col-3">
<div class="usuariosonline">

    <h4>Usuários Online</h4>        

    <p>

    <?php include "usuariosonline.php"; ?>

    </p>
</div>
</div>

The two php files being included are the following:

  

File totalvisitas.php :

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=contador', 'root', '');
}catch (PDOException $e){
    echo $e->getMessage();
}
$selecionar = $pdo->prepare("SELECT * FROM visitas");
$selecionar->execute();
$resultados = $selecionar->fetchAll(PDO::FETCH_ASSOC);
foreach($resultados as $results):
    echo "Total de visitas ao site: ".$results['visitas'];
    $contar = $results['visitas'] + 1;
    $update = $pdo->prepare("UPDATE visitas SET visitas=:visitas");
    $update->bindValue(':visitas', $contar);
    $update->execute();
endforeach;
?>

The other is this (usuariosonline.php):

<?php
session_start();
$session_path = session_save_path();
$visitors=0;
$handle = opendir($session_path);
while (($file = readdir ($handle)) != FALSE)
{
    if ($file!="."&&$file!="..")
    {
        if (preg_match("/^sess/",$file))
        $visitors++;
    }
}
echo "Há $visitors visitantes online.";
?>
    
asked by anonymous 28.12.2017 / 07:04

2 answers

0

Dude, I would change the way you do that.

  • would bring the includes to the top of the file
  • inside the includes, instead of the echo would throw the results for variables
  • finally where the includes were, it would echo the variables created by the includes.
  • 28.12.2017 / 12:39
    0

    To solve the error related to the session can be used another approach. Basically you create a new file, for example session.php and put the following content:

    //chama o session_start apenas se não tiver sido chamado anteriormente
    function iniciar_sessao(){
        if(!(session_status() === PHP_SESSION_ACTIVE)){
            session_start();
        }
    }
    

    With this you can remove all calls to session_start in the other files, and pass the incluit to the top of each file (in the first line)

    require_once 'sessao.php';
    iniciar_sessao();
    

    It will not be a problem if you call it more than once, because the iniciar_sessao() function already does the proper processing.

        
    28.12.2017 / 17:40