Session start php ошибка

Здраствуйте! Начал изучать php, и вобщем не понимаю, почему код с session_start(); Выдает ошибку: Warning: session_start(): Cannot start session when headers already sent in W:domainsphp-learnscript.php on line 10

Вроде как эта команда создает сессию, но почему вобще появляется ошибка, и почему код работает без начала сессии.

Работает:

$_SESSION['text'] = $_REQUEST['text'];
        echo $_SESSION['text'];

Работает, но в первой строке ошибка:

session_start();
        $_SESSION['text'] = $_REQUEST['text'];
        echo $_SESSION['text'];

Весь код:

<?php
  session_start();
      $_SESSION['text'] = $_REQUEST['text'];
      echo $_SESSION['text'];
  ?>

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>PHP</title>
  </head>
  <body>

      <form action="" method="GET">
           <textarea name='text'></textarea>
  	       <input type="submit">
      </form>
      <br>

  </body>
</html>

По учебнику Трепачева кстати, да и везде стоит сначала session_start(), и это должно быть правильно. Вобщем, заранее спасибо

I can’t handle this error, please help me. It worked on my laptop but did not work on my desktop.

Why?

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at F:xampphtdocsetestindex.php:1) in F:xampphtdocsetestcommonheader.php on line 3

The code:

<?php
ob_start();
session_start();
include("constants.php");
include("includes.php");
?>

Thanks for your kindness!

Charles's user avatar

Charles

50.9k13 gold badges104 silver badges142 bronze badges

asked Mar 5, 2011 at 17:59

Freeman's user avatar

2

the error was at F:xampphtdocsetestcommonheader.php on line 3 but output was already started at F:xampphtdocsetestindex.php:1

I assume you posted the header.php, but your index.php either has whitespace before the
<?php include() or outputs something other than a header on the first line.

the error is caused by line one of index.php, whatever is there. I’d guess whitespace.

answered Mar 5, 2011 at 18:06

lunixbochs's user avatar

lunixbochslunixbochs

21.5k2 gold badges39 silver badges46 bronze badges

0

In general, when you see «headers already sent», it means that you are trying to do something that requires an HTTP header to be set, but you have already sent content to the client. When using HTTP, you have to send the headers, then the content comes after. If you’ve sent content, you’ve missed your opportunity to send headers.

answered Mar 5, 2011 at 18:04

Jim's user avatar

JimJim

72.8k14 gold badges101 silver badges106 bronze badges

0

Start the session on top of the file.

direct afer the php tag when you make an echo or send some header before you get this errormessage.

<?php
session_start();
ob_start();
include("constants.php");
include("includes.php");
?>

answered Mar 5, 2011 at 18:01

René Höhle's user avatar

René HöhleRené Höhle

26.6k22 gold badges73 silver badges82 bronze badges

3

Enable output buffering by configuration. This way it will start before anything else, so it certainly solves your problem. Although you should look at your code and find the cause of the present error, because it seems you do not fully understand your site yet.

After enabling output buffering by configuration, you no longer need to call ob_start() manually.

Create a file called .htaccess with this content:

php_flag output_buffering on

… or add this line to your php.ini:

output_buffering = On

answered Mar 5, 2011 at 18:10

vbence's user avatar

vbencevbence

20k9 gold badges68 silver badges117 bronze badges

2

use_only_cookies=0 to use_only_cookies=1 in php.ini file

I encountered the same problem in xampp 7.0.1 and this fixed it. Read it here.

Tunaki's user avatar

Tunaki

132k46 gold badges331 silver badges418 bronze badges

answered Jan 10, 2016 at 3:13

kenn's user avatar

kennkenn

111 silver badge5 bronze badges

Yes start the session on top of the file amd make sure you do not have a space before

<?php

Plus you can call session_start(); only one time

answered Mar 5, 2011 at 18:04

rtacconi's user avatar

rtacconirtacconi

14.2k20 gold badges66 silver badges84 bronze badges

session_start() must be called before there is ANY other output. The error is telling you that output started on index.php line 1. The call to session_start() must be placed before that.

answered Mar 5, 2011 at 18:11

Mark Eirich's user avatar

Mark EirichMark Eirich

9,9862 gold badges24 silver badges27 bronze badges

Put this code inside includes.php

ob_start();
session_start();

And remove the same code from every other page.
Also make sure that in your files there is no whitespace before the initial

(specifically you are getting the error because something is wrong on the first line of index.php not of header.php)

answered Mar 5, 2011 at 18:15

tacone's user avatar

taconetacone

11.4k8 gold badges43 silver badges60 bronze badges

I was getting this even when I had it at the top of the file.

Problem INVISIBLE UTF8 CHARACTER

Solution
Was to delete the file and make a new one starting with <?php and then copy everything after the php into the new one. (Don’t copy the beginning of the file).

answered Jul 4, 2019 at 3:25

Kevin Upton's user avatar

Kevin UptonKevin Upton

3,2462 gold badges21 silver badges24 bronze badges

(PHP 4, PHP 5, PHP 7, PHP 8)

session_startStart new or resume existing session

Description

session_start(array $options = []): bool

When session_start() is called or when a session auto starts,
PHP will call the open and read session save handlers. These will either be a built-in
save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be
custom handler as defined by session_set_save_handler().
The read callback will retrieve any existing session data (stored in a special serialized format)
and will be unserialized and used to automatically populate the $_SESSION superglobal when the
read callback returns the saved session data back to PHP session handling.

To use a named session, call
session_name() before calling
session_start().

When session.use_trans_sid
is enabled, the session_start() function will
register an internal output handler for URL rewriting.

If a user uses ob_gzhandler or similar with
ob_start(), the function order is important for
proper output. For example,
ob_gzhandler must be registered before starting the session.

Parameters

