發表新文章 回覆主題  [ 1 篇文章 ] 

討論區首頁 : 資訊專區 : PHP程式設計

發表人 內容
 文章主題 : COOKIE的應用
文章發表於 : 2011年 11月 5日, 12:45 
離線
系統管理員

註冊時間: 2009年 1月 14日, 06:05
文章: 1419
<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
?>
====================
<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>
====================
<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1);
?>
====================
<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
?>
The above example will output:
three : cookiethree
two : cookietwo
one : cookieone
====================
#cookies.php
/*This code will demonstrate use of cookies with PHP
It is very easy to understand and is better for beginner to
understand and get idea about power of cookies when used
with PHP.Here we give user a form to choose colors he/she
likes for website and when he/she visits site again within one
hour his/her settings are saved and read from cookie
and he/she doesn't have to set the page color and page
text color again.You can change time from 3600
seconds to whatever you deem appropriate in your case.
if you don't understand anything please email me*/

<?php
#checking if form has been submitted
if (isset($_POST['submitted'])){
#if yes (form is submitted) assign values from POST array to variables
$newbgColor=$_POST['bgColor'];
$newtxtColor=$_POST['txtColor'];
#set cookies
setcookie("bgColor",$newbgColor,time()+3600);
setcookie("txtColor",$newtxtColor,time()+3600);

}
#in case user has come for first time and cookies are not set then
if ((!isset($_COOKIE['bgColor']) ) && (!isset($_COOKIE['txtColor']))){
$bgColor = "Black";
$txtColor="White";
}
#if cookies are set then use them
else{
$bgColor = $_COOKIE['bgColor'];
$txtColor = $_COOKIE['txtColor'];
}
?>
<!-- HTML Page-->
<html>
<body bgcolor="<?php echo $bgColor ?>" text="<?php echo $txtColor ?>">
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method ="POST">
<p>Body Color:</p>
<select name=bgColor>
<option value ="Red">Red</option>
<option value ="Green" selected>Green</option>
<option value ="Blue">Blue</option>
<option value ="Yellow">Yellow</option>
<option value ="Black">Black</option>
<option value ="Brown">Brown</option>
<option value ="White">White</option>
</select>
<p>Text Color:</p>
<select name=txtColor>
<tion value ="Red">Red</option>
<option value ="Green" selected>Green</option>
<option value ="Blue">Blue</option>
<option value ="Yellow">Yellow</option>
<option value ="Black">Black</option>
<option value ="Brown">Brown</option>
<option value ="White">White</option>
</select>
<input type ="hidden" name="submitted" value="true"></br>
<input type="submit" value="remind">
</form>
</body>
</html>
====================
<?php
ob_start();
$MaxCount = 4;// set the max of the counter, in my tests "4" = (0,1,2,3) I adjusted below (+1) to get a "real" 4 (0,1,2,3,4) this is in reality 5 keys to humans, you can adjust script to eliminate "0", but my script makes use of the "0"

$random =(rand()%($MaxCount+1));//give me a random number limited by the max, adding "1" because computers start counting at "0"

if(!isset($_COOKIE['random'])){// check if random number cookie is not set
//echo"not set";
setcookie('random', $random);//set the cookie for the first time
}else{
$lastRandom= $_COOKIE['random']; //hold the last number if it was set before
if($lastRandom == $random){//some logic to avoid repeats
if($random < $MaxCount){//if below max, add 1
$random++;
//echo "under the max, adding 1, ";
}elseif($random >= ($MaxCount-1)){// if for some reason the random number is more than max or equal to it -1, and an additional -1 for max count in initial var (so in reality this -1 from intial max var, and -1 from $random which should be the same number)
$random--;
//echo "hit the max, subtracting 1, ";
}else{
$random++;
//echo "no case match, adding 1, ";
}
//echo "(".$lastRandom.", ".$random. "), they matched initally - was it fixed?";
}else{
//echo "(".$lastRandom.", ".$random. "), they DO NOT match";
setcookie('random', $random);
}
//echo"is set: {$_COOKIE['random']}";
}

ob_end_flush();

?>
====================
<?php
function SetCookieLive($name, $value='', $expire = 0, $path = '', $domain='', $secure=false, $httponly=false)
{
$_COOKIE[$name] = $value;
return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
}

