PHP/Cookie Session/ COOKIE

Материал из Web эксперт
Перейти к: навигация, поиск

Checking for Cookie Support from PHP

   <source lang="html4strict">

<?php

   if(!isset($_GET["testcookie"])) {
       setcookie("testcookie", "test value");
       header("Location:  {$_SERVER["PHP_SELF"]}?testcookie=1");
       exit;
   } else {
       if(isset($_COOKIE["testcookie"])) {
           setcookie("testcookie");
           echo "You have cookies enabled";
       } else {
           echo "You do not support cookies!";
       }
   }

?>

 </source>
   
  


Get Cookie Data

   <source lang="html4strict">

<?php

 $user  = $_COOKIE["firstname"];
 $color = $_COOKIE["fontcolor"];

?> <html>

<head>
 
 <title>Get Cookie Data</title>
 
 <style type = "text/css">
  body { color: <?php echo( $color ); ?> }

 </style>
</head>
<body>

Hello <?php echo( $user ); ?>!

</body>

</html>

 </source>
   
  


Printing a cookie value

   <source lang="html4strict">

<? print "Hello, " . $_COOKIE["userid"]; ?>

 </source>
   
  


Reading a cookie value

   <source lang="html4strict">

<?php if (isset($_COOKIE["flavor"])) {

   print "You ate a {$_COOKIE["flavor"]} cookie.";

} ?>

 </source>
   
  


Reading all cookie values

   <source lang="html4strict">

<?php foreach ($_COOKIE as $cookie_name => $cookie_value) {

   print "$cookie_name = $cookie_value 
";

} ?>

 </source>
   
  


Setting and Printing a Cookie Value

   <source lang="html4strict">

<?php

setcookie( "vegetable", "artichoke", time()+3600, "/","wbex.ru", 0 );
?>
<html>
<head>
<title>Setting and Printing a Cookie Value</title>
</head>
<body>
<?php
if ( isset( $_COOKIE["vegetable"] ) ) {
print "

Hello again, your chosen vegetable is "; print "{$_COOKIE["vegetable"]}

";
} else {
print "

Hello you. This may be your first visit

";
}
?>
</body>
</html>
 
 </source>
   
  


Still Logged In with cookie

   <source lang="html4strict">

<?php

 $auth = $_COOKIE["auth"];
 header( "Cache-Control:no-cache" ); 
 if( ! $auth == "ok" ) 
 {
   header("Location:login.php" );
   exit();
 }

?>

<html>

<head>
 <title>Still Logged In</title>
</head>
<body>
 You are still logged in ...
</body>

</html>

 </source>