Redirección de página PHP [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Puede PHP hacer una llamada de redirección después de ejecutar una función? Estoy creando una función en la finalización de la cual quiero redirigir a un archivo ubicado en la misma carpeta raíz. ¿Se puede hacer?

 if {
      //i am using echo here
 }

 else if ($_SESSION['qnum'] > 10) { 
            session_destroy();
            echo "Some error occured.";
            //redirect to user.php
        }
Author: Lance Roberts, 2010-01-21

15 answers

Sí, usarías la función header.

header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();

Es una buena práctica llamar a exit() palabras posteriores para que el código debajo de él no se ejecute.

También, de la documentación:

Recuerde que header() debe ser llamado antes de que cualquier salida real sea enviada, ya sea por etiquetas HTML normales, líneas en blanco en un archivo, o desde PHP. Es un error muy común leer código con include (), require (), functions, u otra función de acceso a archivos, y tener espacios o líneas vacías que se generan antes de que se llame a header (). El mismo problema existe cuando se utiliza un solo archivo PHP / HTML.

Esto significa que no debe hacer eco de nada justo antes de la función header(), ya que hacerlo es más que probable que genere un error. Además, deberá verificar que este código se ejecute antes que cualquier otra salida.

 242
Author: bkildow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 20:17:58

Usando un javascript como un failsafe se asegurará de que el usuario es redirigido (incluso si las cabeceras ya han sido enviadas). Aquí tienes:

// $url should be an absolute url
function redirect($url){
    if (headers_sent()){
      die('<script type="text/javascript">window.location=\''.$url.'\';</script‌​>');
    }else{
      header('Location: ' . $url);
      die();
    }    
}

Si necesita manejar correctamente las rutas relativas, he escrito una función para eso (pero eso está fuera del alcance de la pregunta).

 45
Author: brianreavis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-22 20:00:11

Una forma sencilla es usar:

  echo '<script>window.location.href = "the-target-page.php";</script>';
 11
Author: CrownFord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-04 14:18:57
   $url='the/url/you/want/to/go';
   echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';

Esto funciona para mí bien.

 10
Author: Thusitha Sumanadasa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-12 05:32:43
header( "Location: http://www.domain.com/user.php" );

Pero primero no se puede hacer un eco, y luego redirigir.

 7
Author: code-zoop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 20:57:33
<?php

    http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);

?>
 3
Author: user3164291,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-04 12:35:54

Sí.

En esencia, mientras no se genere nada, puede hacer lo que quiera (matar una sesión, eliminar las cookies de usuario, calcular Pi a 'n' dígitos, etc.) antes de emitir un encabezado de ubicación.

 0
Author: John Parker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 19:56:06

, probablemente voy a configurar el mensaje como una variable de sesión, redirigir al usuario a otra página que muestra el mensaje y destruir la sesión.

 0
Author: Leprosy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 20:46:41

La función header() en PHP hace esto, pero asegúrese de llamarla antes de que se envíe cualquier otro contenido de archivo al navegador o de lo contrario recibirá un error.

JavaScript es una alternativa si ya ha enviado el contenido del archivo.

 0
Author: ServAce85,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-22 11:44:56

En realidad, encontré esto en el código de un cms basado en php.

Redirigir ('?module=blog', 0);

Así que es posible. En este caso, usted está conectado en el nivel de administrador, por lo que no hay daño no hay falta (supongo). la primera parte es la url, y la segunda? No puedo encontrar ninguna documentación para qué es el entero, pero supongo que es tiempo o datos, ya que está adjunto a un formulario.

Yo también quería actualizar una página después de un evento, y colocar esto en un lugar mejor funcionó bien.

 0
Author: llothcat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-13 08:15:17

Puede usar este código para redirigir en php

<?php
/* Redirect browser */
header("Location: http://example.com/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
 0
Author: Mahdiyah Al-kaff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-15 11:55:52

Si desea incluir la redirección en su archivo php sin necesariamente tenerlo en la parte superior, puede activar el búfer de salida en la parte superior, luego llamar a redirección desde cualquier lugar dentro de la página. Ejemplo;

 <?php
 ob_start(); //first line
 ... do some work here
 ... do some more
 header("Location: http://www.yourwebsite.com/user.php"); 
 exit();
 ... do some work here
 ... do some more
 0
Author: nixxx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-26 17:31:37

Como se indica en nixxx agregar ob_start() antes de agregar cualquier código php evitará el error de las cabeceras ya enviadas.

Funcionó para mí

El siguiente código también funciona. Pero primero carga la página y luego redirige cuando la uso.

echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';
 0
Author: user2634873,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 09:21:44

La función header () hace esto:

header("Location: user.php");
 -1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 19:55:52

I serach acerca de esto y me parece relacionado esta respuesta en

Https://stackoverflow.com/questions/13539752/redirect-function/13539808

function redirect_url($path)
{
  header("location:".$path);
  exit;
}
 -3
Author: user1972007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:48