Foros del Web » Programando para Internet » PHP »

problemas con sesionstart()

Estas en el tema de problemas con sesionstart() en el foro de PHP en Foros del Web. Saludos Realice una aplicación que usa sesion start y funciona bien en mi maquina, pero a la hora de subirlo al servidor que tengo y ...
  #1 (permalink)  
Antiguo 09/06/2007, 12:49
 
Fecha de Ingreso: junio-2007
Mensajes: 56
Antigüedad: 16 años, 10 meses
Puntos: 0
problemas con sesionstart()

Saludos
Realice una aplicación que usa sesion start y funciona bien en mi maquina, pero a la hora de subirlo al servidor que tengo y probarlo de manera local, me manda el siguiente error: A session has already been start, ignoring session_start() in ....ruta in line 76
¿Alguien sabe porqué?
  #2 (permalink)  
Antiguo 09/06/2007, 13:27
Avatar de ZydRick  
Fecha de Ingreso: febrero-2005
Ubicación: Lima
Mensajes: 750
Antigüedad: 19 años, 2 meses
Puntos: 4
Re: problemas con sesionstart()

podrías poner el mensaje de error completo que te arroja? para saber dónde está tu falla.
  #3 (permalink)  
Antiguo 09/06/2007, 16:56
Avatar de eits  
Fecha de Ingreso: junio-2005
Ubicación: valladolid, yucatán
Mensajes: 1.655
Antigüedad: 18 años, 10 meses
Puntos: 88
Re: problemas con sesionstart()

el problema puede estar la forma en que inicializas el session_start() ya que este debe de estar al principio y sin nada que la anteceda, pero mejor es que pongas tu código para estar seguro.

saludos.
__________________
El amor es la locura mas lucida que tiene el hombre.- Andres Henestrosa
la tristeza no existe, solo es... la ausencia de la felicidad.
  #4 (permalink)  
Antiguo 11/06/2007, 06:09
 
Fecha de Ingreso: junio-2007
Mensajes: 56
Antigüedad: 16 años, 10 meses
Puntos: 0
Re: problemas con sesionstart()

Este es el error que me sale:
Notice: A session had already been started - ignoring session_start() in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 2
__________________________________________________ _______________
Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\plaincart\admin\library\functions. php:2) in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 18
__________________________________________________ _______________
y este es mi código:
__________________________________________________ _______________
<?php
session_start(); // incio de uso de sesiones.
?>

<?php

function checkUser()
{
$var=isset($_SESSION['plaincart_user_name']);
echo"$var";

if (!isset($_SESSION['plaincart_user_id'])) {
header('Location: ' . WEB_ROOT . 'admin/login.php');
exit;
}

if (isset($_GET['logout'])) {
doLogout();
}
}

function checkPriv($privNeces)
{
$priv=isset($_SESSION['variable']);
if (isset($_SESSION['variable']) != $privNeces) {
header('Location: ' . $_SESSION['login_return_url']);
exit;
}
}


function doLogin()
{
$errorMessage = '';

$userName = $_POST['txtUserName'];
$password = $_POST['txtPassword'];

if ($userName == '') {
$errorMessage = 'Introduce tu nombre de usuario';
} else if ($password == '') {
$errorMessage = 'Introduce tu password';
} else {
$sql = "SELECT user_id
FROM tbl_user
WHERE user_name = '$userName' AND user_password = PASSWORD('$password')";
$result = dbQuery($sql);
$sql = "SELECT privilegios
FROM tbl_user
WHERE user_name = '$userName' AND user_password = PASSWORD('$password')";
$result2 = dbQuery($sql);
if ((dbNumRows($result) == 1)&&(dbNumRows($result2) == 1)) {
$row = dbFetchAssoc($result);
$row2 = dbFetchAssoc($result2);
$_SESSION['plaincart_user_id'] = $row['user_id'];

//session_start();

$_SESSION['variable'] = $row2['privilegios'];
$_SESSION['Uname'] = $userName;
$sql = "UPDATE tbl_user
SET user_last_login = NOW()
WHERE user_id = '{$row['user_id']}'";
dbQuery($sql);


if (isset($_SESSION['login_return_url'])) {
header('Location: ' . $_SESSION['login_return_url']);
exit;
} else {
header('Location: index.php');
exit;
}
} else {
$errorMessage = 'Nombre de usuario o password incorrectos';
}

}

return $errorMessage;
}


