Foros del Web » Programando para Internet » PHP »

Funciones sesion y header

Estas en el tema de Funciones sesion y header en el foro de PHP en Foros del Web. Hola estoy creando una nueva aplicacion en php y me da un error en la pagina de login el siguiente Warning: session_start() [function.session-start]: Cannot send ...
  #1 (permalink)  
Antiguo 04/12/2008, 10:46
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Funciones sesion y header

Hola estoy creando una nueva aplicacion en php y me da un error en la pagina de login el siguiente
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\wamp\www\contemplate\Paginas\login.php:1) in C:\wamp\www\contemplate\Paginas\clases.php on line 68.
Este es el codigo de la pagina login:

<?php
include("clases.php");
$temp=new Reportes();
$temp->AbrirSesion();

if(isset($_POST['usuario'])&& isset($_POST['contrasenna']))
{
include("clases.php");
$temp=new Reportes();
$temp->Connection('localhost','reportesphp','root','') ;
$result= $temp->RestringirAcceso($_POST['usuario'],$_POST['contrasenna']);
$cantidad=mysql_num_rows($result);
echo $cantidad;
//mysql_free_result($result);
//mysql_close();

if($cantidad>0){
$fila=mysql_fetch_row($result);
//$_SESSION['MM_Username'] = $fila[0];
//$GLOBALS['MM_Username'] = $fila[0];
//session_register("MM_Username");
//echo MM_Username;

//header ("location:RegistrarReporte.php");

}
/*else{
header("location:login.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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../mm_training.css" type="text/css" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Documento sin t&iacute;tulo</title>
<!-- TemplateEndEditable -->
<style type="text/css">
<!--
.Estilo5 {color: #FFBA00}
-->
</style>
<!-- TemplateBeginEditable name="head" --><!-- TemplateEndEditable -->
</head>

<BODY BGCOLOR="#FFFFFF" text="#000000" link="#CCCCFF" vlink="#CCCCFF">
<table width="76%" border="0" cellpadding="0" cellspacing="0" bgcolor="#D3DCE6">
<tr>
<td width="221" height="53" valign="top"><IMG SRC="../images/index1x1.jpg" WIDTH=221 HEIGHT=53 BORDER=0></td>
<td width="162" height="53" valign="top"><IMG SRC="../images/index1x2.jpg" WIDTH=162 HEIGHT=53 BORDER=0></td>
<td width="119" height="53" valign="top"><IMG SRC="../images/index1x3.jpg" WIDTH=119 HEIGHT=53 BORDER=0></td>
<td width="16" height="53" valign="top"><IMG SRC="../images/index1x4.jpg" WIDTH=16 HEIGHT=53 BORDER=0 ALT="http://www.forosdelweb.com/images/index1x4.jpg"></td>
<td width="129" height="53" valign="top"><IMG SRC="../images/index1x5.jpg" WIDTH=129 HEIGHT=53 BORDER=0></td>
<td width="133" height="53" valign="top"><IMG SRC="../images/index1x6.jpg" WIDTH=133 HEIGHT=53 BORDER=0></td>
</tr>
<tr>
<td width="221" height="98" rowspan="2" valign="top"><IMG SRC="../images/index2x1.jpg" WIDTH=221 HEIGHT=98 BORDER=0></td>
<td width="162" height="98" rowspan="2" valign="top"><IMG SRC="../images/index2x2.jpg" WIDTH=162 HEIGHT=98 BORDER=0></td>
<td width="119" height="98" rowspan="2" valign="top"><IMG SRC="../images/index2x3.jpg" WIDTH=119 HEIGHT=98 BORDER=0></td>
<td width="16" height="98" rowspan="2" valign="top"><IMG SRC="../images/index2x4.jpg" WIDTH=16 HEIGHT=98 BORDER=0 ALT="http://www.forosdelweb.com/images/index2x4.jpg"></td>
<td width="129" height="57" valign="top"><IMG SRC="../images/index2x5.jpg" WIDTH=129 HEIGHT=57 BORDER=0></td>
<td width="133" height="57" valign="top"><img src="../images/index2x6.jpg" width=133 height=57 border=0></td>
</tr>
<tr>
<td width="129" height="41" valign="top"><IMG SRC="../images/index3x1.jpg" WIDTH=129 HEIGHT=41 BORDER=0></td>
<td width="133" height="41" valign="top"><IMG SRC="../images/index3x2.jpg" WIDTH=133 HEIGHT=41 BORDER=0></td>
</tr>
<tr>
<td width="502" height="4" colspan="3" valign="top"><IMG SRC="../images/autenf2.JPG" WIDTH=502 HEIGHT=4 BORDER=0 ALT="http://www.forosdelweb.com/images/index4x1.jpg"></td>
<td width="278" height="4" colspan="3" valign="top"><IMG SRC="../images/autenf2.JPG" WIDTH=278 HEIGHT=4 BORDER=0 ALT="http://www.forosdelweb.com/images/index4x2.jpg"></td>
</tr>
<tr>
<td width="502" height="20" colspan="3" valign="top" bgcolor="#26354A"><span class="Estilo5"><marquee behavior="scroll">
REPORTES SEISA
</marquee></span> </td>
<td width="278" height="20" colspan="3" valign="top" bgcolor="#26354A">&nbsp;</td>
</tr>
<tr>
<td width="780" height="4" colspan="6" valign="top" bgcolor="#FF6600"><IMG SRC="../images/autenf2.JPG" WIDTH=780 HEIGHT=4 BORDER=0 ALT="http://www.forosdelweb.com/images/index6x1.jpg"></td>
</tr>
<tr>
<td width="780" height="28" colspan="6" align="center" valign="top">&nbsp;</td>
</tr>
<tr>
<td width="221" height="4" valign="top"></td>
<td width="162" height="4" valign="top"></td>
<td width="119" height="4" valign="top"></td>
<td width="16" height="8" rowspan="2" valign="top">&nbsp;</td>
<td width="129" height="4" valign="top"></td>
<td width="133" height="4" valign="top"></td>
</tr>
<tr>
<td width="221" height="4" valign="top"></td>
<td width="162" height="4" valign="top"></td>
<td width="119" height="4" valign="top"></td>
<td width="262" height="279" colspan="2" rowspan="2" valign="top">&nbsp;</td>
</tr>
<tr>
<td width="502" height="275" colspan="3" valign="top"><!-- TemplateBeginEditable name="edtRegionAutenticacion" -->
<p></p>

<form ACTION="login.php" method="post" name="autenticarse" id="autenticarse" onsubmit="MM_validateForm('usuario','','R','contra senna','','R');return document.MM_returnValue">
<table width="26%" border="0" cellspacing="0" cellpadding="1" class="TitleColor">
<tr style="vertical-align: top">
<td><table width="26%" border="0" cellspacing="0" cellpadding="4">
<tr style="vertical-align: top">
<td width="20%" class="TitleColor"><label for="username"><strong>User Name</strong></label>
&nbsp;<br />
<input id="usuario" name="usuario" type="text" size="25" />
<p>&nbsp;</p>
<label for="password"><strong>Password</strong></label>
&nbsp;<br />
<input id="contrasenna" name="contrasenna" type="password" size="25" />
<p>
<input type="submit" name="ButtonName" value="Entrar" />
</p></td>
</tr>
</table></td>
</tr>
</table>
</form>
<p>&nbsp;</p>
<!-- TemplateEndEditable --> </td>
<td width="16" height="275" valign="top">&nbsp;</td>
</tr>
<tr>
<td height="30" colspan="3" valign="top">&nbsp;</td>
<td height="30" valign="top">&nbsp;</td>
<td height="30" colspan="2" valign="top">&nbsp;</td>
</tr>
<tr>
<td width="502" height="30" colspan="3" valign="top" bgcolor="#26354A"><p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p></td>
<td width="16" height="30" valign="top" bgcolor="#26354A">&nbsp;</td>
<td width="262" height="30" colspan="2" valign="top" bgcolor="#26354A">&nbsp;</td>
</tr>
<tr>
<td width="221" height="1" valign="top"><img width="221" height="1" src="../transparent.gif"></td>
<td width="162" height="1" valign="top"><img width="162" height="1" src="../transparent.gif"></td>
<td width="119" height="1" valign="top"><img width="119" height="1" src="../transparent.gif"></td>
<td width="16" height="1" valign="top"><img width="16" height="1" src="../transparent.gif"></td>
<td width="129" height="1" valign="top"><img width="129" height="1" src="../transparent.gif"></td>
<td width="133" height="1" valign="top"><img width="133" height="1" src="../transparent.gif"></td>
</tr>
</table>
</BODY>
</html>

y este el de la pagina donde diseñare las clase:

<?php

/*
* class «class»
*/
/*
* class «class»
*/

class Reportes {

/*
* function «name»
* @param $«arg»
*/
var $link;
function __construct()
{
//this->$link;
}
function MostrarMensaje() {

echo 'Esto es una prueba';
}
/*
* function «name»
* @param $«arg»
*/

function Connection($server,$db,$username,$password)
{
$this->link= mysql_connect($server,$username,$password) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($db,$this->link);
// var_dump($this->link);

/*if (!$this->link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';*/



}

function InsertarReporte($fecha_inicio,$hora_inicio, $id_estado,$id_prioridad,$id_sucursal,$descripcion ,$nombre_cliente,$cargo,$id_servicio)
{


$query="Insert into t_reporte (fecha_inicio,hora_inicio,nombre_cliente,descripci on,cargo,id_sucursal,id_prioridad,id_estado,id_ser vicio)values('$fecha_inicio','$hora_inicio','$nomb re_cliente','$descripcion','$cargo','$id_sucursal' ,'$id_prioridad','$id_estado','$id_servicio')";
//var_dump($this->link);
mysql_query($query,$this->link);
mysql_close();

}

function RestringirAcceso($usuario,$contrasenna) {

$query="SELECT usuario, contrasenna FROM t_usuario WHERE usuario='$usuario' AND contrasenna='$contrasenna'";
$result= mysql_query($query,$this->link);
//$cant=mysql_num_rows($result);
//mysql_free_result($result);
//mysql_close();
return $result;
}

function AbrirSesion() {
//if (!isset($_SESSION))
session_start();
}

}
?>

Por favor me urge que alguien me ayude.
  #2 (permalink)  
Antiguo 04/12/2008, 10:54
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Funciones sesion y header

Hola yanuarys,

Revisa este link: http://www.forosdelweb.com/2037876-post179.html

Saludos.
  #3 (permalink)  
Antiguo 04/12/2008, 10:55
Avatar de Ronruby  
Fecha de Ingreso: julio-2008
Ubicación: 18°30'N, 69°59'W
Mensajes: 4.879
Antigüedad: 15 años, 9 meses
Puntos: 416
Respuesta: Funciones sesion y header

Cita:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\wamp\www\contemplate\Paginas\login.php:1) in C:\wamp\www\contemplate\Paginas\clases.php on line 68.
Ese mensaje de error es muy comun. Significa que estas tratando de imprimir ALGO (lo que sea) antes de usar header() o setcookie(), por lo cual te dice que las cabeceras ya fueron enviadas.

