Foros del Web » Programando para Internet » PHP »

Volver a la última página visitada

Estas en el tema de Volver a la última página visitada en el foro de PHP en Foros del Web. Buenas a todos!! A ver si me podeís echar un cable. Lo que quiero hacer es que cuando una persona se logee en la página ...
  #1 (permalink)  
Antiguo 18/06/2008, 05:29
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Volver a la última página visitada

Buenas a todos!!

A ver si me podeís echar un cable. Lo que quiero hacer es que cuando una persona se logee en la página que tengo inmediatamente despues se redirija a la ultima página que estaba visitando sin que tenga que pulsar ningún botón. Más o menos como lo que hay en el foro cuando te identificas.

No sé si habrá algún tema abierto sobre esto pero es que llevo dos días intentando buscarlo pero en la busqueda del foro me da todo el rato un error.

Y en Google he estado mirando y he encontrado $HTTP_REFERER pero a parte de que no sé muy bien como funciona, he leído que con algunos navegadores no funciona.

Espero que me puedan ayudar.

Muchas gracias.
  #2 (permalink)  
Antiguo 18/06/2008, 08:00
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Nadie sabe como puedo hacerlo????
  #3 (permalink)  
Antiguo 18/06/2008, 08:11
Avatar de almarin  
Fecha de Ingreso: junio-2008
Mensajes: 44
Antigüedad: 15 años, 10 meses
Puntos: 4
Respuesta: Volver a la última página visitada

Yo lo hago así

Código PHP:
// Este código se ejecuta cuando expira la sesión

header('location: login.php?referer='.urlencode($_SERVER['PHP_SELF'])); 
Luego, en el login.php, una vez autenticado, hago lo siguiente:

Código PHP:
$destino= isset($_GET['referer']) ? $_GET['referer'] : 'index.php';
header("location: $destino"); 
Espero que te ayude

Saludos
  #4 (permalink)  
Antiguo 19/06/2008, 08:28
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Muchas gracias almarin, pero no entiendo muy bien el código que me has puesto porque en destino tu pones directamente que vaya a la página de index.php, ¿no?

Pero yo lo que quiero no es que me vaya a la principal si no a la que estaba viendo anteriormente a logearse.

Igual me equivoco y lo que me has puesto si que hace eso.

De todas formas, muchisimas gracias!!
  #5 (permalink)  
Antiguo 19/06/2008, 08:38
Avatar de almarin  
Fecha de Ingreso: junio-2008
Mensajes: 44
Antigüedad: 15 años, 10 meses
Puntos: 4
Respuesta: Volver a la última página visitada

Hola Jarine:

$destino podría ser index.php (supuestamente la página principal) u otra, indicada por la variable GET 'referer'.

A ver, la idea es que, estas viendo una página, y ya sea porque te caduca la sesión, o porque pulsas un enlace para loguearte, ese enlace va acompañado con una variable en la URL que es la que indica dónde te encontrabas. En este caso, esa variable la he representado como 'referer'. Eso es lo que hace la primera parte del código.

La otra parte símplemente hace:
¿Existe alguna variable GET llamada referer? Si es que sí, entonces redirijo a ese lugar. Encaso de que no haya nada, pues por defecto me voy a la página principal.

Saludos.
  #6 (permalink)  
Antiguo 19/06/2008, 08:46
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Muchas gracias de nuevo!!

Voy a probarlo y te comento.

Otra pregunta, la primera parte del código tendría que ponerla en aquellas páginas que tengan acceso a login.php, ¿no?
  #7 (permalink)  
Antiguo 19/06/2008, 15:00
Avatar de almarin  
Fecha de Ingreso: junio-2008
Mensajes: 44
Antigüedad: 15 años, 10 meses
Puntos: 4
Respuesta: Volver a la última página visitada

Claro.

Mira, imagínate que para hacer login, tu pones un enlace html del tipo

Código HTML:
<a href="login.php">Login</a> 
Pues en vez de poner login.php a secas, pones login.php?referer=PAGINA ACTUAL

