Answer on an old question, this new post is posted on April the 4th 2013
To complete the answer of @misza, here a advanced method to check if cookies are enabled without page reloading. The problem with @misza is that it not always work when the php ini setting session.use_cookies
is not true. Also the solution does not check if a session is already started.
I made this function and test it many times with in different situations and does the job very well.
function suGetClientCookiesEnabled() // Test if browser has cookies enabled
{
// Avoid overhead, if already tested, return it
if( defined( 'SU_CLIENT_COOKIES_ENABLED' ))
{ return SU_CLIENT_COOKIES_ENABLED; }
$bIni = ini_get( 'session.use_cookies' );
ini_set( 'session.use_cookies', 1 );
$a = session_id();
$bWasStarted = ( is_string( $a ) && strlen( $a ));
if( !$bWasStarted )
{
@session_start();
$a = session_id();
}
// Make a copy of current session data
$aSesDat = (isset( $_SESSION ))?$_SESSION:array();
// Now we destroy the session and we lost the data but not the session id
// when cookies are enabled. We restore the data later.
@session_destroy();
// Restart it
@session_start();
// Restore copy
$_SESSION = $aSesDat;
// If no cookies are enabled, the session differs from first session start
$b = session_id();
if( !$bWasStarted )
{ // If not was started, write data to the session container to avoid data loss
@session_write_close();
}
// When no cookies are enabled, $a and $b are not the same
$b = ($a === $b);
define( 'SU_CLIENT_COOKIES_ENABLED', $b );
if( !$bIni )
{ @ini_set( 'session.use_cookies', 0 ); }
//echo $b?'1':'0';
return $b;
}
Usage:
if( suGetClientCookiesEnabled())
{ echo 'Cookies are enabled!'; }
else { echo 'Cookies are NOT enabled!'; }
Important note: The function temporarily modify the ini setting of PHP when it not has the correct setting and restore it when it was not enabled. This is only to test if cookies are enabled. It can get go wrong when you start a session and the php ini setting session.use_cookies has an incorrect value. To be sure that the session is working correctly, check and/or set it before start a session, for example:
if( suGetClientCookiesEnabled())
{
echo 'Cookies are enabled!';
ini_set( 'session.use_cookies', 1 );
echo 'Starting session';
@start_session();
}
else { echo 'Cookies are NOT enabled!'; }