Foros del Web » Programando para Internet » PHP »

PHP Sesiones

Estas en el tema de PHP Sesiones en el foro de PHP en Foros del Web. Hola buenos dias. soy novato en PHP y tengo que desarrollar una pequeña web. grácias avanzadas por cualquier ayuda. Me encuentro con el siguiente problema: ...
  #1 (permalink)  
Antiguo 04/10/2013, 01:55
 
Fecha de Ingreso: octubre-2013
Mensajes: 3
Antigüedad: 10 años, 6 meses
Puntos: 0
PHP Sesiones

Hola buenos dias. soy novato en PHP y tengo que desarrollar una pequeña web.
grácias avanzadas por cualquier ayuda.
Me encuentro con el siguiente problema:

desde un index.php almaceno unas variables de sesion.
en un formulario tipo login al validar, llamo a validar.php y no soy capaz de recuperar el valor almacenado en la sesion.
Si hago un print_r($SESSION) desde validar.php veo perfectamente el valor.

Para el almacenamiento/recuperación de dichos valores, uso un funciones.php.

index.php
-----------------------
session_start();
require_once($_SERVER['DOCUMENT_ROOT']."/utils/funciones.php");
setvar('adprueba','valor a guardar');

funciones.php
--------------------
session_start();
function getVar($idvar) {
if (isset($_SESSION[$idvar])){
return $_SESSION[$idvar];
} else {
return '';
}
}

function setVar($idvar,$value) {
$_SESSION[$idvar] = $value;
}

validar.php
---------------
session_start();
require_once($_SERVER['DOCUMENT_ROOT']."/utils/functions.php");

