Foros del Web » Programando para Internet » PHP »

Problemas con el envio de datos

Estas en el tema de Problemas con el envio de datos en el foro de PHP en Foros del Web. Saludos, estoy realizando un sistema donde ingreso usuarios pero al recargar la pagina me da este error Warning: Cannot modify header information - headers already ...
  #1 (permalink)  
Antiguo 23/03/2009, 10:46
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 7 meses
Puntos: 28
Problemas con el envio de datos

Saludos, estoy realizando un sistema donde ingreso usuarios pero al recargar la pagina me da este error

Warning: Cannot modify header information - headers already sent by (output started at /home/bodakare/public_html/lista/listado.php:7) in /home/bodakare/public_html/lista/ing_invitados.php on line 57

Ahora bien, me recarga la pagina y no actualiza el listado lo cual deberia hacerlo, pero ahora delen F5 para actualizar y veran como el usuario se repite y repite.. se agrega muchas veces...

Prueba

aqui les dejo mi codigo de la pagina que contiene el formulario

Código PHP:
<?php require_once('Connections/cersol.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "''";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "''";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? "'" doubleval($theValue) . "'" "''";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "''";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {


  
$insertSQL sprintf("INSERT INTO invitados (id, usuario, pass, nombre, apellido, invitados, status) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['id'], "int"),
                       
GetSQLValueString($_POST['usuario'], "text"),
                       
GetSQLValueString($_POST['pass'], "text"),
                       
GetSQLValueString($_POST['nombre'], "text"),
                       
GetSQLValueString($_POST['apellido'], "text"),
                       
GetSQLValueString($_POST['invitados'], "text"),
                       
GetSQLValueString($_POST['status'], "int"));

  
mysql_select_db($database_cersol$cersol);
  
$Result1 mysql_query($insertSQL$cersol) or die(mysql_error());

  
$insertGoTo "listado.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo16 {color: #FFFFFF}
-->
</style>
<link href="file:///C|/wamp/www/css2/estilo.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript">
function validar_archivo(archivo) {
    var error_archivo;
    error_archivo=0;
      var file=archivo.value;
      
          if (file=="")
          { error_archivo=1; }
          //texto += "\n\nIngrese Foto"
            else{
             
                 // file=document.formulario.FOTO.value
               extArray = new Array(".gif",".jpg");
               // Extension de archivos permitidos
               allowSubmit = false;
                 if (!file) return;

                   while (file.indexOf("\\") != -1)
                       file = file.slice(file.indexOf("\\") + 1);
                       ext = file.slice(file.indexOf(".")).toLowerCase();
                   
                   for (var i=0; i < extArray.length; i++){
                          if (extArray[i] == ext){
                             allowSubmit = true;
                             break;
                            }
                    }

                        if (!allowSubmit) {
                         error_archivo=2;
                        // texto += "\n\nFOTO: solo admite archivo con la extensión ''gif, .jpeg , .jpg''";
                         }
                            }
                            return error_archivo;
}

</script>
<script language="JavaScript" type="text/JavaScript">
<!--
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_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->
</script>
<link href="../css/estilo.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
.style2 {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #042641;
}
-->
</style>
</head>

<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><TABLE width=500 border=0 align="center" cellPadding=0 cellSpacing=0 bordercolor="#FF0000" id=table2>
      <TBODY>
        <TR>
          <TD width="8" vAlign=top ></TD>
          <TD width=498 align="center" vAlign=middle class="nucomplet"><form action="<?php echo $editFormAction?>" method="post" enctype="multipart/form-data" name="form1" onSubmit="MM_validateForm('descripcion','','R');return document.MM_returnValue">
              <table width="414" align="center">
                <tr valign="baseline">
                  <td width="96" align="right" valign="middle" nowrap class="textoINDEX"><div align="left">Usuario</div></td>
                  <td width="306" valign="middle" class="textoINDEX"><div align="left">
                    <input name="usuario" type="text" class="textoINDEX" id="usuario">
                    </div></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="middle" nowrap class="textoINDEX"><div align="left">Contrase&ntilde;a</div></td>
                  <td align="left" valign="middle" class="textoINDEX"><input name="pass" type="text" class="textoINDEX" id="pass">
                      </label></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="top" class="textoINDEX"><div align="left">Nombre</div></td>
                  <td align="left" valign="middle" class="textoINDEX"><input name="nombre" type="text" class="textoINDEX" id="nombre"></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="middle" class="Estilo6"><div align="left">Apellido</div></td>
                  <td valign="middle"><div align="left"><span class="textoINDEX">
                    <input name="apellido" type="text" class="textoINDEX" id="apellido">
                  </span></div></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap align="right">N&ordm; de Invitados: </td>
                  <td><div align="left">
                    <label>
                      <select name="invitados" id="invitados">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                      </select>
                    </label>
                  </div></td><input type="hidden" name="status" value="2" id="status">
                </tr>
                <tr valign="baseline">
                  <td nowrap align="right"><input type="hidden" name="MM_insert" value="form1"></td>
                  <td><input name="submit" type="submit" class="textoINDEX" value="Insertar registro"></td>
                </tr>
              </table>
              
          </form></TD>
          <TD width=13 vAlign=top>&nbsp;</TD>
        </TR>
      </TBODY>
    </TABLE></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>
Alguien sabe pq es????

un saludo y gracias de antemano!!!!
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #2 (permalink)  
Antiguo 23/03/2009, 11:02
Avatar de Ronruby  
Fecha de Ingreso: julio-2008
Ubicación: 18°30'N, 69°59'W
Mensajes: 4.879
Antigüedad: 15 años, 8 meses
Puntos: 416
Respuesta: Problemas con el envio de datos

Yo recargue la página, y no me dio error. O.o!

PD: Cambia el metodo para pasar de un tab a otro, es molesto pasar el mouse sin querer por encima y que el contenido cambie.

EDIT: ah si, ya vi el error.
Echale una mirada a lo que te dijo argy
  #3 (permalink)  
Antiguo 23/03/2009, 11:04
Avatar de argy  
Fecha de Ingreso: octubre-2007
Ubicación: Longitud 75º Latitud 18º Sur
Mensajes: 614
Antigüedad: 16 años, 4 meses
Puntos: 18
Respuesta: Problemas con el envio de datos

la advertencia es porque estás enviando algún texto o espacio en blanco al navegador antes de la cabecera header. es por ello que no te permite redireccionar a la otra página, después de insertar el registro y que al actualizar se siga ingresando los mismos datos, ya que siguen existiendo.

lo que tienes que verificar es de no enviar nada de texto ni espacio en blanco, además de no imprimir nada antes de la cabecera header. Además es recomendable utilizar exit después de header, para asegurarse que no se ejecuta más código.
__________________
Software libre para un mundo libre.

Eventualmente en el foro.
  #4 (permalink)  
Antiguo 23/03/2009, 11:07
Avatar de Ronruby  
Fecha de Ingreso: julio-2008
Ubicación: 18°30'N, 69°59'W
Mensajes: 4.879
Antigüedad: 15 años, 8 meses
Puntos: 416
Respuesta: Problemas con el envio de datos

Especificamente, el error esta en esta linea:

header(sprintf("Location: %s", $insertGoTo));

Si incluyes esa pagina, o lo que sea, no puedes utilizar cabeceras ya que el archivo que lo incluyo, probablemente (en tu caso es asi) ya envio contenido al navegador.

Usa Javascript para la redireccion.
  #5 (permalink)  
Antiguo 23/03/2009, 11:08
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 7 meses
Puntos: 28
Respuesta: Problemas con el envio de datos

Gracias a ambos, a que te refieres con usar exit despues del header???? si te fijas en mi codigo no dejo espacios en blanco y es lo q me tiene preocupado he revisado esos detalles y no los encuentro!!!!
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #6 (permalink)  
Antiguo 23/03/2009, 11:10
Avatar de Ronruby  
Fecha de Ingreso: julio-2008
Ubicación: 18°30'N, 69°59'W
Mensajes: 4.879
Antigüedad: 15 años, 8 meses
Puntos: 416
Respuesta: Problemas con el envio de datos

Cita:
Gracias a ambos, a que te refieres con usar exit despues del header???? si te fijas en mi codigo no dejo espacios en blanco y es lo q me tiene preocupado he revisado esos detalles y no los encuentro!!!!
Esa pagina la incluyes, la pagina que INCLUYO a esta ya ENVIO DE TODO al navegador, por eso el error.

Recuerda que cuando incluyes una pagina en otra, es como si pegaras el codigo fuente ahi mismo.

Con usar exit() despues del header, esto evita que se procese todo el codigo luego de header().
  #7 (permalink)  
Antiguo 23/03/2009, 11:12
Avatar de argy  
Fecha de Ingreso: octubre-2007
Ubicación: Longitud 75º Latitud 18º Sur
Mensajes: 614
Antigüedad: 16 años, 4 meses
Puntos: 18
Respuesta: Problemas con el envio de datos

con exit te aseguras que no se ejecuten más códigos después del header.
__________________
Software libre para un mundo libre.

Eventualmente en el foro.
  #8 (permalink)  
Antiguo 23/03/2009, 11:21
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 7 meses
Puntos: 28
Respuesta: Problemas con el envio de datos

use el header y eliomine las etiquetas HTML y se puso peor :S:S

Código PHP:
<?php require_once('Connections/cersol.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "''";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "''";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? "'" doubleval($theValue) . "'" "''";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "''";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}
$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {


  
$insertSQL sprintf("INSERT INTO invitados (id, usuario, pass, nombre, apellido, invitados, status) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['id'], "int"),
                       
GetSQLValueString($_POST['usuario'], "text"),
                       
GetSQLValueString($_POST['pass'], "text"),
                       
GetSQLValueString($_POST['nombre'], "text"),
                       
GetSQLValueString($_POST['apellido'], "text"),
                       
GetSQLValueString($_POST['invitados'], "text"),
                       
GetSQLValueString($_POST['status'], "int"));

  
mysql_select_db($database_cersol$cersol);
  
$Result1 mysql_query($insertSQL$cersol) or die(mysql_error());

  
$insertGoTo "listado.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
  exit();
}
?>
<script language="JavaScript" type="text/JavaScript">
<!--
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_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->
</script>
<style type="text/css">
<!--
.style2 {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #042641;
}
-->
</style>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><TABLE width=500 border=0 align="center" cellPadding=0 cellSpacing=0 bordercolor="#FF0000" id=table2>
      <TBODY>
        <TR>
          <TD width="8" vAlign=top ></TD>
          <TD width=498 align="center" vAlign=middle class="nucomplet"><form action="<?php echo $editFormAction?>" method="post" enctype="multipart/form-data" name="form1" onSubmit="MM_validateForm('descripcion','','R');return document.MM_returnValue">
              <table width="414" align="center">
                <tr valign="baseline">
                  <td width="96" align="right" valign="middle" nowrap class="textoINDEX"><div align="left">Usuario</div></td>
                  <td width="306" valign="middle" class="textoINDEX"><div align="left">
                    <input name="usuario" type="text" class="textoINDEX" id="usuario">
                    </div></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="middle" nowrap class="textoINDEX"><div align="left">Contrase&ntilde;a</div></td>
                  <td align="left" valign="middle" class="textoINDEX"><input name="pass" type="text" class="textoINDEX" id="pass">
                      </label></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="top" class="textoINDEX"><div align="left">Nombre</div></td>
                  <td align="left" valign="middle" class="textoINDEX"><input name="nombre" type="text" class="textoINDEX" id="nombre"></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="middle" class="Estilo6"><div align="left">Apellido</div></td>
                  <td valign="middle"><div align="left"><span class="textoINDEX">
                    <input name="apellido" type="text" class="textoINDEX" id="apellido">
                  </span></div></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap align="right">N&ordm; de Invitados: </td>
                  <td><div align="left">
                    <label>
                      <select name="invitados" id="invitados">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                      </select>
                    </label>
                  </div></td><input type="hidden" name="status" value="2" id="status">
                </tr>
                <tr valign="baseline">
                  <td nowrap align="right"><input type="hidden" name="MM_insert" value="form1"></td>
                  <td><input name="submit" type="submit" class="textoINDEX" value="Insertar registro"></td>
                </tr>
              </table>
              </form></TD>
          <TD width=13 vAlign=top>&nbsp;</TD>
        </TR>
      </TBODY>
    </TABLE></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #9 (permalink)  
Antiguo 23/03/2009, 11:24
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Problemas con el envio de datos

Revisa esto:

http://www.forosdelweb.com/2037876-post179.html

Tienes que eliminar la salida de texto que tienes en ing_invitados.php en la linea 57.

Saludos.
  #10 (permalink)  
Antiguo 23/03/2009, 11:28
Avatar de SCY-FOX  
Fecha de Ingreso: septiembre-2007
Ubicación: Chile
Mensajes: 139
Antigüedad: 16 años, 6 meses
Puntos: 5
Respuesta: Problemas con el envio de datos

Prueba cambiando esto:
Código PHP:
  header(sprintf("Location: %s"$insertGoTo)); 
por esto otro

Código PHP:
echo "<script type='text/javascript'>window.location='$insertGoTo';</script>"
  #11 (permalink)  
Antiguo 23/03/2009, 11:44
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 7 meses
Puntos: 28
Respuesta: Problemas con el envio de datos

ok ya no me muestra el error... pero hagan la prueba refrescando y se repiten las datos se siguen ingresando si actualizo
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
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 11:05.