2012-04-20 72 views
0

我希望PHP能夠回顯頁面被瀏覽的次數。作爲服務器端腳本語言,我相當有信心有一種方法。PHP - 頁面被瀏覽了多少次

這是我在想什麼......

main.php

<body> 
<?php 
include("views.php"); 
$views = $views + 1; 
echo $views; 
?> 
</body> 

views.php

<?php $views = 0; ?> 

這工作,但不更新。 (它會顯示1,但不會繼續刷新。)

+5

您需要使用databsae – 2012-04-20 01:45:41

+1

或文本文件... – jeroen 2012-04-20 01:46:32

+0

'file_put_contents( 'count.txt',((INT)的file_get_contents( 'count.txt')) + 1);' – Dan 2012-04-20 01:48:17

回答

2

問題是變量$views不能從視圖中持久存在。事實上,下一次有人回到您的網站$views將被重置爲0.您需要查看某種形式的持久性來存儲視圖總數。

您可以完成此操作的一種方法是使用數據庫或通過文件。如果您正在使用文件,您可以在views.php文件中執行以下操作。

views.php

$views = 0; 
$visitors_file = "visitors.txt"; 

// Load up the persisted value from the file and update $views 
if (file_exists($visitors_file)) 
{ 
    $views = (int)file_get_contents($visitors_file) 
} 

// Increment the views counter since a new visitor has loaded the page 
$views++; 

// Save the contents of this variable back into the file for next time 
file_put_contents($visitors_file, $views); 

main.php

include("views.php"); 
echo $views; 
0

您將需要存儲數據的某處。變量不會在請求之間保持其狀態。 $views = 0始終表示$views = 0,不管該變量是否爲included

將視圖數寫入文件(file_put_contents,file_get_contents)或寫入數據庫以永久存儲它們。

0

刷新頁面時,狀態不會保存。這個$views設置爲0,每次你開始,並增加1.

要增加計數並保存該值,你需要通過使用數據庫或文件來保存數字。

+0

非常感謝您的信息。 – user1345415 2012-04-20 01:50:11

0

偉大的想法將是使用如MySQL的數據庫。互聯網上有很多文章如何設置和使用PHP。

你可能會想要做什麼 - 每次訪問頁面時更新'views'中的頁面行。最簡單的方法是這樣的:

<?php 
/* don't forget to connect and select a database first */ 
$page = 'Home Page'; // Unique for every page 
mysql_query("UPDATE views SET num = num + 1 WHERE page = '$page'");