Tienes que revisar que no se imprima NADA antes de header() o setcookie().

Nota: Mete el codigo PHP en etiquetas [php ][/php], es mas facil de leer ;)
  #4 (permalink)  
Antiguo 04/12/2008, 12:34
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Gracias supuse que ese era el problema incluso ahora solo inicio la sesion en la misma pagina no lo mando a la otra y me da este mismo error

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\wamp\www\contemplate\Paginas\login.php:1) in C:\wamp\www\contemplate\Paginas\login.php on line 3

de nuevo les envio el codigo de la pagina

Código PHP:
 <?php
 
if(!isset($_SESSION)) 
 
session_start();
 
//include("clases.php");
 //$temp=new Reportes();
 //$temp->AbrirSesion();
 
?>
 <?php
  
      
if(isset($_POST['usuario'])&& isset($_POST['contrasenna']))
      {
        include(
"clases.php");
        
$temp=new Reportes();
        
$temp->Connection('localhost','reportesphp','root','');
       
$result$temp->RestringirAcceso($_POST['usuario'],$_POST['contrasenna']);
       
$cantidad=mysql_num_rows($result);
       echo 
$cantidad;
       
//mysql_free_result($result);
       //mysql_close();
       
       
if($cantidad>0){
        
$fila=mysql_fetch_row($result);
         
//$_SESSION['MM_Username'] = $fila[0];
         //$GLOBALS['MM_Username'] = $fila[0];
         //session_register("MM_Username");
         //echo MM_Username;
        
        //header ("location:RegistrarReporte.php"); 
        
      
}
      
/*else{
        header("location:login.php");
      }*/
      
}
      