function RemoveCookieLive($name)
{
unset($_COOKIE[$name]);
return setcookie($name, NULL, -1);
}
?>
====================
<?php
function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) {
//set a cookie as usual, but ALSO add it to $_COOKIE so the current page load has access
$_COOKIE[$name] = $value;
return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
}
?>
====================
<?php
$cookie_name = "mytestcookie";
if( !isset($_COOKIE[$cookie_name]) && empty($_COOKIE[$cookie_name]) )
setcookie("$cookie_name", 0, 0, "/");
?>
====================
<?php
header('Location: http://www.example.com/');
setcookie('asite', $site, time()+60*60, '/', 'site.com');
?>
====================
<?php
define( 'COOKIE_PORTIONS' , '_piece_' );

function clearpieces( $inKey , $inFirst ) {
$expire = time()-3600;

for ( $index = $inFirst ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) {
setcookie( $inKey.COOKIE_PORTIONS.$index , '' , $expire , '/' , '' , 0 );
unset( $_COOKIE[$inKey.COOKIE_PORTIONS.$index] );
}
}

function clearcookie( $inKey ) {
clearpieces( $inKey , 1 );
setcookie( $inKey , '' , time()-3600 , '/' , '' , 0 );
unset( $_COOKIE[$inKey] );
}

function storecookie( $inKey , $inValue , $inExpire ) {
$decode = serialize( $inValue );
$decode = gzcompress( $decode );
$decode = base64_encode( $decode );

$split = str_split( $decode , 4000 );//4k pieces
$count = count( $split );

for ( $index = 0 ; $index < $count ; $index += 1 ) {
$result = setcookie( ( $index > 0 ) ? $inKey.COOKIE_PORTIONS.$index : $inKey , $split[$index] , $inExpire , '/' , '' , 0 );
}

clearpieces( $inKey , $count );
}

function fetchcookie( $inKey ) {
$decode = $_COOKIE[$inKey];

for ( $index = 1 ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) {
$decode .= $_COOKIE[$inKey.COOKIE_PORTIONS.$index];
}

$decode = base64_decode( $decode );
$decode = gzuncompress( $decode );

return unserialize( $decode );
}
?>
====================
<?php
setcookie("testcookie", "value1hostonly", time(), "/", ".example.com", 0, true);
setcookie("testcookie", "value2subdom", time(), "/", "subdom.example.com", 0, true);
?>
====================
<?php
$kaker = explode(";", $_SERVER['HTTP_COOKIE']);
foreach($kaker as $val){
$k = explode("=", $val);
echo trim($k[0]) . " => " . $k[1];
}

// output
testcookie => value1hostonly
testcookie => value2subdom

?>
====================
<?php

if(isset($_GET['hide']) && $_GET['hide']=='y'){
setcookie("TmhabarMainNewsHide", 'y', time()+3600*24*1000,"/",".tmhabar.com",0);
}
elseif(isset($_GET['hide']) && $_GET['hide']=='n'){
setcookie("TmhabarMainNewsHide", 'n' ,time()+3600*24*1000,"/",".tmhabar.com",0);
}

$last_modified = filemtime('inc/somefile.html');
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified)." GMT");

echo $_COOKIE['TmhabarMainNewsHide'];

?>
====================
<?php
$foo=unserialize($_COOKIE['remember_me']);
if($foo['version']==1) {
// original cookie. Ignore it? Process it differently?
old_and_busted($foo['data']);
} else if($foo['version']==2) {
// new cookie, proceed as normal
new_hotness($foo['data']);
}
?>
====================
<?php

$ciphertext = $myEncryptionObject->encrypt( $plaintext );
$safeCiphertext = urlencode( $ciphertext );
setcookie( "myCookie", $safeCiphertext, 0, "", "", false, true);

?>

And then using urldecode( ) prior to decryption of the ciphertext:
<?php

$safeData = $_COOKIE[ "myCookie" ];
$ciphertext = urldecode( $safeData );
$plaintext = $myEncryptionObject->decrypt( $ciphertext );

