php實現計數器方法小結_php技巧

來源:互聯網
上載者:User

本文執行個體講述了php實現計數器的方法。分享給大家供大家參考。具體如下:

這裡收藏了三款php計數器代碼,他們三個都有一個同共點就是全部無需資料庫,而是利用了文字檔來實現網頁瀏覽計數.

第一款PHP計數器代碼如下:

複製代碼 代碼如下:
<?php 
//計數器 
function countx($file="count.dat"){ 
if(file_exists($file)){ 
$fp=fopen($file,"r"); 
$numx=fgets($fp,10); 
fclose($fp); 
$numx++; 
//以上四行代碼可以用一條運算式代替:$numx=file_get_contents($file)+1; 

else{ 
$numx=1;} 
file_put_contents($file,$numx);//當檔案不存在時,這函數會自動建立檔案,而且會自動把參數轉成字串寫入。 
echo $numx; 
/*整個函數體可以用兩條運算式代替:file_exists($file)?file_put_contents($file,file_get_contents($file)+1):file_put_contents($file,"1");readfile($file); 
*/ 

//函數調用 
countx(); 
?>

第二款PHP計數器,代碼如下:
複製代碼 代碼如下:
<?php 
  $counterfile = "balong.txt";//儲存數值的檔案名稱幾路徑 
  function displaycounter($counterfile) { 
   $fp = fopen($counterfile,"rw"); 
   $num = fgets($fp,5); 
   $num += 1; 
   print "您是第 "."$num"." 個看巴瀧計數器的傢伙"; 
   exec( "rm -rf $counterfile"); 
   exec( "echo $num > $counterfile"); 
  } 
   
  if (!file_exists($counterfile)) { 
   exec( "echo 0 > $counterfile"); 
  } 
   
  displaycounter($counterfile); 
?>

第三款PHP計數器代碼如下:
複製代碼 代碼如下:
<?php 
  $counterfile = "www.jb51.net.txt";//儲存數值的檔案名稱幾路徑 
   
  function displaycounter($counterfile) { 
   $fp = fopen($counterfile,"rw"); 
   $num = fgets($fp,5); 
   $num += 1; 
   print "您是第 "."$num"." 個看巴瀧計數器的傢伙"; 
   exec( "rm -rf $counterfile"); 
   exec( "echo $num > $counterfile"); 
  }
   
  if (!file_exists($counterfile)) { 
   exec( "echo 0 > $counterfile"); 
  } 
   
  displaycounter($counterfile); 
?>

希望本文所述對大家的php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.