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

Asked

Viewed 64 times

0

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

I have a file saved as PHP that works as an "index", basically full of HTML. About halfway through the structure of the file, in body, I want to insert a visit counter into 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:

"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 that are being included are these:

Filing cabinet total visits.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 one (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.";
?>
  • A. Goes posted on my server the 3 files, I tested, and here with me gave no mistake no. The strange is the number of visitors online. See http://kithomepage.com/sos/session_start.php

  • Hi wmsouza! I researched about the problem... but what I seek (and maybe I was happy in the title but unhappy in the description of the post) is the way to fix in my specific case... maybe something like André answered... The solution well explained was not found by me in the forum (maybe I have not exhausted the research, but I have made a lot of progress...). Perhaps such a solution, since it is such a common problem, if well detailed, can be of great use to many of little experience like me... Leo, thank you for the test! By elimination, you have already said enough! Thank you all for the speed in the answers!

2 answers

0

To resolve session related error another approach can be used. Basically you create a new file, for example php session. and place 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 move to incluit at the top of each file (in the first line)

require_once 'sessao.php';
iniciar_sessao();

It won’t be a problem if you call it more than once, because the function iniciar_sessao() already makes the appropriate treatment.

  • Thanks for the tip, Juven_v! I used it here! It really gets better!

0

Man, I’d change the way I do it.

  1. would bring the includes to the top of the file
  2. inside includes, in place of echo would throw the results for variables
  3. finally where the includes were, would echo the variables created by the includes.
  • Andre, right on! I was unhappy in the description of the problem. I think I understand what the problem is: calling php in the middle of the body (especially after another php with "echo"), I want to forward information after sending the "header", which causes the warning. The question is how I would make the php layout (I suspected it should be at first) so that I could "call it" in place of the body without being through include, but just showing the message I need. Would it be possible to explain or indicate reading about your solution with the variables? I don’t know how to do this!

  • Dude, first you have to get the full visits.php

    1. your query of totalvisitas.php seems wrong, you should return something like a select Count() visits* in order to use the visits... or else this field must exist in the visits table; 2. you are looping the result and will print several times the text: "Total site visits" 3. this file should return only the result of query Something like: $Pdo = new PDO('mysql:host=localhost;dbname=counter', 'root', ') $Row = $Pdo->query( "select Count(*) the visits from visits" )->fetch(); $visits = $Row["visits"]; $Pdo = null;
  • Already the user sonline.php would just change the echo "Há $visitors visitantes online."; for $visitanteonline = "Há $visitors visitantes online."

  • Last would climb the includes to the top and give an echo in those variables $visitas and $visitanteonline where today the includes appear in the index.

  • André, thank you so much for the clarification and readiness to help! You were right! I did everything you said and I also took the tip from Juven.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.