Lo de página actual, en PHP, puedes como te digo en la primera parte del codigo:

Código PHP:
echo '<a href="login.php?referer='.urlencode($_SERVER['PHP_SELF']).'</a>'
Saludos y suerte
  #8 (permalink)  
Antiguo 21/06/2008, 05:34
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Muchas gracias almarin!!

Ya me funciona lo de redirigir la página después de logearse el usuario pero el problema es que siempre me va al index.html y no a la página que estaba visitando antes del login.

En vez de con header(location) lo he tenido que hacer con <head><meta> ya que si no me daba un error.

No sé como solucionarlo, ¿alguna idea?

Os pongo el código:

login.php
Código PHP:
<?php
    session_start
();
?>

<!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>
    <title>Identificación de usuarios</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta name="verify-v1" content="7uiD5QdUtd0j14COc+V8QRQHTsLmS+qE5PWC/+OaSYQ=" />
    <meta name="revisit" content="1 semana">
    <link href="estilo.css" type="text/css" rel="stylesheet" />
    <script language="javascript" src="popup.js"></script>
    <meta content="MSHTML 6.00.2800.1400" name="GENERATOR" />
    <style type="text/css">
        body 
        {
            margin-left: 10px;
            margin-top: 10px;
        }
    </style>
</head>

<?php
    $primeravez 
FALSE;
    if (empty(
$_POST["botEnviar"]))
    {
        
$primeravez TRUE;
        
$_POST["email"] = "";
        
$_POST["contrasena"] = "";
    }
?>

<body bgcolor="#F5F5F5" topmargin="10">
    <table width="836" cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td colspan="2" width="836">
                <iframe name="navigation" src="cabecera.html" frameborder="0" width="836" scrolling="no" height="118"></iframe>
            </td>
        </tr>
        <tr>
            <td colspan="2" width="836" height="22"></td>
        </tr>
        <tr>
            <td colspan="2" width="836" height="30" bgcolor="#FFFFFF">Para poder acceder a su cuenta de usuario, debe identificarse. Si no está registrado, hagalo pulsando <a href="registro.php">aquí</a>.</td>
        </tr>
        <tr>
            <td colspan="2" width="836" height="8" bgcolor="#FFFFFF"></td>
        </tr>
    <form name="login" method="post" action="login.php">
        <tr>
            <td width="100" bgcolor="#FFFFFF">Email *:</td>
              <td width="736" bgcolor="#FFFFFF"><input name="email" type="text" id="email" value="<?php echo $_POST['email']; ?>" size="40" style="background-color:#F5F5F5" /></td>
        </tr>
        <?php
            
if (!$primeravez)
            {
                if (empty(
$_POST["email"]))
                    echo 
"<tr><td colspan=\"2\" width=\"836\" height=\"25\" bgcolor=\"#FFFFFF\" style=\"color:#FF0000; font-size:14px\">¡Tiene que introducir su email!</td></tr>";
                elseif (!
eregi("^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9_\-\.]+$"$_POST["email"]))
                    echo 
"<tr><td colspan=\"2\" width=\"836\" height=\"25\" bgcolor=\"#FFFFFF\" style=\"color:#FF0000; font-size:14px\">¡Email no válido!</td></tr>";
                else
                    
$email htmlspecialchars($_POST["email"]);
            }
        
?>
        <tr>
            <td colspan="2" height="8" bgcolor="#FFFFFF"></td>
        </tr>
        <tr>
            <td width="100" bgcolor="#FFFFFF">Contraseña *:</td>
              <td width="736" bgcolor="#FFFFFF"><input name="contrasena" type="password" id="contrasena" value="<?php echo $_POST['contrasena']; ?>" size="40" style="background-color:#F5F5F5" /></td>
        </tr>
        <?php
            
if (empty($_POST["contrasena"]) && (!$primeravez))
                echo 
"<tr><td colspan=\"2\" width=\"836\" height=\"25\" bgcolor=\"#FFFFFF\" style=\"color:#FF0000; font-size:14px\">¡Tiene que introducir su contraseña!</td></tr>";
            else
                