options

If provided, this is an associative array of options that will override
the currently set
session configuration directives.
The keys should not include the session. prefix.

In addition to the normal set of configuration directives, a
read_and_close option may also be provided. If set to
true, this will result in the session being closed immediately after
being read, thereby avoiding unnecessary locking if the session data
won’t be changed.

Return Values

This function returns true if a session was successfully started,
otherwise false.

Changelog

Version Description
7.1.0 session_start() now returns false and no longer
initializes $_SESSION when it failed to start the
session.

Examples

A basic session example

Example #1 page1.php


<?php
// page1.phpsession_start();

echo

'Welcome to page #1';$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

After viewing page1.php, the second page
page2.php will magically contain the session
data. Read the session reference
for information on propagating
session ids as it, for example, explains what the constant
SID is all about.

Example #2 page2.php


<?php
// page2.phpsession_start();

echo

'Welcome to page #2<br />';

echo

$_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

Providing options to session_start()

Example #3 Overriding the cookie lifetime


<?php
// This sends a persistent cookie that lasts a day.
session_start([
'cookie_lifetime' => 86400,
]);
?>

Example #4 Reading the session and closing it


<?php
// If we know we don't need to change anything in the
// session, we can just read and close rightaway to avoid
// locking the session file and blocking other pages
session_start([
'cookie_lifetime' => 86400,
'read_and_close' => true,
]);


Notes

Note:

To use cookie-based sessions, session_start()
must be called before outputting anything to the browser.

Note:

Use of zlib.output_compression
is recommended instead of ob_gzhandler()

Note:

This function sends out several HTTP headers depending on the
configuration. See session_cache_limiter() to
customize these headers.

See Also

  • $_SESSION
  • The session.auto_start
    configuration directive
  • session_id() — Get and/or set the current session id

ohcc at 163 dot com

9 years ago


The constant SID would always be '' (an empty string) if directive session.use_trans_sid in php ini file is set to 0.

So remember to set session.use_trans_sid to 1 and restart your server before you use SID in your php script.


linblow at hotmail dot fr

12 years ago


If you want to handle sessions with a class, I wrote this little class:

<?php/*
    Use the static method getInstance to get the object.
*/
class Session
{
    const
SESSION_STARTED = TRUE;
    const
SESSION_NOT_STARTED = FALSE;// The state of the session
   
private $sessionState = self::SESSION_NOT_STARTED;// THE only instance of the class
   
private static $instance;

            private function

__construct() {}/**
    *    Returns THE instance of 'Session'.
    *    The session is automatically initialized if it wasn't.
    *   
    *    @return    object
    **/
public static function getInstance()
    {
        if ( !isset(
self::$instance))
        {
           
self::$instance = new self;
        }
self::$instance->startSession();

                return

self::$instance;
    }
/**
    *    (Re)starts the session.
    *   
    *    @return    bool    TRUE if the session has been initialized, else FALSE.
    **/
public function startSession()
    {
        if (
$this->sessionState == self::SESSION_NOT_STARTED )
        {
           
$this->sessionState = session_start();
        }

                return

$this->sessionState;
    }
/**
    *    Stores datas in the session.
    *    Example: $instance->foo = 'bar';
    *   
    *    @param    name    Name of the datas.
    *    @param    value    Your datas.
    *    @return    void
    **/
public function __set( $name , $value )
    {
       
$_SESSION[$name] = $value;
    }
/**
    *    Gets datas from the session.
    *    Example: echo $instance->foo;
    *   
    *    @param    name    Name of the datas to get.
    *    @return    mixed    Datas stored in session.
    **/
public function __get( $name )
    {
        if ( isset(
$_SESSION[$name]))
        {
            return
$_SESSION[$name];
        }
    }

            public function

__isset( $name )
    {
        return isset(
$_SESSION[$name]);
    }

            public function

__unset( $name )
    {
        unset(
$_SESSION[$name] );
    }
/**
    *    Destroys the current session.
    *   
    *    @return    bool    TRUE is session has been deleted, else FALSE.
    **/
public function destroy()
    {
        if (
$this->sessionState == self::SESSION_STARTED )
        {
           
$this->sessionState = !session_destroy();
            unset(
$_SESSION );

                        return !

$this->sessionState;
        }

                return

FALSE;
    }
}
/*
    Examples:
*/

// We get the instance