?>
Soy principiante y quisiera saber ademas si por esta variable puedo preguntar asi si haberla declarado nunca esta predefinida $_SESSION.
Les agradeceria su ayuda no saben lo desesperada que estoy
  #5 (permalink)  
Antiguo 04/12/2008, 12:59
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Ademas ese error me aparece dos veces encima de la pagina
que es el mismo

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\wamp\www\contemplate\Paginas\login.php:1) in C:\wamp\www\contemplate\Paginas\login.php on line 3

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\wamp\www\contemplate\Paginas\login.php:1) in C:\wamp\www\contemplate\Paginas\login.php on line 3

Gracias
  #6 (permalink)  
Antiguo 05/12/2008, 08:24
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Estoy utilizando el Komodo como ide y al debugear me sale este error

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at C:\wamp\www\contemplate\Paginas\login.php:1) in C:\wamp\www\contemplate\Paginas\login.php on line 3

Call Stack:
0.1008 73528 1. {main}() C:\wamp\www\contemplate\Paginas\login.php:0
0.1009 74184 2. session_start() C:\wamp\www\contemplate\Paginas\login.php:3



Por favor no duden en ayudarme lean todo lo que he enviado para intentar que me comprendan.
  #7 (permalink)  
Antiguo 05/12/2008, 08:25
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Por favor ayudenme
  #8 (permalink)  
