Foros del Web » Programando para Internet » PHP »

Problemas con variables de sesion (de un archivo a otro)

Estas en el tema de Problemas con variables de sesion (de un archivo a otro) en el foro de PHP en Foros del Web. Hola, he estado rompiendome la cabeza tengo una pagina donde se valida usuario y contraseña, cada usuario tiene una serie de datos personales y cuando ...
  #1 (permalink)  
Antiguo 15/02/2008, 07:27
 
Fecha de Ingreso: abril-2007
Mensajes: 20
Antigüedad: 17 años
Puntos: 0
Problemas con variables de sesion (de un archivo a otro)

Hola, he estado rompiendome la cabeza tengo una pagina donde se valida usuario y contraseña, cada usuario tiene una serie de datos personales y cuando inicia sesion deben aparecer sus datos y solo los de el, si entra otro usuario aparecen los datos que le pertenecen a este otro y asi, pero mi problema es que no se como hacer la consulta por ejemplo si el codigo de usuario lo guardo en $_SESSION['codusuario']=$user (donde user es el que almacena el valor de la caja de texto donde ingrese el codigo de usuario) no lo guarda porque a la hora de hacer la consulta tipo SELECT nombre, apellido FROM usuarios WHERE codusuario = $_SESSION['codusuario] no me devuelve nada. entonces me di cuenta que el problema podia ser que no estaba pasando el valor de la variable. he estado probando y trate de correr estos dos pequeños codigos y tampoco me corren:

prueba_sesion_1.php

<?php
session_start();
$_SESSION['nombre'] = 'Juan';
?>
<a href="prueba_sesion_2.php">Prueba la sesion!</a>



prueba_sesion_2.php

<?php
session_start();
echo "El nombre es: ".$_SESSION['nombre'];
?>


que puedo hacer? he leido algo sobre modificar el archivo php.ini: cuando ejecuto phpinfo() me sale que el valor de session.save_path es NO VALUE tanto en local value como en master value

pongo los datos que me salen al verificar la configuracion de phpinfo()

session
Session Support enabled
Registered save handlers files user
Registered serializer handlers php php_binary wddx

Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 On On
session.bug_compat_warn On On
session.cache_expire 180 180
session.cache_limiter nocache nocache
session.cookie_domain C:\PHP\temp C:\PHP\temp
session.cookie_httponly Off Off
session.cookie_lifetime 0 0
session.cookie_path C:\PHP\temp C:\PHP\temp
session.cookie_secure Off Off
session.entropy_file no value no value
session.entropy_length 0 0
session.gc_divisor 100 100
session.gc_maxlifetime 1440 1440
session.gc_probability 1 1
session.hash_bits_per_character 4 4
session.hash_function 0 0
session.name PHPSESSID PHPSESSID
session.referer_check no value no value
session.save_handler files files
session.save_path no value no value
session.serialize_handler php php
session.use_cookies On On
session.use_only_cookies Off Off
session.use_trans_sid 0 0


Cuando pruebo con var_dump( $_GET ); me sale array(0) { }

AYUDENME POR FAVOR! no se que hacer... otra cosa: tengo los archivos de conexion (donde declaro las variables de sesion y sus valores) en el directorio raiz y tengo las paginas que llaman a esas variables en un subdirectorio dentro de esa carpeta raiz, uds creen que tenga algo que ver en el problema?. Tambien uso frames e iframes, me explico. mi pagina esta dividida en 3 frames: en el de la izquierda valido la sesion y me logueo, y entro a otra pagina con 3 frames (en realidad 3 iframes) y en el del centro deben aparecer los datos del que inicio sesion. ayuda!. gracias de antemano.

Última edición por yairo_gioel; 15/02/2008 a las 07:51 Razón: agregar informacion
  #2 (permalink)  
Antiguo 15/02/2008, 08:25
 
Fecha de Ingreso: mayo-2006
Ubicación: Madrid
Mensajes: 153
Antigüedad: 18 años
Puntos: 3
Re: Problemas con variables de sesion (de un archivo a otro)

El problema es que en session.save_path no existe ningún valor, con lo que las sesiones no se guardan. Edítalo en el php.ini. P.E:

session.save_path = "c:/sesiones"
  #3 (permalink)  
Antiguo 15/02/2008, 08:56
 
Fecha de Ingreso: abril-2007
Mensajes: 20
Antigüedad: 17 años
Puntos: 0
Re: Problemas con variables de sesion (de un archivo a otro)

Cita:
Iniciado por stardust Ver Mensaje
El problema es que en session.save_path no existe ningún valor, con lo que las sesiones no se guardan. Edítalo en el php.ini. P.E:

session.save_path = "c:/sesiones"
Gracias por tu ayuda. Mira: en el phpinfo() me sale que el directorio de php.ini es C:/php/php.ini entonces ese es el archivo que tengoq ue editar. y en ese archivo he puesto la ruta C:/php/sesiones y no sale nada... sigue saliendo no value a pesar de que he puesto ese directorio, ahora lo que no se es si tengo que poner el nombre del archivo tambien.

este es mi archivo phpinfo()

System Windows NT HRODRIGUEZ 5.1 build 2600
Build Date Feb 7 2007 23:10:31
Configure Command cscript /nologo configure.js "--enable-snapshot-build" "--with-gd=shared"
Server API CGI/FastCGI
Virtual Directory Support enabled
Configuration File (php.ini) Path C:\php\php.ini
PHP API 20041225
PHP Extension 20060613
Zend Extension 220060519
Debug Build no
Thread Safety enabled
Zend Memory Manager enabled
IPv6 Support enabled
Registered PHP Streams php, file, data, http, ftp, compress.zlib
Registered Stream Socket Transports tcp, udp
Registered Stream Filters convert.iconv.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, zlib.*


Y este es mi archivo php.ini (c:/php/php.ini)

[Session]
; Handler used to store/retrieve data.
session.save_handler = files

; Argument passed to save_handler. In the case of files, this is the path
; where data files are stored. Note: Windows users have to change this
; variable in order to use PHP's session functions.
;
; As of PHP 4.0.1, you can define the path as:
;
; session.save_path = "C:\php\sesiones"
;
; where N is an integer. Instead of storing all the session files in
; /path, what this will do is use subdirectories N-levels deep, and
; store the session data in those directories. This is useful if you
; or your OS have problems with lots of files in one directory, and is
; a more efficient layout for servers that handle lots of sessions.
;
; NOTE 1: PHP will not create this directory structure automatically.
; You can use the script in the ext/session dir for that purpose.
; NOTE 2: See the section on garbage collection below if you choose to
; use subdirectories for session storage
;
; The file storage module creates files using mode 600 by default.
; You can change that by using
;
; session.save_path = "C:\php\sesiones"
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
;session.save_path = "C:\php\sesiones"

; Whether to use cookies.
session.use_cookies = 1

;session.cookie_secure =

; This option enables administrators to make their users invulnerable to
; attacks which involve passing session ids in URLs; defaults to 0.
; session.use_only_cookies = 1

; Name of the session (used as cookie name).
session.name = PHPSESSID

; Initialize session on request startup.
session.auto_start = 0

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
session.cookie_lifetime = 0

; The path for which the cookie is valid.
session.cookie_path = "C:\php\temp"

; The domain for which the cookie is valid.
session.cookie_domain = "C:\php\temp"

; Whether or not to add the httpOnly flag to the cookie, which makes it inaccessible to browser scripting languages such as JavaScript.
session.cookie_httponly =

; Handler used to serialize data. php is the standard serializer of PHP.
session.serialize_handler = php

; Define the probability that the 'garbage collection' process is started
; on every session initialization.
; The probability is calculated by using gc_probability/gc_divisor,
; e.g. 1/100 means there is a 1% chance that the GC process starts
; on each request.

session.gc_probability = 1
session.gc_divisor = 100

; After this number of seconds, stored data will be seen as 'garbage' and
; cleaned up by the garbage collection process.
session.gc_maxlifetime = 1440

; NOTE: If you are using the subdirectory option for storing session files
; (see session.save_path above), then garbage collection does *not*
; happen automatically. You will need to do your own garbage
; collection through a shell script, cron entry, or some other method.
; For example, the following script would is the equivalent of
; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
; cd /path/to/sessions; find -cmin +24 | xargs rm

; PHP 4.2 and less have an undocumented feature/bug that allows you to
; to initialize a session variable in the global scope, albeit register_globals
; is disabled. PHP 4.3 and later will warn you, if this feature is used.
; You can disable the feature and the warning separately. At this time,
; the warning is only displayed, if bug_compat_42 is enabled.

session.bug_compat_42 = 1
session.bug_compat_warn = 1

; Check HTTP Referer to invalidate externally stored URLs containing ids.
; HTTP_REFERER has to contain this substring for the session to be
; considered as valid.
session.referer_check =

; How many bytes to read from the file.
session.entropy_length = 0

; Specified here to create the session id.
session.entropy_file =

;session.entropy_length = 16

;session.entropy_file = /dev/urandom

; Set to {nocache,private,public,} to determine HTTP caching aspects
; or leave this empty to avoid sending anti-caching headers.
session.cache_limiter = nocache

; Document expires after n minutes.
session.cache_expire = 180

; trans sid support is disabled by default.
; Use of trans sid may risk your users security.
; Use this option with caution.
; - User may send URL contains active session ID
; to other person via. email/irc/etc.
; - URL that contains active session ID may be stored
; in publically accessible computer.
; - User may access your site with the same session ID
; always using URL stored in browser's history or bookmarks.
session.use_trans_sid = 0

; Select a hash function
; 0: MD5 (128 bits)
; 1: SHA-1 (160 bits)
session.hash_function = 0

; Define how many bits are stored in each character when converting
; the binary hash data to something readable.
;
; 4 bits: 0-9, a-f
; 5 bits: 0-9, a-v
; 6 bits: 0-9, a-z, A-Z, "-", ","
session.hash_bits_per_character = 4

; The URL rewriter will look for URLs in a defined set of HTML tags.
; form/fieldset are special; if you include them here, the rewriter will
; add a hidden <input> field with the info which is otherwise appended
; to URLs. If you want XHTML conformity, remove the form entry.
; Note that all valid entries require a "=", even if no value follows.
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fields et="


que es lo que esta fallando? ayudame por favor...
  #4 (permalink)  
Antiguo 15/02/2008, 09:20
 
Fecha de Ingreso: mayo-2006
Ubicación: Madrid
Mensajes: 153
Antigüedad: 18 años
Puntos: 3
Re: Problemas con variables de sesion (de un archivo a otro)

Tienes que quitarle el ; que tiene justo antes. Si no, esa línea es un comentario y no hace nada.

Ya me cuentas.

Saludos!!!
  #5 (permalink)  
Antiguo 15/02/2008, 09:32
 
Fecha de Ingreso: abril-2007
Mensajes: 20
Antigüedad: 17 años
Puntos: 0
Re: Problemas con variables de sesion (de un archivo a otro)

Cita:
Iniciado por stardust Ver Mensaje
Tienes que quitarle el ; que tiene justo antes. Si no, esa línea es un comentario y no hace nada.

Ya me cuentas.

Saludos!!!
Ya lo hice y efectivamente ahora si aparece el directorio de las sesiones, pero hay alguna otra linea a la que tenga que borrarle el punto y coma? porque aun asi no funciona, sigo probando con var_dump( $_SESSION ); y sigue el mismo problema. mira te pongo una de mis consultas para que me digas si esta bien declarar asi la variable en la consulta, pero aun no se porque no funciona.

ESTA ES LA PAGINA DONDE VALIDO LA SESION (llama a un archivo que se conecta a la base de datos que se llama conexion.php)

<?php //llamando a la pagina conexion.php
include("conexion.php");

//recibiendo los datos del formulario y almacenandolos en una variable
$codusuario=$_GET['codusuario'];
$password=$_GET['password'];

//abre la conexion y valida los datos ingresados por el formulario
$link = Conectarse();
$result=mysql_query("select nivel, codusuario, password from usuarios where codusuario='$codusuario' and password='$password'",$link);

if($row=mysql_fetch_array($result)){
do{

//si el usuario existe crea una sesion

session_start();
$_SESSION['nivel']=$row[0];
$_SESSION['codusuario']=$row[1];
$_SESSION['password']=$row[2];


//luego de crear la sesion redirecciona a la pagina donde se mostrara la pagina principal dela sesion
header ("Location: admin/index_sesion_admin.php?codusuario=$codusuario");

//si el usuario no esta registrado muestra el siguiente mensaje
} while($row=mysql_fetch_array($result));
}else{
echo "¡Usuario o contraseña no existe!";
}

//cerramos la conexion
mysql_close($link);
?>



ESTA ES LA PAGINA DONDE QUIERO LLAMAR A LA VARIABLE: (CON LA CONSULTA)

<?php
$link=Conectarse();
$codigo_nombre=mysql_query("select codusuario, nombempleado, appatempleado, apmatempleado from empleados where codusuario = '$_SESSION['codusuario']'",$link); ?>
<?php while($row=mysql_fetch_array($codigo_nombre)){ ?>
<table width="115%" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td height="45"><div align="center">
<h3 align="center">&iexcl;Bienvenido, empleado <?php echo $row[0] ?> : <?php echo $row[1] ?> <?php echo $row[2] ?> <?php echo $row[3] ?> !<a href="javascript:inicio()" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('logout','','../img/menu_logout2.png',1)"><img src="../img/menu_logout.png" name="logout" width="105" height="25" border="0"></a></h3>
</div></td>
</tr>
</table>
<? } mysql_close($link)?>
  #6 (permalink)  
Antiguo 15/02/2008, 11:52
 
Fecha de Ingreso: abril-2007
Mensajes: 20
Antigüedad: 17 años
Puntos: 0
Re: Ya registra las sesiones en la carpeta de sesiones que cree pero aun falta!!!

Las sesiones ya aparecen en el directorio que cree en php.ini, mas o menos de esta forma:

sess_0af87487971010f6c8093c9815c6d5db

pero lo que no puedo es llamar a una variable de sesion de una pagina a otra... no se porque no me deja, pierde el valor que le asigno al principio, que esta pasando? porque si crea la sesion pero no me permite pasar las variables de una pagina a otra? ayudenme por favor!!! estoy desesperadooo!!!
  #7 (permalink)  
Antiguo 15/02/2008, 12:00
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Re: Problemas con variables de sesion (de un archivo a otro)

En tu segunda pagina, asegurate de llamar a session_start() al principio de tu pagina.

Saludos.
  #8 (permalink)  
Antiguo 15/02/2008, 13:21
 
Fecha de Ingreso: abril-2007
Mensajes: 20
Antigüedad: 17 años
Puntos: 0
Re: Problemas con variables de sesion (de un archivo a otro)

Cita:
Iniciado por GatorV Ver Mensaje
En tu segunda pagina, asegurate de llamar a session_start() al principio de tu pagina.

Saludos.
si la llamo... mira te pongo las dos paginas: lo que pasa es que una pertenece a un frame de 3 partes y la otra tambien.

VALIDACION. PHP (Este archivo esta en el directorio raiz, aqui declaro las variables de sesion)

<?php //llamando a la pagina conexion.php
include("conexion.php");

//recibiendo los datos del formulario y almacenandolos en una variable
$codusuario=$_GET['codusuario'];
$password=$_GET['password'];

//abre la conexion y valida los datos ingresados por el formulario
$link = Conectarse();
$result=mysql_query("select nivel, codusuario, password from usuarios where codusuario='$codusuario' and password='$password'",$link);

if($row=mysql_fetch_array($result)){
do{

//si el usuario existe crea una sesion

session_start();
$_SESSION['nivel']=$row[0];
$_SESSION['codusuario']=$row[1];
$_SESSION['password']=$row[2];


//luego de crear la sesion redirecciona a la pagina donde se mostrara la pagina principal dela sesion
header ("Location: admin/index_sesion_admin.php?codusuario=$codusuario");

//si el usuario no esta registrado muestra el siguiente mensaje
} while($row=mysql_fetch_array($result));
}else{
echo "¡Usuario o contraseña no existe!";
}

//cerramos la conexion
mysql_close($link);
?>


CABEZA_MENU_ADMIN.PHP (este archivo esta en un subdirectorio llamado admin/ y aqui se cargan 4 datos del que inicio sesion: codigo, nombre, apellido materno y apellido paterno) PERO NO LOS MUESTRA!

<?php
session_start();
$nivel=$_SESSION['nivel'];
if($nivel==1){
}else{
header("Location: error.php");
}
?>
<? include("conexion.php"); //en este archivo se conecta a la base de datos?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Club de Socios - Administrador</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
body {
background-color: #000000;
}
.Estilo5 { color: #FFFFFF;
font-size: 12px;
font-weight: bold;
}
body,td,th {
color: #FFFFFF;
}
-->
</style>
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
function inicio()
{
window.top.location.href='../index.php';
}
</script>
</head>

<body onLoad="MM_preloadImages('file:///C|/webs/home/hidesa/img/menu_feedback2.png','file:///C|/webs/home/hidesa/img/movimiento2.png','file:///C|/webs/home/hidesa/img/consultas2.png','file:///C|/webs/home/hidesa/img/consultas_avanzadas2.png','file:///C|/webs/home/hidesa/img/mantenimiento2.png','file:///C|/webs/home/hidesa/img/impresion2.png','file:///C|/webs/home/hidesa/img/control_del_sistema2.png','img/menu_logout2.png')" width="2000">
<div align="center">
<table width="80%" border="0" align="center" cellpadding="2" cellspacing="2" bordercolor="#000000">
<tr>
<td colspan="7"><div align="center"><img src="../socios/img/logo_hide1.png" width="69" height="69"><img src="../socios/img/banner.png" width="500" height="70"></div></td>
</tr>
<tr>
<td><div align="center">
<p><a href="file:///C|/webs/home/hidesa/control_sistema.php%20target="izquierda_menu" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('control_sistema','','fi le:///C|/webs/home/hidesa/img/control_del_sistema2.png',1)"><img src="../socios/img/control_del_sistema.png" name="control_sistema" width="185" height="26" border="0"></a></p>
</div> </td>
<td><a href="file:///C|/webs/home/hidesa/movimiento.php" target="izquierda_menu" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('movimiento','','file:///C|/webs/home/hidesa/img/movimiento2.png',1)"><img src="../socios/img/movimiento.png" name="movimiento" width="105" height="25" border="0"></a></td>
<td><div align="center"><a href="file:///C|/webs/home/hidesa/consultas" target="izquierda_menu" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('consultas','','file:///C|/webs/home/hidesa/img/consultas2.png',1)"><img src="../socios/img/consultas.png" name="consultas" width="105" height="25" border="0"></a></div></td>
<td><div align="center"><a href="file:///C|/webs/home/hidesa/consultas_avanzadas.php" target="izquierda_menu"onMouseOut="MM_swapImgResto re()" onMouseOver="MM_swapImage('consultas_avanzadas','' ,'file:///C|/webs/home/hidesa/img/consultas_avanzadas2.png',1)"><img src="../socios/img/consultas_avanzadas.png" name="consultas_avanzadas" width="185" height="26" border="0"></a></div></td>
<td><div align="center"><a href="admin/izquierda_mantenimiento.php" target="izquierda_menu" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('mantenimiento','','file :///C|/webs/home/hidesa/img/mantenimiento2.png',1)"><img src="../socios/img/mantenimiento.png" name="mantenimiento" width="140" height="26" border="0"></a></div></td>
<td><a href="file:///C|/webs/home/hidesa/impresion.php" target="izquierda_menu" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('impresion','','file:///C|/webs/home/hidesa/img/impresion2.png',1)"><img src="../socios/img/impresion.png" name="impresion" width="105" height="25" border="0"></a></td>
</tr>
</table>
</div>
<hr>
<?php
$link=Conectarse();
$codigo_nombre=mysql_query("select codusuario, nombempleado, appatempleado, apmatempleado from empleados where codusuario = '$_SESSION['codusuario']'",$link); //consulta para extraer los datos?>

<?php while($row=@mysql_fetch_array($codigo_nombre)){ ?>
<table width="115%" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td height="45"><div align="center">
<h3 align="center">&iexcl;Bienvenido, empleado <?php echo $row[0] ?> : <?php echo $row[1] ?> <?php echo $row[2] ?> <?php echo $row[3] ?> !<a href="javascript:inicio()" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('logout','','img/menu_logout2.png',1)"><img src="img/menu_logout.png" name="logout" width="105" height="25" border="0"></a></h3>
</div></td>
</tr>
</table>
<? } mysql_close($link);?>
<p>&nbsp;</p>
</body>
</html>


la consulta esta bien hecha? tengo que llamarla de alguna forma? porque tambien probe en la consulta primero llamando a la variable asi:

$codusuario = $_SESSION['codusuario'];

y en la consulta ya puse ...WHERE codusuario = $codusuario, pero nada tampoco, que puede ser? si pongo session_start().
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 19:31.