$data = Session::getInstance();// Let's store datas in the session
$data->nickname = 'Someone';
$data->age = 18;// Let's display datas
printf( '<p>My name is %s and I'm %d years old.</p>' , $data->nickname , $data->age );/*
    It will display:

        Array
    (
        [nickname] => Someone
        [age] => 18
    )
*/

printf( '<pre>%s</pre>' , print_r( $_SESSION , TRUE ));// TRUE
var_dump( isset( $data->nickname ));// We destroy the session
$data->destroy();// FALSE
var_dump( isset( $data->nickname ));?>

I prefer using this class instead of using directly the array $_SESSION.


marco dot agnoli at me dot com

5 years ago


I recently made an interesting observation:

It seems that `session_start()` can return `true` even if the session was not properly created. In my case, the disk storage was full and so the session data could not be written to disk. I had some logic that resulted in an infinite loop when the session was not written to disk.

To check if the session really was saved to disk I used:

```
<?phpfunction safe_session_start() {
   
# Attempt to start a session
   
if (!@session_start()) return false;#
    # Check if we need to perform
    # the write test.
    #
   
if (!isset($_SESSION['__validated'])) {
       
$_SESSION['__validated'] = 1;# Attempt to write session to disk
       
@session_write_close();# Unset the variable from memory.
        # This step may be unnecessary
       
unset($_SESSION['__validated']);# Re-start session
       
@session_start();# Check if variable value is retained
       
if (!isset($_SESSION['__validated'])) {
           
# Session was not written to disk
           
return false;
        }
    }

    return

true;
}

if (!

safe_session_start()) {
   
# Sessions are probably not written to disk...
    # Handle error accordingly.
}?>
```

Took me quite a while to figure this out.

Maybe it helps someone!


bachtel at [googles email service]dotcom

6 years ago


If you are using a custom session handler via session_set_save_handler() then calling session_start() in PHP 7.1 you might see an error like this:
session_start(): Failed to read session data: user (path: /var/lib/php/session) in ...

As of this writing, it seems to be happening in PHP 7.1, and things look OK in PHP7.0.

It is also hard to track down because if a session already exists for this id (maybe created by an earlier version of PHP), it will not trigger this issue because the $session_data will not be null.

The fix is simple... you just need to check for 'null' during your read function:

<?phpfunction read($id)
{
 
//... pull the data out of the DB, off the disk, memcache, etc
 
$session_data = getSessionDataFromSomewhere($id);//check to see if $session_data is null before returning (CRITICAL)
 
if(is_null($session_data))
  {
   
$session_data = ''//use empty string instead of null!
 
}

  return

$session_data;
}
?>


aaronw at catalyst dot net dot nz

8 years ago


As others have noted, PHP's session handler is blocking. When one of your scripts calls session_start(), any other script that also calls session_start() with the same session ID will sleep until the first script closes the session.

A common workaround to this is call session_start() and session_write_close() each time you want to update the session.

The problem with this, is that each time you call session_start(), PHP prints a duplicate copy of the session cookie to the HTTP response header. Do this enough times (as you might do in a long-running script), and the response header can get so large that it causes web servers & browsers to crash or reject your response as malformed.

This error has been reported to PHP HQ, but they've marked it "Won't fix" because they say you're not supposed to open and close the session during a single script like this. https://bugs.php.net/bug.php?id=31455

As a workaround, I've written a function that uses headers_list() and header_remove() to clear out the duplicate cookies. It's interesting to note that even on requests when PHP sends duplicate session cookies, headers_list() still only lists one copy of the session cookie. Nonetheless, calling header_remove() removes all the duplicate copies.

<?php
/**
* Every time you call session_start(), PHP adds another
* identical session cookie to the response header. Do this
* enough times, and your response header becomes big enough
* to choke the web server.
*
* This method clears out the duplicate session cookies. You can
* call it after each time you've called session_start(), or call it
* just before you send your headers.
*/
function clear_duplicate_cookies() {
   
// If headers have already been sent, there's nothing we can do
   
if (headers_sent()) {
        return;
    }
$cookies = array();
    foreach (
headers_list() as $header) {
       
// Identify cookie headers
       
if (strpos($header, 'Set-Cookie:') === 0) {
           
$cookies[] = $header;
        }
    }
   
// Removes all cookie headers, including duplicates
   
header_remove('Set-Cookie');// Restore one copy of each cookie
   
foreach(array_unique($cookies) as $cookie) {
       
header($cookie, false);
    }
}
?>


emre@yazici

13 years ago


PHP Manual specifically denotes this common mistake:

Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

See session_id() manual page for more details.


dave1010 at gmail dot com

12 years ago


PHP locks the session file until it is closed. If you have 2 scripts using the same session (i.e. from the same user) then the 2nd script will not finish its call to session_start() until the first script finishes execution.

If you have scripts that run for more than a second and users may be making more than 1 request at a time then it is worth calling session_write_close() as soon as you've finished writing session data.

<?php
// a lock is places on the session, so other scripts will have to wait
session_start();// do all your writing to $_SESSION
$_SESSION['a'] = 1;// $_SESSION can still be read, but writing will not update the session.
// the lock is removed and other scripts can now read the session
session_write_close();do_something_slow();
?>

Found this out from http://konrness.com/php5/how-to-prevent-blocking-php-requests/


elitescripts2000 at yahoo dot com

9 years ago


3 easy but vital things about Sessions in AJAX Apps.

<?php
// session start

//  It is VERY important to include a Period if using
// a whole domain.  (.yourdomain.com)
// It is VERY important to set the root path your session will always
// operate in... (/members) will ensure sessions will NOT be interfered
// with a session with a path of say (/admin) ... so you can log in
// as /admin and as /members... NEVER do unset($_SESSION)
// $_SESSION=array(); is preferred, session_unset();  session_destroy();

session_set_cookie_params(0, '/members', '.yourdomain.com', 0, 1);
session_start();
$_SESSION = array();
session_unset();
session_destroy();session_set_cookie_params(0, '/members', '.yourdomain.com', 0, 1);
session_start();$_SESSION['whatever'] = 'youwhat';// session destroying

// To be safe, clear out your $_SESSION array
// Next, what most people do NOT do is delete the session cookie!
// It is easy to delete a cookie by expiring it long before the current time.
// The ONLY WAY to delete a cookie, is to make sure ALL parameters match the
// cookie to be deleted...which is easy to get those params with
// session_get_cookie_params()...
// FInally, use  session_unset(); and session_destroy(); in this order to ensure
// Chrome, IE, Firefox and others, are properly destroying the session.

$_SESSION = array();
if (
ini_get('session.use_cookies'))
{
   
$p = session_get_cookie_params();
   
setcookie(session_name(), '', time() - 31536000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
session_unset();
session_destroy();// AJAX and SESSIONS.
// Example... you start a session based PHP page, which then calls an Ajax (XMLHTTP) authenticated
// using the SAME SESSION to Poll and output the data, for example.  But, you notice when you
// try to start the Polling AJAX call always HANGS and seems to hang at the session_start().
// This is because the session is opened in the first page, calls the AJAX polling example, and
// tries to open the same session (for authentication) and do the AJAX call, you MUST call
// session_write_close(); meaning you are done writing to the $_SESSION variable, which really
// represents a file that must be CLOSED with session_write_close();....
// THAN you can call your AJAX Polling code to reopen the same session and do its polling...
// Normally, the $_SESSION is closed automatically when the script is closed or finished executing
// So, if you need to keep a PHP page running after opening a SESSION, simply close it when finished
// writing to $_SESSION so the AJAX polling page can authenticate and use the same session in a
// seperate web page...
session_write_close();?>

Hope this helps someone with their sessions...
Thanks.


someOne_01 at somewhere dot com

10 years ago


When you have an import script that takes long to execute, the browser seem to lock up and you cannot access the website anymore. this is because a request is reading and locking the session file to prevent corruption.

you can either

- use a different session handler with session_set_save_handler()

- use session_write_close() in the import script as soon you don't need session anymore (best moment is just before the long during part takes place), you can session_start when ever you want and as many times you like if your import script requires session variables changed.

example

<?php

session_start
(); //initiate / open session

$_SESSION['count'] = 0; // store something in the session

session_write_close(); //now close it,

# from here every other script can be run (and makes it seem like multitasking)

for($i=0; $i<=100; $i++){ //do 100 cycles

   
session_start(); //open the session again for editing a variable

   
$_SESSION['count'] += 1; //change variable

   
session_write_close(); //now close the session again!

   
sleep(2); //every cycle sleep two seconds, or do a heavy task

}

?>


Anonymous

2 years ago


Be careful with the 'read_and_close' option. It doesn't update the session file's last modification time unlike the default PHP behaviour when you don't close the session (or when you use session_write_close explicitly).
Old session files (for me, older than 24 minutes) will be occasionally cleared by the garbage collector (for me every 09 and 39 minute of every hour).
So a session can disappear even if the page regularly sends requests to the server that only reads and closes the session.

jamestrowbridge at gmail dot com

13 years ago


Unfortunately, after pulling my hair out trying to figure out why my application was working fine in every browser other than IE ( Internet Explorer) (Opera, Chrome, Firefox, Safari are what I've tested this in) - when using a DNS CNAME record (like a vanity name that is different from the DNS A record, which is the hostname of the server) sessions do not work correctly.

If you store a session var while on the CNAME:

vanity.example.com and the hostname of the server is hosname.example.com

Then try to call the variable from a different page, it will not find it because of the CNAME (I guess it store the variable under the hostname, then when trying to read it it's still looking under the CNAME) the same application works fine when accessing it under the hostname directly.  Keep in mind that I was testing this on an internal network.


ben dot morin at spaboom dot com

16 years ago


James at skinsupport dot com raises a good point (warning) about additional requests from the browser.  The request for favicon.ico, depending on how it is handled, can have unintended results on your sessions. 

For example, suppose you have ErrorDocument 404 /signin.php, no favicon.ico file and all pages in your site where the user signs in are also redirected to /signin.php if they're not already signed in. 

If signin.php does any clean up or reassigning of session_id (as all good signin.php pages should) then the additional request from the browser for favicon.ico could potentially corrupt the session as set by the actual request. 

Kudos to James for pointing it out and shame on me for skimming past it and not seeing how it applied to my problem.  Thanks too to the Firefox Live HTTP Headers extension for showing the additional request. 

Don't waste days or even hours on this if your session cookies are not being sent or if the session data isn't what you expect it to be.  At a minimum, eliminate this case and see if any additional requests could be at fault.


James

16 years ago


To avoid the notice commited by PHP since 4.3.3 when you start a session twice, check session_id() first:

if (session_id() == "")
  session_start();


hu60 dot cn at gmail dot com

3 years ago


The following code shows how the PHP session works. The function my_session_start() does almost the same thing as session_start().

<?php
error_reporting
(E_ALL);
ini_set('display_errors', true);
ini_set('session.save_path', __DIR__);my_session_start();

echo

'<p>session id: '.my_session_id().'</p>';

echo

'<code><pre>';
var_dump($_SESSION);
echo
'</pre></code>';$now = date('H:i:s');
if (isset(
$_SESSION['last_visit_time'])) {
  echo
'<p>Last Visit Time: '.$_SESSION['last_visit_time'].'</p>';
}
echo
'<p>Current Time: '.$now.'</p>';$_SESSION['last_visit_time'] = $now;

function

my_session_start() {
  global
$phpsessid, $sessfile;

  if (!isset(

$_COOKIE['PHPSESSID']) || empty($_COOKIE['PHPSESSID'])) {
   
$phpsessid = my_base32_encode(my_random_bytes(16));
   
setcookie('PHPSESSID', $phpsessid, ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
  } else {
   
$phpsessid = substr(preg_replace('/[^a-z0-9]/', '', $_COOKIE['PHPSESSID']), 0, 26);
  }
$sessfile = ini_get('session.save_path').'/sess_'.$phpsessid;
  if (
is_file($sessfile)) {
   
$_SESSION = unserialize(file_get_contents($sessfile));
  } else {
   
$_SESSION = array();
  }
 
register_shutdown_function('my_session_save');
}

function

my_session_save() {
  global
$sessfile;file_put_contents($sessfile, serialize($_SESSION));
}

function

my_session_id() {
  global
$phpsessid;
  return
$phpsessid;
}

function

my_random_bytes($length) {
  if (
function_exists('random_bytes')) {
      return
random_bytes($length);
  }
 
$randomString = '';
  for (
$i = 0; $i < $length; $i++) {
     
$randomString .= chr(rand(0, 255));
  }
  return
$randomString;
}

function

my_base32_encode($input) {
 
$BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
 
$output = '';
 
$v = 0;
 
$vbits = 0;
  for (
$i = 0, $j = strlen($input); $i < $j; $i++) {
   
$v <<= 8;
   
$v += ord($input[$i]);
   
$vbits += 8;
    while (
$vbits >= 5) {
     
$vbits -= 5;
     
$output .= $BASE32_ALPHABET[$v >> $vbits];
     
$v &= ((1 << $vbits) - 1);
    }
  }
  if (
$vbits > 0) {
   
$v <<= (5 - $vbits);
   
$output .= $BASE32_ALPHABET[$v];
  }
  return
$output;
}


schlang

13 years ago


if you store your sessions in a database, always ensure that the type of the database column is large enough for your session values

jorrizza at gmail dot com

18 years ago


If you open a popup window (please no commercial ones!) with javascript window.open it might happen IE blocks the session cookie.
A simple fix for that is opening the new window with the session ID in a GET value. Note I don't use SID for this, because it will not allways be available.

----page.php----
//you must have a session active here
window.open('popup.php?sid=<?php echo session_id(); ?>', '700x500', 'toolbar=no, status=no, scrollbars=yes, location=no, menubar=no, directories=no, width=700, height=500');

----popup.php----
<?php
session_id
(strip_tags($_GET['sid']));
session_start();
//and go on with your session vars
?>


andy_isherwood at hotmail dot com

14 years ago


A session created with session_start will only be available to pages within the directory tree of the page that first created it.

i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.


bwz

3 months ago


Be warned of another issue with blocking sessions: if you want to call an external program (or use an external service) that needs to access your website using the same session.

For example I am printing a page as a PDF. I can just save the web page as a HTML file. But the images in the HTML are also private and require the current user session to be seen.

What will happen is that this program might hang indefinitely (or timeout) as session_start waits for the parent PHP process to release the lock. And session_start doesn't obey max_execution_time (as documented in this bug: https://bugs.php.net/bug.php?id=72345 ), so this will effectively kill the server after a few requests, as each one will be hanging forever

It's the same if you use an external HTTP service:

<?php
$pdf
= file_get_contents('http://pdf.website.tld/?url=http://website.tld/print.php');
?>

The service will wait for the website host to release the lock, but it can't as it is waiting for the PDF service to finish...

The nice solution is to release the lock immediately by calling session_write_close after session_start, and when you need to write to the session you do the same again, but as noted it has its own issues. Using a custom session handler is probably the best solution.


polygon dot co dot in at gmail dot com

1 year ago


Websites are prone to Session Attack where its proper usage is not done.

There are tools like "Apache Benchmark" (ab) and many others which can hit the website with load for load / performance testing.

Code below starts the session for every request.

<?php
session_start
();$username = $_POST['username'];
$password = $_POST['password'];

if(

isValidUser($username, $password)) {Suserdetails = getUserDetails($username);$_SESSION['user_id']    = Suserdetails['user_id'];
   
$_SESSION['username']    = Suserdetails['username'];
   
$_SESSION['firstname']    = Suserdetails['firstname'];header('Location: dashboard.php');
}
?>

This generates session file for every request irrespective of PHPSESSID cookie value when I use tools like ab, there by creating inode issue.

One should start the session after properly authenticating.

<?php

$username

= $_POST['username'];
$password = $_POST['password'];

if(

isValidUser($username, $password)) {Suserdetails = getUserDetails($username);session_start();$_SESSION['user_id']    = Suserdetails['user_id'];
   
$_SESSION['username']    = Suserdetails['username'];
   
$_SESSION['firstname']    = Suserdetails['firstname'];header('Location: dashboard.php');
}
?>

Scripts other then login first validates session which requires session.

<?phpif(session_status()!=PHP_SESSION_NONEheader('Location: login.php');session_start();

    if(!isset(

$_SESSION['user_id'])) header('Location: login.php');code logic below....
}
?>

This example is for file based session.
For other modes of session check function session_set_save_handler.


axew3 at axew3 dot com

5 years ago


I need, with easy, count how many times the page reload over the site, may to add a warning popup, while the counter is 0 ...
session_start();
if(isset($_SESSION['count'])){
$count = $_SESSION['count'];
$count++;
$count = $_SESSION['count'] = $count;
} else {
    $count = $_SESSION['count'] = 0;
}
echo $count;

//session_destroy();


chris at ocproducts dot com

6 years ago


Initiating a session may overwrite your own custom cache control header, which may break clicking back to get back to a prior post request (on Chrome at least).
On my system it was setting 'no-store', which is much more severe than 'no-cache' and what was breaking the back-button.

If you are controlling your own cache headers carefully you need to call:
session_cache_limiter('');

...to stop it changing your cache control headers.


fabmlk at hotmail dot com

7 years ago


If you ever need to open multiple distinct sessions in the same script and still let PHP generate session ids for you, here is a simple function I came up with (PHP default session handler is assumed):

<?php
/**
  * Switch to or transparently create session with name $name.
  * It can easily be expanded to manage different sessions lifetime.
  */
function session_switch($name = "PHPSESSID") {
        static
$created_sessions = array();

        if (

session_id() != '') { // if a session is currently opened, close it
           
session_write_close();
        }
       
session_name($name);
        if (isset(
$_COOKIE[$name])) {    // if a specific session already exists, merge with $created_sessions
           
$created_sessions[$name] = $_COOKIE[$name];
        }
        if (isset(
$created_sessions[$name])) { // if existing session, impersonate it
           
session_id($created_sessions[$name]);
           
session_start();
        } else {
// create new session
           
session_start();
           
$_SESSION = array(); // empty content before duplicating session file
                        // duplicate last session file with new id and current $_SESSION content
                        // If this is the first created session, there is nothing to duplicate from and passing true as argument will take care of "creating" only one session file
           
session_regenerate_id(empty($created_sessions));
           
$created_sessions[$name] = session_id();
        }
}
session_switch("SESSION1");
$_SESSION["key"] = "value1"; // specific to session 1
session_switch("SESSION2");
$_SESSION["key"] = "value2"; // specific to session 2
session_switch("SESSION1");
// back to session 1
// ...
?>

When using this function, session_start() should not be called on its own anymore (can be replaced with a call to session_switch() without argument).
Also remember that session_start() sets a Set-Cookie HTTP header on each call, so if you echo in-between sessions, wrap with ouput buffering.

Note: it's probably rarely a good idea to handle multiple sessions so think again if you think you have a good use for it.
Personally it played its role for some quick patching of legacy code I had to maintain.


ilnomedellaccount at gmail dot com

9 years ago


A note about session_start(), custom handlers and database foreign key constraints, which I think may be of some use...

We know that if we want our sessions into a database table (rather than the default storage), we can refer to session_set_save_handler(...) to get them there. Note that session_set_save_handler must (obviously) be called before session_start(), but let me get to the point...

Upon calling session_start() the "first time", when the session does not already exist, php will spawn a new session but will not call the write handler until script execution finishes.

Thus, the session at this point exists in the server process memory, but won't be visible as a row in the DB before the script ends.

This seems reasonable, because this avoids some unnecessary database access and resource usage before we even populate our session with meaningfull and definitive data, but this also has side-effects.

In my case, the script called session_start() to make sure a session was initiated, then used session_id() to populate another table in the DB, which had foreign_key constraint to the "sessions" table. This failed because no session was in the db at that point, yet!

I know I could simply force the creation of the row in the DB by manually calling the write handler after session_start(), when necessary, but I am not sure if this is the best possible approach.

As soon as I find an "elegant" solution, or a completely different approach, I will post some working sample code.

In the meanwhile... have fun!


info at nospam dot mmfilm dot sk

13 years ago


For those of you running in problems with UTF-8 encoded files:

I was getting an error because of the BOM, although i set Dreamweaver to "save as" the without the BOM. It appears that DW will not change this setting in already existing files. After creating a new file withou the BOM, everything worked well.

I also recommend http://people.w3.org/rishida/utils/bomtester/index.php - a utility that remote checks for the presence of BOM.


Charlie at NOSPAM dot example dot com

13 years ago


Be warned that depending on end of script to close the session will effectively serialize concurrent session requests.   Concurrent background "data retrieval" (e.g. applications such as AJAX or amfphp/Flex) expecting to retrieve data in parallel can fall into this trap easily.

Holding the session_write_close until after an expensive operation is likewise problematic.

To minimize effects, call session_write_close (aka session_commit) as early as practical (e.g. without introducing race conditions) or otherwise avoid the serialization bottleneck.


tom at bitworks dot de

5 years ago


A simple session_start() will not be sufficiant to kepp you Session alive.
Due to the filesystems mounting parameters, atime will normally not be updated. Instead of atime, mtime will be delivered.

This behavior may cause an early session death and your users my be kicked of your login system. 

To keep the session alive it will be necessary to write something into the sessionfile at each request, e. g. a simple

"$_SESSION['time'] = time();"

That would keep your session alive, even if the client in reality is only clicking around the site.


axew3 at axew3 dot com

5 years ago


I just need with easy, count how many times the page reload over the site, may to add a warning popup, while the counter is 0:

session_start();
if(isset($_SESSION['count'])){
$count = $_SESSION['count'];
$count++;
$count = $_SESSION['count'] = $count;
} else {
    $count = $_SESSION['count'] = 0;
}
echo $count;

//session_destroy();


sanjuro at 1up-games dot com

11 years ago


The problem with SID is that if on occasions you don't start a session, instead of outputting an empty string for transparent integration it will return the regular undefined constant notice. So you might want to test the constant with defined() beforehand.

info.at.merchandisinginteractive.sk

13 years ago


A handy script that checks fot the presence of uft-8 byte order mark (BOM) in all files in all directories starting on current dir. Combined from the work of other people here...

<?php

function fopen_utf8 ($filename) {

   
$file = @fopen($filename, "r");

   
$bom = fread($file, 3);

    if (
$bom != b"xEFxBBxBF")

    {

        return
false;

    }

    else

    {

        return
true;

    }

}

function

file_array($path, $exclude = ".|..|design", $recursive = true) {

   
$path = rtrim($path, "/") . "/";

   
$folder_handle = opendir($path);

   
$exclude_array = explode("|", $exclude);

   
$result = array();

    while(
false !== ($filename = readdir($folder_handle))) {

        if(!
in_array(strtolower($filename), $exclude_array)) {

            if(
is_dir($path . $filename . "/")) {

                               
// Need to include full "path" or it's an infinite loop

               
if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);

            } else {

                if (
fopen_utf8($path . $filename) )

                {

                   
//$result[] = $filename;

                   
echo ($path . $filename . "<br>");

                }

            }

        }

    }

    return
$result;

}
$files = file_array(".");

?>


m dot kuiphuis at hccnet dot nl

19 years ago


[Editors Note: For more information about this

http://www.zvon.org/tmRFC/RFC882/Output/chapter5.html ]

I use name-based virtual hosting on Linux with Apache and PHP 4.3.2.

Every time when I refreshed (by pressing F5 in Internet Explorer) I noticed that I got a new session_id. Simultaneously browsing the same site with Netscape didn't give me that problem. First I thought this was some PHP issue (before I tested it with Netscape), but after searching a lot on the internet I found the problem.

Since I was using name based virtual hosting for my testserver and we have different webshops for different customers I used the syntax webshop_customername.servername.nl as the domain-name.

The _ in the domain name seemed to be the problem. Internet Explorer just denies setting the cookie on the client when there is a special character (like an _ ) in the domain name. For more information regarding this issue: http://support.microsoft.com/default.aspx?scid=kb;EN-US;316112

Stupidly enough, this information was related to asp (yuk :o)


anon at ymous dot com

12 years ago


I am trying to get a session created by a browser call to be used by a command line cli->curl php call (in this case, both calls to the same server and php.ini), for a set of flexible media import routines,

but the cli->curl call always starts a new session despite me putting PHPSESSID=validID as the first parameter for the url called by curl.

I was able to fix it by calling session_id($_GET['PHPSESSID']) before calling session_start() in the script called via curl.


dstuff at brainsware dot org

13 years ago


It seems like spaces in the name don't work either - got a new session id generated each time

leandroico—at—gmail—dot—com

16 years ago


TAGS: session_start headers output errors include_once require_once php tag new line

Errors with output headers related to *session_start()* being called inside include files.

If you are starting your session inside an include file you must be aware of the presence of undesired characters after php end tag.

Let's take an example:
> page.php
<?php
include_once 'i_have_php_end_tag.inc.php';
include_once
'init_session.inc.php';

echo

"Damn! Why I'm having these output header errors?";
?>

> i_have_php_end_tag.inc.php
<?php
$_JUST_A_GLOBAL_VAR
= 'Yes, a global var, indeed';
?>

> init_session.inc.php
<?php
session_start
();
$_SESSION['blabla'] = 123;
?>

With all this stuff we will get an error, something like:
"... Cannot send session cache limiter - headers already sent (output started at ...", right?

To solve this problem we have to ignore all output sent by include files. To ensure that we need to use the couple of functions: *ob_start()* and *ob_end_clean()* to suppress the output. So, all we have to do is changing the *page.php* to this:

<?php
ob_start
();
include_once
'i_have_php_end_tag.inc.php';
include_once
'init_session.inc.php';
ob_end_clean();

echo

"Woo hoo! All right! Die you undesired outputs!!!";
?>


jphansen at uga dot edu

15 years ago


I just wrote that session_start() will erase your querystring variable(s) once called. I want to clarify that it will only do this if a variable by the same subscript is defined in $_SESSION[].

erm[at]the[dash]erm[dot]com

18 years ago


If you are insane like me, and want to start a session from the cli so other scripts can access the same information.

I don't know how reliable this is.  The most obvious use I can see is setting pids.

// temp.php

#!/usr/bin/php -q
<?php

session_id

("temp");
session_start();

if (

$_SESSION) {
   
print_r ($_SESSION);
}
$_SESSION['test'] = "this is a test if sessions are usable inside scripts";?>

// Temp 2

#!/usr/bin/php -q
<?php

session_id

("temp");
session_start();print_r ($_SESSION);?>


james at skinsupport dot com

17 years ago


One thing of note that caused me three days of trouble:

It's important to note that Firefox (for one) makes two calls to the server automatically.  One for the page, and one for favicon.ico.

If you are setting session variables (as I was) to certain values when a page exists, and other values when pages don't exist, the values for non-existent pages will overwrite the values for existing pages if favicon.ico doesn't exist.

I doubt many of you are doing this, but if you are, this is a consideration you need to address or you'll be bald over the course of a three day period!


ivijan dot stefan at gmail dot com

6 years ago


How to fix session_start error?

Sometimes when you made plugins, addons or some components in projects you need to check if session is started and if is not, you need to start it with no session_start() errors.

Here is my tested solution what currently work on +9000 domains and in one my plugin but also in some custom works.

<?php
if (strnatcmp(phpversion(),'5.4.0') >= 0)
{
    if (
session_status() == PHP_SESSION_NONE) {
       
session_start();
    }
}
else
{
    if(
session_id() == '') {
       
session_start();
    }
}
?>

Feel free to use it and don't worry, be happy. ;)


hbertini at sapo dot pt

18 years ago


workaround when using session variables in a .php file referred by a frame (.html, or other file type) at a different server than the one serving the .php:

Under these conditions IE6 or later silently refuses the session cookie that is attempted to create (either implicitly or explicitly by invoquing session_start()).

As a consequence, your session variable will return an empty value.

According to MS kb, the workaround is to add a header that says your remote .php page will not abuse from the fact that permission has been granted.

Place this header on the .php file that will create/update the session variables you want:

<?php header('P3P: CP="CAO PSA OUR"'); ?>

Regards,
Hugo


Nathan

4 years ago


Btw you can use:

if (!isset($_SESSION)) {
// We love every user
session_start();
// Then refresh for changes to take affect
header("location: ../../");
} elseif ($_SESSION["user] == "123ABC - abcmouse.com") {
/* We don't like this user, so let's kick them out of
the session */
session_destroy();
// Then refresh for changes to take affect
header("location: ../../");
}


This guide will walk you through the process of resolving the common PHP error «Cannot send session cache limiter — headers already sent». This error occurs when your PHP script attempts to start a session after the HTTP headers have already been sent to the browser, causing issues with session management. We will cover the reasons for this error and provide step-by-step solutions to fix it.

Table of Contents

  1. Understanding the Error
  2. Identifying the Causes
  3. Step-by-Step Solutions
  • Fixing Whitespace and BOM issues
  • Moving Session_Start()
  • Using Output Buffering
  1. FAQs
  2. Related Links

Understanding the Error

The «Cannot send session cache limiter — headers already sent» error typically occurs when your PHP script attempts to start a session using session_start() after the HTTP headers have already been sent to the browser. Once the headers have been sent, you can no longer modify them, which is necessary for managing sessions.

Identifying the Causes

The most common causes of this error are:

  1. Whitespace or any output before the session_start() function call.
  2. The Byte Order Mark (BOM) included in the file encoding.
  3. The session_start() function is called after the HTML, or any other output has been sent to the browser.

Step-by-Step Solutions

Fixing Whitespace and BOM issues

  1. Open your PHP script in a text editor.
  2. Ensure there is no whitespace or any other output before the opening <?php tag.
  3. Save the file with UTF-8 encoding without BOM. In most text editors, you can find this option in the «Save As» dialog box.

Moving Session_Start()

  1. Locate the session_start() function in your PHP script.
  2. Move the session_start() function to the beginning of your script, before any output (including HTML, echo statements, or print statements) is sent to the browser.
  3. Save the changes and test your script.

Using Output Buffering

  1. At the beginning of your PHP script, add the following line to enable output buffering:
<?php ob_start(); ?>
  1. At the end of your PHP script, add the following line to flush the output buffer:
<?php ob_end_flush(); ?>
  1. Save the changes and test your script.

FAQs

Q: What is the session cache limiter?

A: The session cache limiter is a configuration setting that controls the caching behavior of session data. It can be set to various values, such as «nocache», «public», «private», or «private_no_expire», depending on your desired caching behavior.

Q: Can I use output buffering in all my PHP scripts?

A: Yes, you can use output buffering in all your PHP scripts. However, it is not always necessary and can sometimes cause performance issues if not used properly.

Q: What is the Byte Order Mark (BOM)?

A: The Byte Order Mark (BOM) is a Unicode character used to indicate the byte order of a text file. It is sometimes included in the file encoding and can cause issues with PHP scripts.

Q: Can I use ini_set() to modify the session.cache_limiter setting?

A: Yes, you can use the ini_set() function to modify the session.cache_limiter setting at runtime. For example, you can use the following code to disable caching:

<?php ini_set('session.cache_limiter', 'nocache'); ?>

Q: Why is it important to start the session before sending any output to the browser?

A: Starting the session before sending any output to the browser is important because it allows PHP to modify the HTTP headers, which are necessary for managing sessions. Once the headers have been sent, you can no longer modify them, causing issues with session management.

  • PHP: session_start() — Manual
  • PHP: Output Control Functions — Manual
  • PHP: Byte Order Mark (BOM) — Stack Overflow
  • PHP: Understanding Sessions — SitePoint

02 Jun 2018

phpsessionsС сессиями в php существует множество непонятных проблем. С появлением виртуальных окружений проблем стало больше.

Рассмотрим наиболее часто встречающиеся проблемы сессий на файлах (мы не будем затрагивать сессии в бд и кастомные обработчики).

session_start(): open(filename, O_RDWR) failed: No such file or directory

Очевидно, что ошибка возникает, когда не существует пути, по которому пишутся данные. Но при этом вы знаете, что на диске каталог, который был указан как аргумент session_save_path(), существует.

Например.

$ mkdir /tmp/sessions  
$ chmod 777 /tmp/sessions
session_save_path('/tmp/sessions');  
session_start();

Вы увидите на экране или в логах ошибку из заголовка (не во всех дистрибутивах).

Можно посмотреть audit.log из selinux, но если там нет ничего подозрительного и каталог действительно есть (а вы его создали выше), то причина такого поведения достаточно неожиданна.

Происходит это потому что вы работаете в centos 7 версии (или redhatfedora) и выше. Именно в этой версии ввели параметр PrivateTmp для сервисов. Что это означает для нас?

Сделайте второй скрипт, который перечисляет содержимое директории /tmp, а так же выводит реальный путь каталога /tmp/sessions.

var_dump(glob('/tmp/*'));

Откройте скрипт в браузере. Вы увидите, что содержимое в браузере кардинально отличается от содержимого реальной папки /tmp. На скриншоте мы видем вывод из консоли и из браузера — результат совершенно разный.

2018-06-02-12:32:03_1625x863

Как это побороть? Использовать другой каталог для хранения сессий. Или перед стартом приложения проверять и создавать в случае необходимости нужную файловую структуру.

session_start(): Session data file is not created by your uid

Не самая распространенная ошибка. Чаще всего возникает в виртуальных окружениях.

Ошибка возникает в случае, когда uid владельца файла сессии не совпадает с uid текущего пользователя под которым запущен интерпретатор.

Как проверить, что это именно наш случай? Нужно создать скрипт, которыый создает файл в каталоге, в котором вы планируете размещать сессии и сверяет uid владельца файла и uid владельца процесса.

$file = __DIR__ . DIRECTORY_SEPARATOR . 'file.name';  
$fd = fopen($file, 'w');  
fwrite($fd, 'test data');  
fclose($fd);  
if (file_exists($file)) {  
 $stat = stat($file);  
 var_dump($stat['uid'] == posix_getuid());  
}

Если мы увидим false, то да. Проблема имеет мысто быть. И вам нужно переместить сессии в другое место.

Так же подобное поведение характерно при некоторых способах монтирования nfs.

session_start(): open(filename, O_RDWR) failed: Permission denied

Каталог недоступен для записи и достаточно дать права 777. Но тут не все так очевидно и данный трюк действует не всегда. Если вы работаете в дистрибутивах, которые используют selinux, то даже при установке полных прав система можем вам не позволить писать по выбранному пути.

Это происходит потому что контекст процесса отличается от контекста папки. Вы всегда можете посмотреть в /var/log/audit/audit.log чтобы убедиться.

Как обращаться с контекстами можно подробнее посмотреть в документации и в книге.

Литература

  • CentOS wiki: SELinux
  • SELinux System Administration
  • GitHub: php-src

Теги:
linux

php

selinux

Категории:

Разработка

Понравилась статья? Поделить с друзьями:
  • Servostar 600 ошибки
  • Scarlett sc 410 ошибка e4 ремонт
  • Servo alarm ошибка на лазерном станке
  • Sc00003e xentry ошибка
  • Servista ru ошибка авторизации