Antiguo 05/12/2008, 08:31
Avatar de David
Moderador
 
Fecha de Ingreso: abril-2005
Ubicación: In this planet
Mensajes: 15.720
Antigüedad: 19 años
Puntos: 839
Respuesta: Funciones sesion y header

Fíjate que no haya NINGÚN tipo de salida antes de invocar a session_start() o header(). O sea, ni siquiera un espacio en blanco debe haber. Por otro lado, si ya quitaste toda salida y aún no funciona, revisa esto: http://www.forosdelweb.com/2023067-post176.html
__________________
Por favor, antes de preguntar, revisa la Guía para realizar preguntas.
  #9 (permalink)  
Antiguo 05/12/2008, 08:46
 
Fecha de Ingreso: marzo-2008
Mensajes: 73
Antigüedad: 16 años
Puntos: 0
Respuesta: Funciones sesion y header

Cita:
Iniciado por yanuarys Ver Mensaje
Por favor ayudenme
El problema es bastante común. Mayormente el problema está en que hay espacios en blanco antes de session_start() o del mismo tag de PHP. Revísa en tu código que eso no pase, ya que como previamente han dicho, no puedes mandar NADA antes de header() o session_start().

Intenta borrar esos espacios y esos "enters" que hay antes de que se llame a la función session_start().
  #10 (permalink)  
Antiguo 05/12/2008, 09:07
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Gracias ya resovi disculpen mi novatada era un espacio pequeño ante la etiqueta php y no me percate les agradezco de corazon los quiere Yanuarys.Besos.
  #11 (permalink)  