function doLogout()
{
if (isset($_SESSION['plaincart_user_id'])) {
unset($_SESSION['plaincart_user_id']);
session_unregister('plaincart_user_id');
}
if (isset($_SESSION['variable'])) {
unset($_SESSION['variable']);
session_unregister('variable');
}

header('Location: login.php');
exit;
}


function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;

if ($parentId == 0) {
$categories[$id] = array('name' => $name, 'children' => array());
} else {
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}

$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];

$list .= "<optgroup label=\"$name\">";

foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}

$list .= ">{$child['name']}</option>\r\n";
}

$list .= "</optgroup>";
}

return $list;
}

function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;

if ($parentId == 0) {

$categories[$id] = array('name' => $name, 'children' => array());
} else {

$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}

$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];

$list .= "<option value=\"$key\"";
if ($key == $catId) {
$list.= " selected";
}

$list .= ">$name</option>\r\n";

foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}

$list .= ">&nbsp;&nbsp;{$child['name']}</option>\r\n";
}
}

return $list;
}

function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
$thumbnail = '';

if (file_exists($srcFile) && isset($destFile))
{
$size = getimagesize($srcFile);
$w = number_format($width, 0, ',', '');
$h = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

$thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality);
}

return basename($thumbnail);
}

function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
$tmpSrc = pathinfo(strtolower($srcFile));
$tmpDest = pathinfo(strtolower($destFile));
$size = getimagesize($srcFile);

if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
{
$destFile = substr_replace($destFile, 'jpg', -3);
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} elseif ($tmpDest['extension'] == "png") {
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} else {
return false;
}

switch($size[2])
{
case 1: //GIF
$src = imagecreatefromgif($srcFile);
break;
case 2: //JPEG
$src = imagecreatefromjpeg($srcFile);
break;
case 3: //PNG
$src = imagecreatefrompng($srcFile);
break;
default:
return false;
break;
}

imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

switch($size[2])
{
case 1:
case 2:
imagejpeg($dest,$destFile, $quality);
break;
case 3:
imagepng($dest,$destFile);
}
return $destFile;

}

function getPagingNav($sql, $pageNum, $rowsPerPage, $queryString = '')
{
$result = mysql_query($sql) or die('Error, query failed. ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

$maxPage = ceil($numrows/$rowsPerPage);

$self = $_SERVER['PHP_SELF'];

if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$self?page=$page{$queryString}\">[Prev]</a> ";

$first = " <a href=\"$self?page=1{$queryString}\">[First Page]</a> ";
}
else
{
$prev = ' [Prev] ';
$first = ' [First Page] ';
}

if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$self?page=$page{$queryString}\">[Next]</a> ";

$last = " <a href=\"$self?page=$maxPage{$queryString}{$queryStr ing}\">[Last Page]</a> ";
}
else
{
$next = ' [Next] ';
$last = ' [Last Page] ';
}

return $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
}
?>
  #5 (permalink)  
Antiguo 11/06/2007, 07:40
 
Fecha de Ingreso: junio-2007
Mensajes: 56
Antigüedad: 16 años, 10 meses
Puntos: 0
Re: problemas con sesionstart()

Mi versión de php en el servidor es: 5.2.2
Cambie el código al siguiente:
--------------------------------------------------------------------------
Me sale el siguiente error:
Notice: A session had already been started - ignoring session_start() in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 4

