0

he estado intentando redireccionar a otra página con PHP con header y javascript pero de ninguna manera me funciona. Después de haber cargado la página (hola.php) hay una función que consulta un valor en una base de datos y dependiendo de ese valor te regresa a index.php que es un login o te deja en la misma página. En conclusión lo que intento es que una función verifique a cada 10 segundos si un campo llamado token fue alterado o no (lo cual ya logre, solo me falta redireccionar), si fue alterado tendría que redireccionar a index.php y si no fue alterado que no haga nada. Desde ya, MUCHAS GRACIAS!!!

Adjunto mi código.

            <?php
            session_start();

            //LLAMA A FUNCION UPDATE A CADA 10 SEGUNDOS 
            if(isset($_POST["action"])) { 
                switch(sprintf("%d", $_POST["action"])) { 
                    case 1:
                        update(); 

                        break;
                    default:

                }
            }

            function update() {
                require_once("conexion.php");

                //VERIFICA SI EL CAMPO TOKEN FUE ALTERADO, SI FUE ALTERADO TE TENDRIA QUE REDIRECCIONAR A INDEX.PHP SI SIGUE IGUAL NO HACE NADA.
                $consulta_bd3=  $conexion->prepare("select token from usuario where idUsuario = ? ");
                $consulta_bd3 -> bind_param('s', $_SESSION['id']);
                $consulta_bd3->execute();
                $resultado3 = $consulta_bd3->get_result();
                $row3 = $resultado3->fetch_assoc();
                $comparaToken = $row3['token'];



                if($comparaToken == $_SESSION['token']){

                }else{

                    //DESDE AQUI INTENTO REDIRECCIONAR A INDEX.PHP
                    echo "<script>";    
                    echo "window.location.href ='/index.php';";
                    echo "</script>";
                //echo "<script> alert('rwrqw');</script>";
                // die();

                }
            }

            if (empty($_SESSION['nombre']) ) {
                header('location: index.php');
            }
            if (isset($_POST['submit'])) {
                $_SESSION['nombre']=null;
                session_destroy();
                session_unset();
                session_commit();
                header('location: index.php');
            }



            ?>

            <!DOCTYPE html>
            <html>
            <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                <title>HOLA</title>
                <script>


                    $(function() { 
                    cron(); 
                    function cron() {
                        $.ajax({
                            method: "POST",
                            url: "hola.php",
                            data: {
                                action: 1
                            }
                        }).done(function(msg) {
                            console.log(msg);
                        });
                    }
                    setInterval(function() {
                        cron();
                    }, 10000); 
                });
                </script>
            </head>
            <body>
            <div id="comments">

            </div>


                <center>
            <H1>BIENVENIDO</H1>
            <form method="POST">
            <input  name="submit" type="submit"  value="Cerrar sesion"/>
            </form>

            </center>
            </body>
            </html>

3 respuestas 3

0

Realmente ahí no haces nada relacionado a la redirección, ya que ajax no funciona de esa manera he tratado de cambiar lo menos tu código , básicamente es una misma pagina llamada hola.php si hay un post de action unicamente llamará a la función update en caso contrario hace todo lo demás, ademas para que pueda ser bien interpretada por el result de ajax si el token cambio, basicamente envia 1 sino enviara 0 para retornar lo valores basta hacer json encode e imprimirlo

Del lado del javascript dependiendo de lo que retorne pues redireccionará o escribirá un log diciendo que el token sigue igual y en caso de fallo por un html malformado o porque por x o y retona algo extraño mostrara un alert para que te puedas guiar

sin mas que decir aquí esta

hola.php

<?php
    session_start();

    if(isset($_POST["action"])) { 
        switch($_POST["action"]) { 
            case '1':
                update(); 
                break;
            default:
        }
    }else{

        if (empty($_SESSION['nombre']) ) {
            header('location: index.php');
        }

        if (isset($_POST['submit'])) {
            $_SESSION['nombre']=null;
            session_destroy();
            session_unset();
            session_commit();
            header('location: index.php');
        }

        defaultPage();
    }


    function update() {
        require_once("conexion.php");

        //VERIFICA SI EL CAMPO TOKEN FUE ALTERADO, SI FUE ALTERADO TE TENDRIA QUE REDIRECCIONAR A INDEX.PHP SI SIGUE IGUAL NO HACE NADA.
        $consulta_bd3=$conexion->prepare("select token from usuario where idUsuario = ? ");
        $consulta_bd3->bind_param('s', $_SESSION['id']);
        $consulta_bd3->execute();
        $resultado3=$consulta_bd3->get_result();
        $row3=$resultado3->fetch_assoc();
        $comparaToken=$row3['token'];


        if($comparaToken != $_SESSION['token']){
            $result['result']=1;
        }else{
             $result['result']=0;
        }

        echo json_encode($result);


    }


    ?>


<?php function defaultPage (){ ?>


<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <title>HOLA</title>
        <script>
            $(function() { 
            cron(); 

            function cron() {

                .ajax({
                type: "POST",
                cache: false,
                async: false, 
                url: 'hola.php',     
                dataType  : 'json',
                data: "action=1",  
                success: function (resp) 
                {
                        var msgaler = (resp);
                        if(msgaler["result"]==1)
                        {
                            $(location).attr('href','index.php');
                        }    
                        else
                        {
                            log('Token sigue igual');
                        }
                    },
                    error: function (request, status, error) {
                        alert(request.responseText);
                    } 
                });
            }
            setInterval(function() {
              //Se Llama a si misma cada 10 segundos
                cron();
            }, 10000); 
        });
        </script>
    </head>
    <body>
        <div id="comments"></div>
        <center>
            <H1>BIENVENIDO</H1>
            <form method="POST">
                <input  name="submit" type="submit"  value="Cerrar sesion"/>
            </form>
        </center>
    </body>
</html>

<?php } ?>    
2
  • Muchas gracias por tomarte el tiempo de contestar, pero sigue sin funcionar. el 23 nov. 2018 a las 4:58
  • Coméntame qué error te da, muéstrame el error de la consola de Javascript, puede que omitira algo, por otro lado mustrame que dice PHP en respuesta al post, eso se puede hacer usando postman o insomnia
    – Darkeniel
    el 23 nov. 2018 a las 11:00
0

Intenta poniendo Location en vez de location. En la documentación oficial de PHP figura con la L en mayúscula. Quizás sea eso. Un ejemplo:

    <?php
      /* Redirecciona a una página diferente en el mismo directorio el cual se hizo la petición */
      $host  = $_SERVER['HTTP_HOST'];
      $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
      $extra = 'mypage.php';
      header("**Location**: http://$host$uri/$extra");
      exit;
    ?>
1
  • El location lo he utilizado con minúscula en otras ocasiones y de igual manera funciona. Gracias por tu respuesta pero sigue sin funcionar. el 22 nov. 2018 a las 4:43
0

se escribe header('Location: index.php'); pero el problema que tienes esta en esta linea de if($comparaToken != $_SESSION['token']){ no haces nada si es true te deberia salir un warnig o un error pero supongo que as de tener los mensajes desabilitados!
solucion:

    if($comparaToken != $_SESSION['token']){

     header('Location: index.php');
     //DESDE AQUI INTENTO REDIRECCIONAR A INDEX.PHP
     echo "<script>";    
     echo "window.location.href ='/index.php';";
     echo "</script>";
     //echo "<script> alert('rwrqw');</script>";
     // die();
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.