Antiguo 05/12/2008, 11:20
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Ahora tengo el siguiente problema paso el nombre del usuario que se logeo a otra pagina y sale bien pero si en la barra pongo la direccion de la paina de login y entro con otro usuario en la siguiente pagina se muestra el nombre del primero que se registro.Sin embargo si cierro el navegador y lo vuelvo a abrir no hay problema.
Alguien tiene idea que tengo que hacer para arreglarlo y se me actualice.

Aqui muestro el codigo de login.php
Código PHP:
<?php
 
if(!isset($_SESSION))
 
session_start();
 
//if (!empty( $_SESSION['MM_Username'] ))
 //$_SESSION['MM_Username'] = '';
  
?><?php
  
      
if(isset($_POST['usuario'])&& isset($_POST['contrasenna']))
      {
        include(
"clases.php");
        
$temp=new Reportes();
        
$temp->Connection('localhost','reportesphp','root','');
       
$result$temp->RestringirAcceso($_POST['usuario'],$_POST['contrasenna']);       
       
$cantidad=mysql_num_rows($result);         
       if(
$cantidad>0){
        
$fila=mysql_fetch_row($result);         
        
//$_SESSION['MM_Username']=$fila[0];
        
$GLOBALS['MM_Username'] = $fila[0];
        
session_register("MM_Username");
        
//echo $_SESSION['MM_Username'];
        
header("location:RegistrarReporte.php");
        exit();
      }
      else{
        
header("location:login.php");
        exit();
         
      }
      }
      
?>
Este otro en el principio de RegistrarReporte.php que es a donde redirecciona login.php

Código PHP:
<?php
 
if(!isset($_SESSION))
 
session_start(); 
 if (!isset(
$_SESSION['MM_Username'])){
   
header("location:login.php");
   exit();
 } 
  
?>
Dentro de la pagina RegistrarReporte.php muestro el valor asi(este es el que no se actualiza correctamente):

Código PHP:
<?php echo $_SESSION['MM_Username'];?>
:
  #12 (permalink)  
Antiguo 05/12/2008, 11:28
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Funciones sesion y header

Tienes que hacer una pagina de logout donde destruyas la sesion, con algo asi basta:
Código php:
Ver original
  1. $_SESSION = array();
  2. header("Location: index.php");

Saludos.
  #13 (permalink)  
Antiguo 05/12/2008, 13:19
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
De acuerdo Respuesta: Funciones sesion y header

Disculpa pero soy principiante y no entiendo mucho supongo que con eso limpias o destruyes la sesion pero a que pagina debo conectar con el fichero logout y si no es mucho pedir me podrias explicar por encima ese codigo a ver si logro ir aprendiendo te lo voy a agradecer para ver si termino este proyecto.Espero por tu ayuda.Gracias
  #14 (permalink)  
Antiguo 05/12/2008, 13:25
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Funciones sesion y header

Con eso limpias la sesión y si quieres que el usuario salga tienes que poner un enlace a esa pagina.

Saludos.
  #15 (permalink)  
Antiguo 05/12/2008, 14:44
 
Fecha de Ingreso: noviembre-2008
Mensajes: 43
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: Funciones sesion y header

Tienes razon pero por ejemplo si enlazo ese codigo con el boton salir pero sigue el problema si cierra la pagina directamente en el boton cerrar de la ventana de windows o si vuelve a cargar la pagina de login en el navegador despues de haber entrado con otro usuario ese se queda enganchado y es el nombre que se muestra y creo que debo controlarlo lo ideal fuera que utilizaran la opcion salir pero sabemos que por lo general hay que prever cualquier accion del usuario.Gracias necesito tu ayuda.
  #16 (permalink)  
Antiguo 05/12/2008, 15:54
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Funciones sesion y header

En ese caso modifica el php.ini, pon que la cookie solo sea valida mientras el usuario no ha cerrado el browser.

Los parámetros que buscas estan dentro de la sección session.

Saludos.
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:20.