Difficulty using ob_start(); ob_end_flush(); and their similar?

Asked

Viewed 241 times

1

Follow the lines of the program. Even I’ve read a material that has been available here in stackoverflow but still can not solve my problem. I’m an amateur programmer and due to this Warning I cannot access another part of the Panel that relates to Step 2 for Product Registration because this following warning occurs:

Strict Standards: Only variables should be passed by Reference in /home/chanc184/public_html/classes/Site.class.php on line 214 Warning: Cannot Modify header information - headers already sent by (output Started at /home/chanc184/public_html/admin/panel/inc/header.php:39) in /home/chanc184/public_html/admin/panel/pages/cadProducts.php on line 55

FROM NOW THANK YOU WHO CAN HELP ME. THANK YOU

<?php
    ob_start();
    session_start();
    include_once "../../config.php";
    function __autoload($classe){
        require_once "../../classes/".$classe.'.class.php';
    }
    BD::conn();
    $login = new Login('adm_', 'loja_adm');
    $site = new Site;
    $val = new Validacao;

    if(!$login->isLogado()){
        header("Location: ../");
        exit;
    }else{
        $pegar_dados = BD::conn()->prepare("SELECT * FROM `loja_adm` WHERE email_log = ? AND senha_log = ?");
        $pegar_dados->execute(array($_SESSION['adm_emailLog'], $_SESSION['adm_senhaLog']));
        $usuarioLogado = $pegar_dados->fetchObject();
    }
    if(isset($_GET['acao']) && $_GET['acao'] == 'sair'):
        if($login->deslogar()){
            header("Location: ../");
        }
    endif;
    ob_end_flush();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chances de Ouro - Painel de Administração</title>
<link href="css/style_painel.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="../../js/jquery.js"></script>
<script type="text/javascript" src="js/botoes.js"></script>
<script type="text/javascript" src="../../js/price.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<?php if(!isset($_GET['pagina'])):?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
         <?php
            $sqlVendas = BD::conn()->prepare("SELECT *, SUM(valor_total) AS total_venda FROM `loja_pedidos` 
                                                WHERE TO_DAYS(NOW()) - TO_DAYS(criado) <= 90 GROUP BY MONTH(criado)");
            $sqlVendas->execute();
            while($fetchVendas = $sqlVendas->fetchObject()){
         ?>
          ['<?php echo date('m/Y', strtotime($fetchVendas->criado));?>', <?php echo $fetchVendas->total_venda;?>],
         <?php }?>
        ]);

        var options = {
          title: 'Ganho trimestral de vendas em R$',
          'width':610,
          'height':240
        };

        var chart = new google.visualization.PieChart(document.getElementById('grafico'));
        chart.draw(data, options);
      }
    </script>
<?php endif;?> 
</head>

<body>

<div id="box">
    <div id="header">
        <div class="logo">  </div>
    </div><!-- header -->
<div id="content_painel">

First thank you for responding promptly and second sorry for not being very specific, I thought I had gone to the line where the problem is listed, well for the searches I did in google the output occurs in this line that starts the Warning:

...(output Started at /home/chanc184/public_html/admin/panel/inc/header.php:39)

Line 39 in my script matches that code in PHP

