PHP7.27: Cookie and Session

 

<?php

// 有的瀏覽器不支持Cookie,這要考慮的
$cFile="count.txt";
$acctime=time();
if(file_exists($cFile)){
	$fp=fopen($cFile,"r"); 
	$str=fgets($fp,22);
	fclose($fp);
	$count=trim($str);
	$count++;
}else{
	$count=1;
}
$first=false;
if(!isset($_COOKIE['acctime'])){
	setcookie("acctime",$acctime,time()+3600*24);
	$first=true;
	$acctime=3600*24+$acctime;
}else{
	$acctime=3600*24+$_COOKIE['acctime'];
}
if($first||$acctime<=time()){
	$count=sprintf("%d",$count);
	$fp=fopen($cFile,"w");
	fputs($fp,$count);
	fclose($fp);
}else{
	$count--;
}
//print "您是第 ".$count." 位訪客。您訪問計入統計的時間是:".date("Y-n-j H:i:s",$acctime)."。";
?>
<?php
//讀取顯示
    $f_open=fopen('count.txt','r+');
	$count=fgets($f_open);
	settype($count,"string");
	$len=strlen($count);
    $str=str_repeat("0",6-$len);
    echo "當前的訪問量爲:";
    for($i=0;$i<=strlen($str);$i++){
		echo '<img src=images/0.gif>';
    }
    for($j=0;$j<$len;$j++){
      switch ($count[$j]){
      	    case "0"; $img[$j]="0.gif";break;
		    case "1"; $img[$j]="1.gif";break;
		    case "2"; $img[$j]="2.gif";break;
		    case "3"; $img[$j]="3.gif";break;
		    case "4"; $img[$j]="4.gif";break;
		    case "5"; $img[$j]="5.gif";break;
		    case "6"; $img[$j]="6.gif";break;
		    case "7"; $img[$j]="7.gif";break;
		    case "8"; $img[$j]="8.gif";break;
		    case "9"; $img[$j]="9.gif";break;
		}
		echo "<img src=images/".$img[$j]." title=".$img[$j].".>";
   }

?>

  

<?php
	session_start(); //建立會話
	$f_open=fopen('count.txt','r+');
	$count=fgets($f_open);
	if($_SESSION[count]==''){  //全局變量
		$count++;
		rewind($f_open);
		fwrite($f_open,$count);
		fclose($f_open);
		$_SESSION[count]=1;  //存儲會話變量
		//unset($_SESSION[count]); //註銷會話變量
		//session_unregister($_SESSION[count]) //php4
		//session_unset($_SESSION[count])
	}
?>
相關文章
相關標籤/搜索