PHP does not redirect to another page

Asked

Viewed 672 times

1

I have this code in "if(isset($_POST['send']){" when I try to redirect to another page, or create a cookie via php simply does not happen in.

<!doctype html>
<html>
<head>
    <!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>-->
    <link href="Style/FazerAtividade.css" rel="stylesheet" type="text/css">
    <meta charset="utf-8">
    <title>Fazer Atividade</title>
</head>
<body>
<?php
    header('Content-Type: text/html; charset=utf-8');

    include_once("Sys/defines.php");
    require_once("../Classes/BD.class.php");
    include_once("../Classes/Login.class.php");

    $objLogin = new Login();

    if(!$objLogin->isLoggedIn()){
        Header("Location: ../index.php");
        exit();
    }

    if(isset($_GET['acao']) && $_GET['acao']=='sair'){
        $objLogin->logOut();
        header('Location: ./');
    }

    $dados = $objLogin->getDados($_SESSION['viewcoreonline_user']);
    if (!is_null($dados)){extract($dados, EXTR_PREFIX_ALL, 'user');}else{header('Location: ./');}


    $valor = $_COOKIE['atividade'];;
    $busca = BD::conn()->prepare("SELECT * FROM `atividade` WHERE `cod` = '$valor'");
    $busca->execute();
    $documento = $busca->fetch();
    $tipoRespostaComplet = $documento['tipo_resposta'];
    $tipoResposta = explode("-", $documento['tipo_resposta']);
    $questoes = explode("-", $documento['questoes']);
    $alternativas = explode("-", $documento['alternativa']);
    $respostaCorretaComplet = $documento['resposta_correta'];
    $respostaCorreta = explode("-", $documento['resposta_correta']);
    $qtdQuestoes = $documento['qtd_questoes'];
    $envio = date("d.m.y");
    echo"
        <article class='textActivity'>
            <h2>$documento[titulo]</h2>
            <p>
                $documento[texto_motivacional]   
            </p>
            <div class='controls'>
                <input class='submit' type='submit' onclick='active(1)' name='enviar' value='Enviar' title='Enviar' data='hy'/></input>
                <input class='submit' type='submit'  name='cancelar' value='Cancelar' title='Cancelar' data='hy'/></input>
            </div>
        </article>
        <header class='questionNumbers'>
                <div onclick='select(900)'>
                    <hr>
                    <hr>
                </div>
            <section>
    ";
    for($x=1;$x<=$qtdQuestoes;$x++){
        echo"<a id='n$x'href='#q$x' onclick='select($x)'>$x</a>";
    }
    echo"        
            </section>
            <div onclick='select(1000)'>
                <hr>
                <hr>
            </div>
        </header>
        <form form method='post' enctype='multipart/form-data' class='all_question scroll'>
    ";
    for($x=1;$x<=$qtdQuestoes;$x++){
        $vetor = $x-1;
        echo"
            <article class='question_itens' id='q$x'>
            <h2>Questão - $x</h2>
            <h3>$questoes[$vetor]</h3>
        ";
        if($tipoResposta[$vetor]==1){
            $escolhas = explode("_", $alternativas[$vetor]);
            echo"
                <div class='radioBtn'>
                    <ul>
                        <li>
                            <input type='radio' id='a-option$x' name='certa$x' class='answer' value='a' checked>
                            <label for='a-option$x'>A</label>
                            <div class='check'></div>
                            <p for='a-option$x'>$escolhas[0]</p>
                        </li>

                        <li>
                            <input type='radio' id='b-option$x' name='certa$x' class='answer' value='b'>
                            <label for='b-option$x'>B</label>
                            <div class='check'></div>
                            <p for='b-option$x'>$escolhas[1]</p>
                        </li>

                        <li>
                            <input type='radio' id='c-option$x' name='certa$x' class='answer' value='c'>
                            <label for='c-option$x'>C</label>
                            <div class='check'></div>
                            <p for='c-option$x'>$escolhas[2]</p>
                        </li>

                        <li>
                            <input type='radio' id='d-option$x' name='certa$x' class='answer' value='d'>
                            <label for='d-option1'>D</label>
                            <div class='check'></div>
                            <p for='d-option$x'>$escolhas[3]</p>
                        </li>
                    </ul>
                </div>
                </article>
            ";
        }else if($tipoResposta[$vetor]==2){
            echo"
                <textarea class='inputText' name='resposta$x' maxlength='1000'></textarea>
                </article>
            ";

        }
    } 
    echo"

        <article class='confirm'>
            <hr onclick='off()'>
            <div>
                <h2>Deseja realmente enviar agora?</h2>
                <input class='submit' type='submit' name='enviar' value='Enviar' title='Enviar' data='hy'/></input>
            </div>
        </article>

    </form>";

    if(isset($_POST['enviar'])){
        $cod_atividade = $valor;
        $cod_usuario = $user_cod;
        $envio = date("y.m.d");
        $resposta;
        $acerto_erro;
        $acerto;
        for($x=1;$x<=$qtdQuestoes;$x++){
            $vetor = $x-1;
            if($tipoResposta[$vetor]==1){
                $resposta = $resposta.$_POST['certa'.$x]."-";
                if($respostaCorreta[$vetor]==$_POST['certa'.$x]){
                    $acerto_erro = $acerto_erro."-1";
                    $acerto++;
                }else{
                    $acerto_erro = $acerto_erro."-0";
                }
            }else if($tipoResposta[$vetor]==2){
                if($respostaCorreta[$vetor]==$_POST['resposta'.$x]){
                    $resposta = $resposta.$_POST['resposta'.$x]."-";
                    $acerto_erro = $acerto_erro."-1";
                    $acerto++;
                }else{
                    $acerto_erro = $acerto_erro."-0";
                }
            }
        }
        $nota = $acerto*100/$qtdQuestoes/10;

        $insereUser = BD::conn()->prepare("INSERT INTO `resposta_atividade` (`cod_atividade`, `cod_usuario`, `envio`, `resposta`, `acerto_erro`, `nota`) VALUES (?, ?, ?, ?, ?, ?)"); 
        $insereUser->execute(array($cod_atividade, $cod_usuario, $envio, $resposta, $acerto_erro, $nota));

        echo"
        <script>
        window.sessionStorage.setItem('valor1', '$qtdQuestoes');
        window.sessionStorage.setItem('valor2', '$tipoRespostaComplet');
        window.sessionStorage.setItem('valor3', '$respostaCorretaComplet');
        window.sessionStorage.setItem('valor4', '$resposta');
        window.sessionStorage.setItem('valor5', '$acerto');
        window.sessionStorage.setItem('valor6', '$nota');
        </script>
        ";
        Header("Location: ../index.php");
    }