<?php if(!isset($_GET['pagina'])):?>`

    <?php
        ob_start();
        session_start();
        include_once "../../config.php";
        function __autoload($classe){
            require_once "../../classes/".$classe.'.class.php';
        }
        BD::conn();
        $login = new Login('adm_', 'loja_adm');
        $site = new Site;
        $val = new Validacao;

        if(!$login->isLogado()){
            header("Location: ../");
            exit;
        }else{
            $pegar_dados = BD::conn()->prepare("SELECT * FROM `loja_adm` WHERE email_log = ? AND senha_log = ?");
            $pegar_dados->execute(array($_SESSION['adm_emailLog'], $_SESSION['adm_senhaLog']));
            $usuarioLogado = $pegar_dados->fetchObject();
        }
        if(isset($_GET['acao']) && $_GET['acao'] == 'sair'):
            if($login->deslogar()){
                header("Location: ../");
            }
        endif;
        ob_end_flush();
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> Painel de Administração</title>
    <link href="css/style_painel.css" rel="stylesheet" type="text/css" media="screen" />
    <script type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript" src="../../js/jquery.js"></script>
    <script type="text/javascript" src="js/botoes.js"></script>
    <script type="text/javascript" src="../../js/price.js"></script>
    <script type="text/javascript" src="js/functions.js"></script>
    ***<?php if(!isset($_GET['pagina'])):?>Linha 39***
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
          function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['Task', 'Hours per Day'],
             <?php
                $sqlVendas = BD::conn()->prepare("SELECT *, SUM(valor_total) AS total_venda FROM `loja_pedidos` 
                                                    WHERE TO_DAYS(NOW()) - TO_DAYS(criado) <= 90 GROUP BY MONTH(criado)");
                $sqlVendas->execute();
                while($fetchVendas = $sqlVendas->fetchObject()){
             ?>
              ['<?php echo date('m/Y', strtotime($fetchVendas->criado));?>', <?php echo $fetchVendas->total_venda;?>],
             <?php }?>
            ]);

            var options = {
              title: 'Ganho trimestral de vendas em R$',
              'width':610,
              'height':240
            };

            var chart = new google.visualization.PieChart(document.getElementById('grafico'));
            chart.draw(data, options);
          }
        </script>
    <?php endif;?> 
    </head>

    <body>

    <div id="box">
        <div id="header">
            <div class="logo">  </div>
        </div><!-- header -->
    <div id="content_painel">

In my research I read that output can occur when there is code PHP after HTML. I’m learning more about the applications of ob_start() and its similar but I have not yet been able to solve my problem. This script is inside the folder Inc in the structure of my site and make the call so you can use the page cadprodutos.php, which deals with the second part of

Warning:in /home/chanc184/public_html/admin/panel/pages/cadProducts.php **on line 55 **

follows the script below:

h1 class="title">Cadastrar novo Produto</h1>
<?php
if(isset($_POST['acao']) && $_POST['acao'] == 'cadastrar'):
include_once "inc/slug.php";
    $img_padrao = $_FILES['img_padrao'];
    $titulo = strip_tags(filter_input(INPUT_POST, 'titulo'));
    $slug = slug($titulo);
    $categoria = $_POST['categoria'];
    $subcategoria = $_POST['subcategoria'];

    $val_anterior = $_POST['valAnterior'];
    $val_atual = $_POST['valAtual'];
    $descricao = htmlentities($_POST['descricao'], ENT_QUOTES);
    $peso = strip_tags(filter_input(INPUT_POST, 'peso'));
    $qtdEstoque = strip_tags(filter_input(INPUT_POST, 'qtdEstoque'));

    $verificar_slug = BD::conn()->prepare("SELECT id FROM `loja_produtos` WHERE slug = ?");
    $verificar_slug->execute(array($slug));
    if($verificar_slug->rowCount() > 0){
        $slug .= $verificar_slug->rowCount();
    }

    $val->set($titulo, 'Titulo')->obrigatorio();
    $val->set($categoria, 'Categoria')->obrigatorio();
    $val->set($subcategoria, 'Subcategoria')->obrigatorio();
    $val->set($val_atual, 'Valor Atual')->obrigatorio();
    $val->set($descricao, 'Descrição')->obrigatorio();
    $val->set($peso, 'Peso')->obrigatorio();
    $val->set($qtdEstoque, 'Quantidade em Estoque')->obrigatorio();

    if(!$val->validar()){
        $erro = $val->getErro();
        echo '<div class="erros">Erro: '.$erro[0].'</div>';
    }elseif($img_padrao['error'] == '4'){
        echo '<div class="erros">Informe uma imagem padrão para o produto!</div>';
    }else{
    $nomeImg = md5(uniqid(rand(), true)).$img_padrao['name'];
    $site->upload($img_padrao['tmp_name'], $img_padrao['name'], $nomeImg, '350', '../../produtos/');
    $now = date('Y-m-d H:i:s');

    $dados = array('img_padrao' => $nomeImg, 
                    'titulo' => $titulo, 
                    'slug' => $slug, 
                    'categoria' => $categoria, 
                    'subcategoria' => $subcategoria, 
                    'valor_anterior' => $val_anterior, 
                    'valor_atual' => $val_atual, 
                    'descricao' => $descricao, 
                    'peso' => $peso, 
                    'estoque' => $qtdEstoque, 
                    'qtdVendidos' => 0, 
                    'data' => $now);
        if($site->inserir('loja_produtos', $dados)){
            $_SESSION['ultimoId'] = BD::conn()->lastInsertId();
            **header("Location: index.php?pagina=passo2"); linha 55 - aqui o usuário é redirecionado para a 2 etapa do processo de cadastro de Produto**
        }
    }
endif;
?>
<div id="formularios">
    <form action="" method="post" enctype="multipart/form-data">
        <label class="img">
            <span class="title">Imagem Padrão</span>
            <input type="file" name="img_padrao" />
        </label>

        <label>
            <span class="title">Titulo do produto</span>
            <input type="text" name="titulo" />
        </label>

        <div class="fix">
            <label>
                <span class="title">Escolha a categoria:</span>
                <select name="categoria">
                    <option value="" selected="selected">Selecione...</option>
                    <?php
                        $pegar_categorias = BD::conn()->prepare("SELECT * FROM `loja_categorias` ORDER BY id DESC");
                        $pegar_categorias->execute();
                        while($cat = $pegar_categorias->fetchObject()){
                    ?>
                    <option value="<?php echo $cat->slug;?>"><?php echo $cat->titulo;?></option>
                    <?php }?>
                </select>
            </label>

            <label>
                <span class="title">Escolha a subcategoria:</span>
                <select name="subcategoria">
                    <option value="" selected="selected">Selecione...</option>
                </select>
            </label>
        </div><!--- div para fixar -->

        <div class="fix">
        <label>
            <span class="title">Valor Anterior</span>
            <input type="text" name="valAnterior" id="preco"/>
        </label>
        <label>
            <span class="title">Valor Atual</span>
            <input type="text" name="valAtual" id="preco1"/>
        </label>
        </div><!--- div para fixar -->

        <label>
            <span class="title">Escreva as características deste produto</span>
            <textarea name="descricao" cols="30" rows="5" id="tiny"></textarea>
        </label>

        <div class="fix">
        <label>
            <span class="title">Peso do produto</span>
            <input type="text" name="peso"/>
        </label>
        <label>
            <span class="title">Quantidade em estoque</span>
            <input type="text" name="qtdEstoque" />
        </label>
        </div><!--- div para fixar -->

        <input type="hidden" name="acao" value="cadastrar" />
        <input type="submit" value="Próximo Passo" class="btn"/>
    </form>
</div>

So that’s it.... I can even register a Product but I can’t be redirected to Step 2 of the process.

Script do Site.class.php..... line 214

function upload($tmp, $name, $nome, $larguraP, $pasta){

    **$ext = end(explode('.', $name));*****LINHA 214***
    if($ext=='jpg' || $ext == 'JPG' || $ext == 'jpeg' || $ext == 'JPEG'){
            $img = imagecreatefromjpeg($tmp);
    }elseif($ext == 'png'){
            $img = imagecreatefrompng($tmp);
    }elseif($ext == 'gif'){
            $img = imagecreatefromgif($tmp);
    }
    list($larg, $alt) = getimagesize($tmp);
    $x = $larg;
    $y = $alt;
    $largura = ($x>$larguraP) ? $larguraP : $x;
    $altura = ($largura*$y)/$x;

    if($altura>$larguraP){
            $altura = $larguraP;
            $largura = ($altura*$x)/$y;
    }
    $nova = imagecreatetruecolor($largura, $altura);
    imagecopyresampled($nova, $img, 0,0,0,0, $largura, $altura, $x, $y);

    imagejpeg($nova, $pasta.$nome);
    imagedestroy($img);
    imagedestroy($nova);
    return (file_exists($pasta.$nome)) ? true : false;

2 answers

2

The function end() in:

$ext = end(explode('.', $name));

Only accepts references, see what is and how the references works here: http://php.net/manual/en/language.references.pass.php

To fix just do so:

$dados = explode('.', $name);
$ext = end($dados);

Or so:

$ext = explode('.', $name);
$ext = $ext[count($ext) - 1];

However this type of file type check based on the extension "it’s not safe", would be better to check the mimetype which is a little safer:

Could stay like this:

function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

function upload($tmp, $name, $nome, $larguraP, $pasta){
    $type = mimeType($tmp);

    if($type == 'image/jpeg'){
            $img = imagecreatefromjpeg($tmp);
    }elseif($type == 'image/png'){
            $img = imagecreatefrompng($tmp);
    }elseif($type == 'image/gif'){
            $img = imagecreatefromgif($tmp);
    } else {
       return false;
    }

    list($larg, $alt) = getimagesize($tmp);
    $x = $larg;
    $y = $alt;
    $largura = ($x>$larguraP) ? $larguraP : $x;
    $altura = ($largura*$y)/$x;

    if($altura>$larguraP){
            $altura = $larguraP;
            $largura = ($altura*$x)/$y;
    }
    $nova = imagecreatetruecolor($largura, $altura);
    imagecopyresampled($nova, $img, 0,0,0,0, $largura, $altura, $x, $y);

    imagejpeg($nova, $pasta.$nome);
    imagedestroy($img);
    imagedestroy($nova);

    return file_exists($pasta.$nome);
}

About the spacing

In this code:

<?php if(!isset($_GET['pagina'])):?>

    <?php
        ob_start();
        session_start();

There are spaces before the ob_start and session_start, do so to avoid them:

<?php

if(!isset($_GET['pagina'])):
    ob_start();
    session_start();

    include_once "../../config.php";
    function __autoload($classe){
        require_once "../../classes/".$classe.'.class.php';
    }
    BD::conn();
    $login = new Login('adm_', 'loja_adm');
    $site = new Site;
    $val = new Validacao;

    if(!$login->isLogado()){
        header("Location: ../");
        exit;
    }else{
        $pegar_dados = BD::conn()->prepare("SELECT * FROM `loja_adm` WHERE email_log = ? AND senha_log = ?");
        $pegar_dados->execute(array($_SESSION['adm_emailLog'], $_SESSION['adm_senhaLog']));
        $usuarioLogado = $pegar_dados->fetchObject();
    }
    if(isset($_GET['acao']) && $_GET['acao'] == 'sair'):
        if($login->deslogar()){
            header("Location: ../");
        }
    endif;
    ob_end_flush();
?>

1


It’s unclear where the problem is.

Apparently a single error triggered the following.

Strict Standards: Only variables should be passed by reference 

The error points to classes/Site.class.php in 214

Post the contents of this file to the question.

Suggestions for solving

You can solve it the right way it is nay go by reference.

You can also opt for something fast by disabling "Warning". This is not recommended. Do it if it really is inevitable because the right thing is to correct the mistakes:

ini_set('display_errors', '0');
error_reporting(E_ALL ^ E_STRICT);

Place at the beginning of the running script.

This causes "Strict" type warnings to be hidden.

If you are in a hurry to resolve the issue, hiding the warning may resolve the issue and subsequent ones.

Of course, I cannot guarantee that it will work because there may be invocations in other parts of the system that modify these setagens. Be aware, please be aware.

Output buffering?

As for the functions of "output buffering", by the code you posted it is not possible to say whether it is being applied well or not and whether this is the root of the problem. It seems that the system depends on it but does not seem to have correlation with the context of the problem presented.

Browser other questions tagged

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