?>
====================
<?php INI_Set('session.cookie_secure',true); ?>
====================
<?php
createCookie($name, $value='', $maxage=0, $path='',$domain='', $secure=false, $HTTPOnly=false)
{
if(is_array($name))
{
list($k,$v) = each($name);

$name = $k.'['.$v.']';

}
$ob = ini_get('output_buffering');
// Abort the method if headers have already been sent, except when output buffering has been enabled
if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )
return false;
if ( !empty($domain) )
{
// Fix the domain to accept domains with and without 'www.'.
if ( strtolower( substr($domain, 0, 4) ) == 'www.' ) $domain = substr($domain, 4);
// Add the dot prefix to ensure compatibility with subdomains
if ( substr($domain, 0, 1) != '.' ) $domain = '.'.$domain;
// Remove port information.
$port = strpos($domain, ':');
if ( $port !== false ) $domain = substr($domain, 0, $port);
}
// Prevent "headers already sent" error with utf8 support (BOM)
//if ( utf8_support ) header('Content-Type: text/html; charset=utf-8');
if(is_array($name))
{
header('Set-Cookie: '.$name.'='.rawurlencode($value)
.(empty($domain) ? '' : '; Domain='.$domain)
.(empty($maxage) ? '' : '; Max-Age='.$maxage)
.(empty($path) ? '' : '; Path='.$path)
.(!$secure ? '' : '; Secure')
.(!$HTTPOnly ? '' : '; HttpOnly'), false);
}else{
header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value)
.(empty($domain) ? '' : '; Domain='.$domain)
.(empty($maxage) ? '' : '; Max-Age='.$maxage)
.(empty($path) ? '' : '; Path='.$path)
.(!$secure ? '' : '; Secure')
.(!$HTTPOnly ? '' : '; HttpOnly'), false);
}
return true;
}
?>
====================
<?php
setcookie($name, $value, time()+(60*60*24*365));
?>
====================
<?php

/**
* A better alternative (RFC 2109 compatible) to the php setcookie() function
*
* @param string Name of the cookie
* @param string Value of the cookie
* @param int Lifetime of the cookie
* @param string Path where the cookie can be used
* @param string Domain which can read the cookie
* @param bool Secure mode?
* @param bool Only allow HTTP usage?
* @return bool True or false whether the method has successfully run
*/
function createCookie($name, $value='', $maxage=0, $path='', $domain='', $secure=false, $HTTPOnly=false)
{
$ob = ini_get('output_buffering');

// Abort the method if headers have already been sent, except when output buffering has been enabled
if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )
return false;

if ( !empty($domain) )
{
// Fix the domain to accept domains with and without 'www.'.
if ( strtolower( substr($domain, 0, 4) ) == 'www.' ) $domain = substr($domain, 4);
// Add the dot prefix to ensure compatibility with subdomains
if ( substr($domain, 0, 1) != '.' ) $domain = '.'.$domain;

// Remove port information.
$port = strpos($domain, ':');

if ( $port !== false ) $domain = substr($domain, 0, $port);
}

// Prevent "headers already sent" error with utf8 support (BOM)
//if ( utf8_support ) header('Content-Type: text/html; charset=utf-8');

header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value)
.(empty($domain) ? '' : '; Domain='.$domain)
.(empty($maxage) ? '' : '; Max-Age='.$maxage)
.(empty($path) ? '' : '; Path='.$path)
.(!$secure ? '' : '; Secure')
.(!$HTTPOnly ? '' : '; HttpOnly'), false);
return true;
}

?>
====================
<?php
ob_start();

echo "somtehing";
setcookie("cookie", "value"); /* if you didn't add the ob_start() function at this point the headers would have been already sent and the cookie have not been saved */

ob_end_flush();
?>
====================
<?php
setcookie(mycookie, $test, time() + 3600);
setcookie("mycookie","",time() - 3600);
?>

The above is wrong. But the examples are right:

<?php
setcookie("mycookie", $test, time() + 3600);
setcookie("mycookie","",time() - 3600);
?>

<?php
setcookie(mycookie, $test, time() + 3600);
setcookie(mycookie,"",time() - 3600);
?>
====================
<?php
function FreshenSessionCookie($lifetimeSeconds, $cookieName = 'PHPSESSID')
{
if (isset($_COOKIE[$cookieName]))
{
$data = $_COOKIE[$cookieName];
$timeout = time()+$lifetimeSeconds;
setcookie($cookieName, $data, $timeout);
}
}
?>
====================
<?php
function build_cookie($var_array) {
if (is_array($var_array)) {
foreach ($var_array as $index => $data) {
$out.= ($data!="") ? $index."=".$data."|" : "";
}
}
return rtrim($out,"|");
}