$valor =getvar('adprueba'); /* aqui no captura el valor */
print_r($_SESSION); /* muestra: Array ( [adprueba] => valor de prueba ... )
  #2 (permalink)  
Antiguo 04/10/2013, 02:03
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: PHP Sesiones

Como nota no deberías iniciar sesión más de una vez, es decir, usar session_start() más de una vez en la misma ejecución.

En tu caso inicias sesión dentro y fuera de funciones.php lo cual está mal.

En relación al print_r() y getVar() pues tiene sentido que no veas nada, porque sencillamente no haces nada para imprimir el valor que obtienes.

La función print_r() imprime efectivamente lo que le pases, pero en la linea donde asignas $valor no haces nada para imprimir y verificar que hay algo, ¿o me equivoco?

Porque vamos, si tu código es tal cual lo muestras la respuesta es obvia.
Código PHP:
Ver original
  1. $valor = getVar('adprueba');
  2. echo $valor;
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 04/10/2013, 02:17
 
Fecha de Ingreso: octubre-2013
Mensajes: 3
Antigüedad: 10 años, 6 meses
Puntos: 0
Respuesta: PHP Sesiones

Error tipográfico, he olvidado copiar el print_r($valor);
  #4 (permalink)  
Antiguo 04/10/2013, 02:34
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: PHP Sesiones

Cita:
Iniciado por ADJP Ver Mensaje
Error tipográfico, he olvidado copiar el print_r($valor);
Aún así, carece de sentido tu ejemplo.

Como prueba, dentro de la función getVar() has un var_dump() de $_SESSION y muestra lo que te resulte.

Es decir, independientemente del contexto sí existe algo en la sesión, y un código tan simple como el de getVar() no debería fallar así no más por que sí.

Hay algo que no vemos, o hay algo que tu no ves.

A simple vista el código es correcto.
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #5 (permalink)  
Antiguo 04/10/2013, 04:02
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: PHP Sesiones

Quita el session_start(); de funciones.php
  #6 (permalink)  
Antiguo 04/10/2013, 09:48
 
Fecha de Ingreso: octubre-2013
Mensajes: 3
Antigüedad: 10 años, 6 meses
Puntos: 0
Respuesta: PHP Sesiones

Hola, tampoco funciona quitando el session_start del funciones.php.

VarDump's:

vardump al cargar la página index.php
array(6) { ["adws"]=> string(23) "http://localhost:23967/" ["adweb"]=> string(39) "http://portal.adhumansoft.com/index.php" ["adsession"]=> string(26) "xxxxxxxx" ["adlanguage"]=> string(3) "cat" ["adpage"]=> string(0) "" ["aderror"]=> string(0) "" }

vardump al cargar la página loginuser.php
array(2) { ["adpage"]=> string(0) "" ["aderror"]=> string(22) "Error inicio sesion..." }

Por algun motivo, es como si no recuperara la sesion en curso.

adjunto codigo:

---------------------------------------------------------------
index.php
---------------------------------------------------------------
Código PHP:
Ver original
  1. <?php
  2.     require_once($_SERVER['DOCUMENT_ROOT']."/utils/functions.php");
  3.     $cur_web = getVar('adweb');
  4.     if ($cur_web == "") {
  5.         session_destroy();
  6.         session_unset();
  7.         session_write_close();
  8.         session_cache_limiter('private');
  9.         session_start();
  10.         error_reporting(E_ALL);
  11.         ini_set('display_errors', '1');
  12.         ini_set("soap.wsdl_cache_enabled","0");
  13.         header("charset=utf-8");   
  14.         setVar('adws', "http://localhost:23967/"); 
  15.         try {
  16.             $url_actual = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
  17.             setVar('adweb', $url_actual);
  18.             $url = getVar('adws')."adConfig.asmx?WSDL";
  19.             $client = new SoapClient($url);
  20.             $data = array('');
  21.         $response  = $client->GetConfig($data)->GetConfigResult;
  22.             $xml = new SimpleXMLElement($response);    
  23.             $lang = (string)$xml->config->language;
  24.            
  25.             $data = array('sLang' => $lang);
  26.             $response  = $client->GetLanguage($data)->GetLanguageResult;
  27.             $xmllang = new SimpleXMLElement($response);
  28.            
  29.             setVar('adsession', (string) session_id());
  30.             setVar('adlanguage',  strtolower($lang));
  31.             setVar('adpage', '');
  32.             setVar('aderror','');
  33.            
  34.         } catch(Exception $e) {
  35.                
  36.                 $xmllang = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" standalone= "yes"?> <idiomas></idiomas>');
  37.                 setVar('adsession', '');
  38.                 setVar('adlanguage', '');
  39.                 setVar('adpage', 'errorpage');
  40.                 setVar('aderror', $e->getMessage());
  41.                
  42.         }      
  43.        
  44.     }
  45. ?>
  46. <!DOCTYPE html>
  47. <html lang="es">
  48.     <head>
  49.         <meta charset="utf-8" />
  50.         <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
  51.         <title>PRUEBAS</title>
  52.         <meta name="description" content="PRUEBAS" />
  53.         <meta name="author" content="PRUEBAS" />
  54.         <meta name="viewport" content="width=device-width; initial-scale=1.0" />
  55.         <link rel="shortcut icon" href="image/PRUEBAS.ico" />
  56.         <link rel="favicon" href="image/PRUEBAS.ico" />
  57.         <link rel="stylesheet" href="css/PRUEBAS.css" />
  58.     </head>
  59.  
  60.     <body>
  61.         <?php
  62.        
  63.         ?>
  64.         <section class="mainContainer">
  65.                 <?php
  66.                         require_once($_SERVER['DOCUMENT_ROOT'].'/desktop.php');                        
  67.                 ?>
  68.         </section>
  69.         <?php var_dump($_SESSION); ?>
  70.     </body>
  71. </html>
---------------------------------------------------------------
functions.php
---------------------------------------------------------------

Código PHP:
Ver original
  1. <?php
  2.     function getVar($idvar) {
  3.         if (isset($_SESSION[$idvar])){
  4.             return $_SESSION[$idvar];
  5.         } else {
  6.             return '';
  7.         }
  8.     }
  9.  
  10.     function setVar($idvar,$value) {   
  11.         $_SESSION[$idvar] = $value;
  12.         session_write_close(); 
  13.     }
  14.    
  15.     function XMLToArray($xml) {
  16.       if ($xml instanceof SimpleXMLElement) {
  17.         $children = $xml->children();
  18.         $return = null;
  19.       }
  20.       foreach ($children as $element => $value) {
  21.         if ($value instanceof SimpleXMLElement) {
  22.           $values = (array)$value->children();
  23.          
  24.           if (count($values) > 0) {
  25.             $return[$element] = XMLToArray($value);
  26.           } else {
  27.             if (!isset($return[$element])) {
  28.               $return[$element] = (string)$value;
  29.             } else {
  30.               if (!is_array($return[$element])) {
  31.                 $return[$element] = array($return[$element], (string)$value);
  32.               } else {
  33.                 $return[$element][] = (string)$value;
  34.               }
  35.             }
  36.           }
  37.         }
  38.       }
  39.       return $return;
  40.     }
  41.    
  42.     function GetLang($xmllang,$idLang,$defaultvalue) {
  43.         $return = "*".$defaultvalue;
  44.         if ($idLang != "") {
  45.            
  46.             try {
  47.               $readlang = (string) $xmllang->{getvar('adlanguage')}->{$idLang};
  48.               if ($readlang != "") {
  49.                 $return = $readlang;
  50.               }
  51.             } catch (exception $e) {
  52.            
  53.             }
  54.            
  55.         }
  56.        
  57.         return $return;
  58.     }  
  59.    
  60. ?>


---------------------------------------------------------------
desktop.php
---------------------------------------------------------------
Código PHP:
Ver original
  1. <?php
  2.            
  3.     $cur_page = getVar('adpage');
  4.     $aduser = getVar('aduser');
  5.    
  6.     switch ($cur_page) {
  7.         case 'errorpage':
  8.             require_once($_SERVER['DOCUMENT_ROOT'].'/errorpage.php');  
  9.             break;
  10.         case '':
  11.             require_once($_SERVER['DOCUMENT_ROOT'].'/login.php');          
  12.             break;
  13.            
  14.         default:           
  15.             break;
  16.     }
  17.    
  18. ?>

---------------------------------------------------------------
login.php
---------------------------------------------------------------
Código PHP:
Ver original
  1. <?php
  2.  ?>
  3. <div class="loginform cf">
  4.     <form name="login" action="loginuser.php" method="post" accept-charset="utf-8">
  5.         <img src="./image/SistemaHumansoft.png" class="LoginImage" >
  6.         <table>
  7.             <tr>
  8.                 <td><label for="userid"><?php echo GetLang($xmllang,'l60018',"Usuario");?></label></td>
  9.                 <td><input type="text"  name="userid" title="" placeholder="<?php echo GetLang($xmllang,'l1536',"Indicar código profesional");?>" required="prova"></td>
  10.             </tr>
  11.             <tr>
  12.                 <td><label for="userpas"><?php echo GetLang($xmllang,'l60019',"Contraseña");?></label></td>
  13.                 <td><input type="password" name="userpas" title="" placeholder="" required></td>
  14.             </tr>
  15.             <tr>
  16.                 <td colspan="2"><input type="submit" value="<?php echo GetLang($xmllang,'l90008',"Validar");?>" ></td>
  17.             </tr>
  18.             <?php
  19.                 $err = getVar('aderror');
  20.                 if ($err != "") {
  21.             ?>         
  22.                 <tr>
  23.                     <td colspan="2"><?php echo $err ?></td>
  24.                 </tr>
  25.             <?php
  26.                 }
  27.             ?>
  28.         </table>
  29.         </form>
  30.        
  31.         <?php
  32.        
  33.         $err = getVar('aderror');
  34.         if ($err != "") {
  35.            
  36.            
  37.             ?>
  38.             <script>alert('error');</script>
  39.            
  40.            
  41.             <?php
  42.            
  43.             setVar('aderror','');
  44.         }
  45.        
  46.         ?>
  47.        
  48. </div>

---------------------------------------------------------------
loginuser.php
---------------------------------------------------------------
Código PHP:
Ver original
  1. <?php
  2.    
  3.    
  4.     session_start();
  5.     require_once($_SERVER['DOCUMENT_ROOT']."/utils/functions.php");
  6.    
  7.    
  8.    
  9.     setVar('adpage','');
  10.     $url_actual = getVar('adweb');
  11.  
  12.     $userid = $_POST['userid'];
  13.     $userpass = $_POST['userpas'];
  14.  
  15.     $temp = getvar('adws');
  16.     $urlws = $temp."adPortal.asmx?WSDL";
  17.    
  18.    
  19.     /*$client = new SoapClient($urlws);
  20.     $data = array('sIdUser' => $userid,
  21.                   'sIdPass' => $userpass);
  22.     if (( $client->IsValidUser($data)->IsValidUserResult) == true ) {
  23.    
  24.         print_r("User Ok");
  25.         setVar('aderror','');
  26.        
  27.     } else {
  28.        
  29.         setVar('aderror','Error inicio sesion...');
  30.        
  31.        
  32.     }*/
  33.    
  34.    
  35.     setVar('aderror','Error inicio sesion...');
  36.        
  37.     var_dump($_SESSION);
  38.     //header("location: ".$url_actual);
  39.  
  40.    
  41.    
  42. ?>

Etiquetas: formulario, sesiones, variable
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 12:48.