To answer your question exactly, if you create a function
<?php
function cookies_are_enabled() {
setcookie('enabled', 'enabled');
return $_COOKIE['enabled'] === 'enabled';
}
?>
Then in your code you have:
<?php
if (cookies_are_enabled()) {
/* Cookies related code goes here */
/* Create PHP cookie, read cookies etc */
} else {
/* Do something else */
}
?>
Update: As pointed out in the comments. This won't work directly. From the setcookie PHP page (my emphasis):
'Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.'
Given that you can't trust setcookie, best I can think of doing is forcing a redirect.
<?php
function cookies_are_enabled() {
// if first page load
// set cookie and redirect
// if redirected check the cookie
if (isset($_GET['cookie_check'])) {
return $_COOKIE['enabled'] === 'enabled';
} else {
setcookie('enabled', 'enabled');
if (empty($_SERVER['QUERY_STRING'])) {
$url = $_SERVER['PHP_SELF'].'?cookie_check=1';
} else {
$url = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&cookie_check=1';
}
exit(header("Location: $url"));
}
}
if (cookies_are_enabled()) {
/* Cookies related code goes here */
/* Create PHP cookie, read cookies etc */
$message = 'cookies are enabled';
} else {
/* Do something else */
$message = 'cookies are <strong>not</strong> enabled';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cookies!</title>
</head>
<body>
<p><?php echo $message; ?></p>
</body>
</html>