function break_cookie ($cookie_string) {
$array=explode("|",$cookie_string);
foreach ($array as $i=>$stuff) {
$stuff=explode("=",$stuff);
$array[$stuff[0]]=$stuff[1];
unset($array[$i]);
}
return $array;
}
?>
====================
<?php
function set_cookie($Name, $Value = '', $MaxAge = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false) {
header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
. (empty($MaxAge) ? '' : '; Max-Age=' . $MaxAge)
. (empty($Path) ? '' : '; path=' . $Path)
. (empty($Domain) ? '' : '; domain=' . $Domain)
. (!$Secure ? '' : '; secure')
. (!$HTTPOnly ? '' : '; HttpOnly'), false);
}

# examples:
set_cookie("TestCookie", $value, 3600); /* expire in 1 hour */
set_cookie("TestCookie", $value, 3600, "/~rasmus/", ".example.com", 1);
?>
====================
<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !== false) ? $_SERVER['HTTP_HOST'] : '');
?>
====================
<?php setcookie("region", $_GET['set_region']); ?>
<?php $_SERVER['HTTP_COOKIE'] ?>
====================
<?php

// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}

?>
====================
<?php

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);

?>
====================
<?PHP

//check to see how to set the cookie
$Browsertype = $_SERVER['HTTP_USER_AGENT'];
$Parts = explode(" ",$Browsertype);
$MSIE = array_search("MSIE",$Parts);

if($MSIE)
{
setcookie("name", "", time()+20000);
}
else
{
setcookie("name", "", time()-20000, "/", ".domain.com" );
}

?>
====================
<?php

$Seperator = '--';
$uniqueID = 'Ju?hG&F0yh9?=/6*GVfd-d8u6f86hp';
$Data = 'Ahmet '.md5('123456789');

setcookie('VerifyUser', $Data.$Seperator.md5($Data.$uniqueID));

if ($_COOKIE) {
$Cut = explode($Seperator, $_COOKIE['VerifyUser']);
if (md5($Cut[0].$uniqueID) === $Cut[1]) {
$_COOKIE['VerifyUser'] = $Cut[0];
} else {
die('Cookie data is invalid!!!');
}
}

echo $_COOKIE['VerifyUser'];

?>
====================
<?php
function set_cookie_fix_domain($Name, $Value = '', $Expires = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false)
{
if (!empty($Domain))
{
// Fix the domain to accept domains with and without 'www.'.
if (strtolower(substr($Domain, 0, 4)) == 'www.') $Domain = substr($Domain, 4);
$Domain = '.' . $Domain;

// Remove port information.
$Port = strpos($Domain, ':');
if ($Port !== false) $Domain = substr($Domain, 0, $Port);
}

header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
. (empty($Expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $Expires) . ' GMT')
. (empty($Path) ? '' : '; path=' . $Path)
. (empty($Domain) ? '' : '; domain=' . $Domain)
. (!$Secure ? '' : '; secure')
. (!$HTTPOnly ? '' : '; HttpOnly'), false);
}
?>
====================
<?php
//Flag up repeat actions (like credit card transaction, etc)
if(count($_POST)>0) {
$lastpost= isset($_COOKIE['lastpost']) ? $_COOKIE['lastpost'] : '';
if($lastpost!=md5(serialize($_POST))) {
setcookie('lastpost', md5(serialize($_POST)));
$_POST['_REPEATED']=0;
} else {
$_POST['_REPEATED']=1;
}
}

//At this point, if $_POST['_REPEATED']==1, then the user
//has hit the refresh button; so don't do any actions that you don't
//want to repeat!
?>
====================
<?php
session_start();

// many code

$sessionName = session_name();
$sessionCookie = session_get_cookie_params();

session_destroy();

setcookie($sessionName, false, $sessionCookie['lifetime'], $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure']);
?>
====================
<?php
header("Pragma: no-cache");
header('Location: http://www.example.com/');
setcookie('AA','1',0,'/');
setcookie('BB','2',time() + 24 * 3600,'/');
?>
====================


Back to top
 個人資料  
 
顯示文章 :  排序  
發表新文章 回覆主題  [ 1 篇文章 ] 

討論區首頁 : 資訊專區 : PHP程式設計


誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 2 位訪客


不能 在這個版面發表主題
不能 在這個版面回覆主題
不能 在這個版面編輯文章
不能 在這個版面刪除文章
不能 在這個版面上傳附加檔案

搜尋:
前往 :  
cron
Style by Midnight Phoenix & N.Design Studio
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
正體中文語系由 竹貓星球 維護製作