?>
</body>
<script type="text/javascript" src="Scripts/jquery.min.js"></script>
<script type="text/javascript" src="Scripts/Scroll.js"></script>
<script>

    var question = 1;

    var x;
    var confirm = document.getElementsByClassName('confirm');
    var modal = document.getElementsByClassName('modal')[0];
    function active(x){
        if(x == 1){
            confirm[0].style.display="block";
            setTimeout(function(){
                 confirm[0].style.top="0";
            }, 0);
        }


    }
    function off(){
        confirm[0].style.top="100%";
        setTimeout(function(){
             confirm[0].style.display="none";
        }, 550);
    }

    function select(x){
        if(x==900){
                q = "n".concat(question-1);
                document.getElementById(q).click();
        }else if(x==1000){
                q = "n".concat(question+1);
                document.getElementById(q).click();
        }else{
            var z = "n".concat(question);
            document.getElementById(z).style.backgroundColor = "#222222";
            document.getElementById(z).style.color = "#FF3C3A";
            document.getElementById(z).style.borderColor = "#FF3C3A";

            var y = "n".concat(x);
            document.getElementById(y).style.backgroundColor = "#FF3C3A";
            document.getElementById(y).style.color = "#fcfcfc";
            document.getElementById(y).style.borderColor = "#FF3C3A";
            question = x;
        }
    }
function filtra(valor){
        jQuery.ajax({
         url: "busca.php?valor="+valor,
         context: document.body
        }).done(function(retorno) {
         jQuery('#resultado').html(retorno);
        });
    }

</script>

  • Run Output Buffers before HTML, ie the PHP codes before everything, you put in the middle of the body tag.

  • There’s a lot of things wrong with the code. header() capital letter; $documento[titulo] without quotation marks; Did not quote cookies (setcookie('nomedocookie', 'valordocookie')); semicolon after semicolon... I think it’s best to fix these problems with the code first.

  • Wesley, each header you place, must close with Exit; after redirect, otherwise only the first header will work.

1 answer

3

The problem is probably that output before the header

    echo"
    <script>
    window.sessionStorage.setItem('valor1', '$qtdQuestoes');
    window.sessionStorage.setItem('valor2', '$tipoRespostaComplet');
    window.sessionStorage.setItem('valor3', '$respostaCorretaComplet');
    window.sessionStorage.setItem('valor4', '$resposta');
    window.sessionStorage.setItem('valor5', '$acerto');
    window.sessionStorage.setItem('valor6', '$nota');
    </script>
    ";
    Header("Location: ../index.php");

Enable and configure the error logs properly and you can see that there is a header conflict error in that snippet.

Your situation is a bit unusual because from what I understand you do not necessarily need to write something on the screen for the user but need to write Javascript to set data in window.sessionStorage. I don’t know if I can say this because I’m oblivious to what you’re doing, but this is more of a design issue. I don’t mean "image/layout/art/illustration design" but programming logic structure.

Normally, in programming logic, when we get to a crossroads, it’s because we fail at some logical point in the structure. Rethink a way of redesigning the logical structure. Otherwise you can also solve it, however, by going rogue. Choose the one that is most convenient because sometimes a gambiarra is better.

See similar questions like this regarding the use of header(): Error when redirecting after sending form

Browser other questions tagged

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