El nombre de la sesion es: PHPSESSID
Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\plaincart\admin\library\functions. php:4) in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 87
Si pongo el siguiente código:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>
<?php
//session_write_close();
//session_destroy();
session_start(); // incio de uso de sesiones.
echo "<br> El nombre de la sesion es: ".session_name();
$variable=$_SESSION['variable'];
?>
<?php
/*
Check if a session user id exist or not. If not set redirect
to login page. If the user session id exist and there's found
$_GET['logout'] in the query string logout the user
*/
function checkUser()
{
$var=isset($_SESSION['plaincart_user_name']);
echo"$var";
// if the session id is not set, redirect to login page
if (!isset($_SESSION['plaincart_user_id'])) {
header('Location: ' . WEB_ROOT . 'admin/login.php');
exit;
}

// the user want to logout
if (isset($_GET['logout'])) {
doLogout();
}
}

function checkPriv($privNeces)
{
$priv=isset($_SESSION['variable']);
// if the session id is not set, redirect to login page
if (isset($_SESSION['variable']) != $privNeces) {
header('Location: ' . $_SESSION['login_return_url']);
exit;
}
}

/*

*/
function doLogin()
{
// if we found an error save the error message in this variable
$errorMessage = '';

$userName = $_POST['txtUserName'];
$password = $_POST['txtPassword'];
// first, make sure the username & password are not empty
if ($userName == '') {
$errorMessage = 'Introduce tu nombre de usuario';
} else if ($password == '') {
$errorMessage = 'Introduce tu password';
} else {
// check the database and see if the username and password combo do match
$sql = "SELECT user_id
FROM tbl_user
WHERE user_name = '$userName' AND user_password = PASSWORD('$password')";
$result = dbQuery($sql);
$sql = "SELECT privilegios
FROM tbl_user
WHERE user_name = '$userName' AND user_password = PASSWORD('$password')";
$result2 = dbQuery($sql);
if ((dbNumRows($result) == 1)&&(dbNumRows($result2) == 1)) {
$row = dbFetchAssoc($result);
$row2 = dbFetchAssoc($result2);
$_SESSION['plaincart_user_id'] = $row['user_id'];

//session_start();

$_SESSION['variable'] = $row2['privilegios'];
$_SESSION['Uname'] = $userName;
// log the time when the user last login
$sql = "UPDATE tbl_user
SET user_last_login = NOW()
WHERE user_id = '{$row['user_id']}'";
dbQuery($sql);

// now that the user is verified we move on to the next page
// if the user had been in the admin pages before we move to
// the last page visited
if (isset($_SESSION['login_return_url'])) {
header('Location: ' . $_SESSION['login_return_url']);
exit;
} else {
header('Location: index.php');
exit;
}
} else {
$errorMessage = 'Nombre de usuario o password incorrectos';
}

}

return $errorMessage;
}

/*
Logout a user
*/
function doLogout()
{
if (isset($_SESSION['plaincart_user_id'])) {
unset($_SESSION['plaincart_user_id']);
session_unregister('plaincart_user_id');
}
if (isset($_SESSION['variable'])) {
unset($_SESSION['variable']);
session_unregister('variable');
}
session_write_close();
//session_destroy();
header('Location: login.php');
exit;
}


/*
Generate combo box options containing the categories we have.
if $catId is set then that category is selected
*/
function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;

if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];

$list .= "<optgroup label=\"$name\">";

foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}

$list .= ">{$child['name']}</option>\r\n";
}

$list .= "</optgroup>";
}

return $list;
}

/*
If you want to be able to add products to the first level category
replace the above function with the one below
*/
/*

function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;

if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
}
}

// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];

$list .= "<option value=\"$key\"";
if ($key == $catId) {
$list.= " selected";
}

$list .= ">$name</option>\r\n";

foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}

$list .= ">&nbsp;&nbsp;{$child['name']}</option>\r\n";
}
}

return $list;
}
*/

/*
Create a thumbnail of $srcFile and save it to $destFile.
The thumbnail will be $width pixels.
*/
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
$thumbnail = '';

if (file_exists($srcFile) && isset($destFile))
{
$size = getimagesize($srcFile);
$w = number_format($width, 0, ',', '');
$h = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

$thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality);
}

// return the thumbnail file name on sucess or blank on fail
return basename($thumbnail);
}

/*
Copy an image to a destination file. The destination
image size will be $w X $h pixels
*/
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
$tmpSrc = pathinfo(strtolower($srcFile));
$tmpDest = pathinfo(strtolower($destFile));
$size = getimagesize($srcFile);