$contrasena htmlspecialchars($_POST["contrasena"]);
        
?>
        <tr>
            <td colspan="2" width="836" height="8" bgcolor="#FFFFFF"></td>
        </tr>
        <tr>
              <td colspan="2" width="836" bgcolor="#FFFFFF" align="center"><input name="botEnviar" type="submit" id="botEnviar" value="Enviar" style="width:100px; cursor:pointer" /></td>
        </tr>
    </form>
    <?php
        
if ((!$primeravez) && isset($email) && isset($contrasena))
        {
            require_once(
"conexion.inc.php");
            
$conexion mysql_connect($servidor$usuario$passwd);
            
$db mysql_select_db($basedatos$conexion);
            if (!
$conexion)
            {
                echo 
"Error al establecer la conexión con la base de datos: " mysql_error();
                exit();
            }
            if (!
$db)
            {
                echo 
"Error seleccionando la base de datos: " mysql_error();
                exit();
            }
            
$resultado mysql_query("SELECT id_cliente FROM clientes WHERE email = '$email' AND contrasena = '$contrasena'"$conexion);
            if (
mysql_num_rows($resultado) > 0)
            {
                
$fila mysql_fetch_array($resultado);
                
$_SESSION["usuario"] = $fila["id_cliente"];
                
$_SESSION["logged"] = TRUE;
                echo 
"<tr><td colspan=\"2\" width=\"836\" height=\"15\" bgcolor=\"#FFFFFF\"></td></tr><tr><td colspan=\"2\" width=\"836\" heigth=\"25\" bgcolor=\"#FFFFFF\" align=\"center\" style=\"color:#33CC00; font-size:14px\">Identificación realizada con éxito.</td></tr>";
                
$destino = isset($_GET['referer']) ? $_GET['referer'] : 'index.html';
                echo 
"<head><meta http-equiv=\"refresh\" content=\"3; url=$destino\"></head>";
            }
            else
            {
                echo 
"<tr><td colspan=\"2\" width=\"836\" height=\"15\" bgcolor=\"#FFFFFF\"></td></tr><tr><td colspan=\"2\" width=\"836\" heigth=\"25\" bgcolor=\"#FFFFFF\" align=\"center\" style=\"color:#FF0000; font-size:14px\">¡Usuario o contraseña incorrectos!</td></tr>";
            }
            
mysql_free_result($resultado);
            
mysql_close($conexion);
        }
    
?>
        <tr>
            <td height="20" bgcolor="#F5F5F5" colspan="6"></td>
        </tr>
    </table>
</body>
</html>
Sigue más abajo.
  #9 (permalink)  
Antiguo 21/06/2008, 05:38
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Página desde la que accedo a login.php
Código PHP:
<!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>
    <title>Producto</title>
    <link href="estilo.css" type="text/css" rel="stylesheet" />
    <script language="javascript" src="popup.js"></script>
    <style type="text/css">
        body 
        {
            margin-left: 10px;
            margin-top: 10px;
        }
    </style>
</head>

<?php
    
require_once("conexion.inc.php");
    
$conexion mysql_connect($servidor$usuario$passwd);
    
$db mysql_select_db($basedatos$conexion);
    if (!
$conexion)
    {
        echo 
"Error al establecer la conexión con la base de datos: " mysql_error();
        exit();
    }
    if (!
$db)
    {
        echo 
"Error seleccionando la base de datos: " mysql_error();
        exit();
    }
    
$resultado mysql_query("SELECT * FROM " $_GET["categoria"] . " WHERE referencia=\"" $_GET["referencia"] . "\""$conexion);
    
$fila mysql_fetch_array($resultado);
?>

