Difficulty in using ob_start (); o ob_end_flush (); and their like? [closed]

1

Follow the programming lines. I've even read a material that was available here in stackoverflow but I still can not solve my problem. I am an amateur programmer and due to this Warning I can not access another part of the Panel that concerns Step 2 for Product Registration because this warning occurs:

Strict Standards: Only variables should be passed by reference in /home/chanc184/public_html/classes/Site.class.php on line 214 Warning: Can not modify header information - headers already sent by (/ started / / chanc184 / public_html / admin / panel / pages / php on line 55

FROM THANKS TO THOSE 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><scripttype="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 of all thank you for responding promptly and second sorry for not being very specific, I thought that I had gone the line in which the problem appears, well by the searches I did in google the output occurs in this line that starts Warning:

  

... (output started at /home/chanc184/public_html/admin/painel/inc/header.php:39)

Line 39 in my script matches this 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><scripttype="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 searches I read that output can occur when there is PHP code after HTML. I'm learning more about ob_start() applications and their similar ones but I still can not solve my problem. This script is inside the Inc folder in the structure of my site and makes the call so that you can use the page cadprodutos.php , which deals with the second part of

  

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

follow 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 not be redirected to Step 2 of the process.

Site.class.php script ..... 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;
    
asked by anonymous 30.03.2017 / 19:25

2 answers

1

It's not clear 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 na 214

Post the contents of this file to the question.

Suggestions to solve

You can solve correctly that not is passed by reference.

You can also choose something fast by disabling the warning. This is not recommended. Make sure it's really inevitable because it's the right thing to do is fix the errors:

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

Place at the beginning of the running script.

This causes "strict" warnings to be hidden.

If you are in a hurry to solve the problem, hiding the warning can solve the problem and the subsequent issue.

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

Output buffering?

Regarding the functions of "output buffering", the code you posted can not tell if it is being properly applied or not, and if that is the root of the problem. It seems that the system depends on this but does not seem to correlate with the context of the problem presented.

    
30.03.2017 / 19:48
2

The function end() in:

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

Only accept references, see what references are and how they work here: link

To fix it just do it like this:

$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 is not secure ", it would be best to check mimetype which is a little more secure:

It could look 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 spacing

In this code:

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

    <?php
        ob_start();
        session_start();

There are spaces before ob_start and session_start, so do 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();
?>
    
30.03.2017 / 21:58