if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
{
$destFile = substr_replace($destFile, 'jpg', -3);
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} elseif ($tmpDest['extension'] == "png") {
$dest = imagecreatetruecolor($w, $h);
imageantialias($dest, TRUE);
} else {
return false;
}

switch($size[2])
{
case 1: //GIF
$src = imagecreatefromgif($srcFile);
break;
case 2: //JPEG
$src = imagecreatefromjpeg($srcFile);
break;
case 3: //PNG
$src = imagecreatefrompng($srcFile);
break;
default:
return false;
break;
}

imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

switch($size[2])
{
case 1:
case 2:
imagejpeg($dest,$destFile, $quality);
break;
case 3:
imagepng($dest,$destFile);
}
return $destFile;

}

/*
Create the paging links
*/
function getPagingNav($sql, $pageNum, $rowsPerPage, $queryString = '')
{
$result = mysql_query($sql) or die('Error, query failed. ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

$self = $_SERVER['PHP_SELF'];

// creating 'previous' and 'next' link
// plus 'first page' and 'last page' link

// print 'previous' link only if we're not
// on page one
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$self?page=$page{$queryString}\">[Prev]</a> ";

$first = " <a href=\"$self?page=1{$queryString}\">[First Page]</a> ";
}
else
{
$prev = ' [Prev] '; // we're on page one, don't enable 'previous' link
$first = ' [First Page] '; // nor 'first page' link
}

// print 'next' link only if we're not
// on the last page
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$self?page=$page{$queryString}\">[Next]</a> ";

$last = " <a href=\"$self?page=$maxPage{$queryString}{$queryStr ing}\">[Last Page]</a> ";
}
else
{
$next = ' [Next] '; // we're on the last page, don't enable 'next' link
$last = ' [Last Page] '; // nor 'last page' link
}

// return the page navigation link
return $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
}
?>
  #6 (permalink)  
Antiguo 11/06/2007, 07:41
 
Fecha de Ingreso: junio-2007
Mensajes: 56
Antigüedad: 16 años, 10 meses
Puntos: 0
Re: problemas con sesionstart()

--------------------------------------------------------------------------
Si cambio las 1eras líneas y descomento el destroy_session();
<?php
//session_write_close();
session_destroy();
session_start(); // incio de uso de sesiones.
echo "<br> El nombre de la sesion es: ".session_name();
$variable=$_SESSION['variable'];
?>
Me sale el siguiente error:
El nombre de la sesion es: PHPSESSID
Notice: Undefined index: variable in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 6

Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\plaincart\admin\library\functions. php:5) in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 87
--------------------------------------------------------------------------
Y si comento el destroy y descomento el write_close:
<?php
session_write_close();
//session_destroy();
session_start(); // incio de uso de sesiones.
echo "<br> El nombre de la sesion es: ".session_name();
$variable=$_SESSION['variable'];
?>
El nombre de la sesion es: PHPSESSID
Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\plaincart\admin\library\functions. php:5) in D:\xampp\htdocs\plaincart\admin\library\functions. php on line 87
Ya no se que más hacer aquí
  #7 (permalink)  
Antiguo 11/06/2007, 08:04
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 sesionstart()

Tu problema es que estas llamando a session_start() en tu script functions.php, pero la estas llamando una vez mas porque en otro script (probablemente donde incluyes tu archivo) ya haz llamado a session_start(), esto te crea un E_NOTICE lo que envia salida al explorador, y te causa el problema de que ya no puedes enviar mas cabeceras porque ya haz enviado salida al explorador.

Por disenio se recomienda solo usar 1 session_start() en toda tu aplicacion para que asi tengas control donde y como se esta iniciando.

Saludos.
  #8 (permalink)  
Antiguo 11/06/2007, 10:02
 
Fecha de Ingreso: junio-2007
Mensajes: 56
Antigüedad: 16 años, 10 meses
Puntos: 0
Re: problemas con sesionstart()

ok muchas grax
Ya logré resolverlo
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 15:43.