<?php
if (!isset($_SESSION["logged"]))
{
?>

<body bgcolor="#F5F5F5" topmargin="10">
    <table width="836" cellpadding="0" cellspacing="0" border="0" bgcolor="#FFFFFF">
        <tr>
            <td colspan="6">
                <iframe name="navigation" src="cabecera.html" frameborder="0" width="836" scrolling="no" height="118"></iframe>
            </td>
        </tr>
        <tr>
            <td width="836" height="20" colspan="6" style="font-size:12px">
                <b>Para poder visualizar los precios debe 
                <?php 
                    
echo "<a href=\"login.php?referer=" urlencode($_SERVER['PHP_SELF']) . "\">identificarse</a>";
                
?>
                . Si no está registrado, puede hacerlo pinchando 
                <?php
                    
echo "<a href=\"registro.php?referer=" urlencode($_SERVER['PHP_SELF']) . "\">aquí</a>";
                
?>
                .</b>
            </td>
        </tr>
        <tr>
            <td width="836" height="10" bgcolor="#F5F5F5" colspan="6"></td>
        </tr>
        <tr>
            <td colspan="6" height="20" width="836">
                <?php
                    
echo $fila["descripcion"];
                
?>
            </td>
        </tr>
        <tr>
            <td width="836" height="10" bgcolor="#F5F5F5" colspan="6"></td>
        </tr>
        <tr>
            <td colspan="6" height="20" width="836">
                <?php
                    $color 
explode("-"$fila["colores"]);
                    
$total_color count ($color);
                    for (
$i=0$i<$total_color$i++)
                    {
                        
$nombres_color mysql_query("SELECT color FROM colores WHERE codigo = $color[$i]"$conexion);
                        
$nom_color mysql_fetch_array($nombres_color);
                        echo 
$nom_color["color"];
                    }
                
?>
            </td>
        </tr>
        <tr>
            <td width="836" height="10" bgcolor="#F5F5F5" colspan="6"></td>
        </tr>
        <tr>
            <td rowspan="9" width="300" height="300" align="center">
                <?php
                    
echo "<img src=\"imagenes/" $fila["referencia"] . ".jpg\" width=180 height=180>";
                
?>
            </td>
            <td rowspan="9" bgcolor="#F5F5F5" width="10"></td>
            <th width="150">Cantidad</th>
            <th width="150">Precio</th>
            <td rowspan="9" bgcolor="#F5F5F5" width="10"></td>
            <td></td>
        </tr>
        <tr>
            <th width="150">25</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <th width="226">Código de marcaje</th>
        </tr>
        <tr>
            <th width="150">50</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <td width="226" align="center">
                <?php
                    
echo $fila["codigo_marcaje"];
                
?>
            </td>
        </tr>
        <tr>
            <th width="150">100</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <th width="226">Medida de marcaje</th>
        </tr>
        <tr>
            <th width="150">250</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <td width="226" align="center">
                <?php
                    
echo $fila["medida_marcaje"];
                
?>
            </td>
        </tr>
        <tr>
            <th width="150">500</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <th width="226">Colores máximos de marcaje</th>
        </tr>
        <tr>
            <th width="150">1000</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <td  width="226" align="center">
                <?php
                    
echo $fila["colores_maximos"];
                
?>
            </td>
        </tr>
        <tr>
            <th width="150">5000</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                
?>
            </td>
            <td></td>
        </tr>
        <tr>
            <th width="150">10000</th>
            <td width="150" align="center">
                <?php
                    
echo "Debe identificarse.";
                    
mysql_free_result($resultado);
                    
mysql_close($conexion);
                
?>
            </td>
            <td></td>
        </tr>
    </table>
</body>

<?php
}
else
{
?>

<body bgcolor="#F5F5F5" topmargin="10">
    <table width="836" cellpadding="0" cellspacing="0" border="0" bgcolor="#FFFFFF">
        <tr>
            <td colspan="6">
                <iframe name="navigation" src="cabecera.html" frameborder="0" width="836" scrolling="no" height="118"></iframe>
            </td>
        </tr>
        <tr>
            <td colspan="6" height="20" width="836">
                <?php
                    
echo $fila["descripcion"];
                
?>
            </td>
        </tr>
        <tr>
            <td width="836" height="10" bgcolor="#F5F5F5" colspan="6"></td>
        </tr>
        <tr>
            <td colspan="6" height="20" width="836">
                <?php
                    $color 
explode("-"$fila["colores"]);
                    
$total_color count ($color);
                    for (
$i=0$i<$total_color$i++)
                    {
                        
$nombres_color mysql_query("SELECT color FROM colores WHERE codigo = $color[$i]"$conexion);
                        
$nom_color mysql_fetch_array($nombres_color);
                        echo 
$nom_color["color"];
                    }
                
?>
            </td>
        </tr>
        <tr>
            <td width="836" height="10" bgcolor="#F5F5F5" colspan="6"></td>
        </tr>
        <tr>
            <td rowspan="9" width="300" height="300" align="center">
                <?php
                    
echo "<img src=\"imagenes/" $fila["referencia"] . ".jpg\" width=180 height=180>";
                
?>
            </td>
            <td rowspan="9" bgcolor="#F5F5F5" width="10"></td>
            <th width="150">Cantidad</th>
            <th width="150">Precio</th>
            <td rowspan="9" bgcolor="#F5F5F5" width="10"></td>
            <td></td>
        </tr>
        <tr>
            <th width="150">25</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["veinticinco"] != 0)
                    {
                        
$precio $fila["veinticinco"] + (($fila["veinticinco"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <th width="226">Código de marcaje</th>
        </tr>
        <tr>
            <th width="150">50</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["cincuenta"] != 0)
                    {
                        
$precio $fila["cincuenta"] + (($fila["cincuenta"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <td width="226" align="center">
                <?php
                    
echo $fila["codigo_marcaje"];
                
?>
            </td>
        </tr>
        <tr>
            <th width="150">100</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["cien"] != 0)
                    {
                        
$precio $fila["cien"] + (($fila["cien"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <th width="226">Medida de marcaje</th>
        </tr>
        <tr>
            <th width="150">250</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["doscientoscincuenta"] != 0)
                    {
                        
$precio $fila["doscientoscincuenta"] + (($fila["doscientoscincuenta"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <td width="226" align="center">
                <?php
                    
echo $fila["medida_marcaje"];
                
?>
            </td>
        </tr>
        <tr>
            <th width="150">500</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["quinientos"] != 0)
                    {
                        
$precio $fila["quinientos"] + (($fila["quinientos"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <th width="226">Colores máximos de marcaje</th>
        </tr>
        <tr>
            <th width="150">1000</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["mil"] != 0)
                    {
                        
$precio $fila["mil"] + (($fila["mil"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <td  width="226" align="center">
                <?php
                    
echo $fila["colores_maximos"];
                
?>
            </td>
        </tr>
        <tr>
            <th width="150">5000</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["cincomil"] != 0)
                    {
                        
$precio $fila["cincomil"] + (($fila["cincomil"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                
?>
            </td>
            <td></td>
        </tr>
        <tr>
            <th width="150">10000</th>
            <td width="150" align="center">
                <?php
                    
if ($fila["diezmil"] != 0)
                    {
                        
$precio $fila["diezmil"] + (($fila["diezmil"] * $fila["incremento"]) / 100);
                        echo 
Round($precio,2) . "€/ud";
                    }
                    else
                    {
                        echo 
"Producto no disponible en esta cantidad.";
                    }
                    
mysql_free_result($resultado);
                    
mysql_close($conexion);
                
?>
            </td>
            <td></td>
        </tr>
    </table>
</body>

<?php
}
?>

</html>
Muchas gracias por vuestras respuestas.

Un saludo.
  #10 (permalink)  
Antiguo 22/06/2008, 04:51
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Nadie sabe como puedo solucionarlo??
  #11 (permalink)  
Antiguo 22/06/2008, 08:38
 
Fecha de Ingreso: septiembre-2007
Mensajes: 100
Antigüedad: 16 años, 7 meses
Puntos: 0
Respuesta: Volver a la última página visitada

Necesito ayuda, por favor!!!

No consigo que cuando una persona se logea le lleve a la última página que estaba visitando si no que siempre le lleva a la página principal.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 21:28.