我有3个php页面。
Counter.php - 我希望这个文件显示Counter 2,Counter 3得到的点击次数。
<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
</head>
<body>
You visited page Counter2
<?php include 'Counter2.php'; echo $Counter; ?>
Times.
You visited page Counter3
<?php include 'Counter3.php'; echo $Counter3; ?>
Times.
</body>
</html>
Counter2.php - 我想计算此页面的点击量。
<?php
session_start();
if(isset($_SESSION["counter"]))
{
$counter = $_SESSION["counter"];
}
else
{
$counter = 0;
}
$_SESSION["counter"] = $counter + 1;
?>
<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
</head>
<body>
<?= $counter ?>
</body>
</html>
Counter3.php - 我想计算此页面的点击量。
<?php
session_start();
if(isset($_SESSION["counter3"]))
{
$counter3 = $_SESSION["counter3"];
}
else
{
$counter3 = 0;
}
$_SESSION["counter3"] = $counter3 + 1;
?>
<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
</head>
<body>
You visted this page this many times:
<?= $counter3 ?>
</body>
</html>
现在,当我包含php文件<?php include 'Counter3.php'; echo $Counter3; ?>
时,一切都在发挥作用。
记录加载Counter.php文件时它继续增加的点击量。我不想要它,我只想让Counter.php记录Counter2和Counter3有多少次点击。
并停止Counter.php增加点击次数。
答案 0 :(得分:0)
您可以使用$_SERVER['REQUEST_URI']
向counter2.php和counter3.php添加额外的if,如果$_SERVER['REQUEST_URI']
指向counter.php,则可以跳过递增计数器
答案 1 :(得分:0)
包含页面会使代码运行,因此会增加页面中的所有计数器。而是直接使用$_SESSION[]
变量。
<?php
session_start()
?>
<!DOCTYPE html>
<html>
<head>
<title>Counter</title>
</head>
<body>
You visited page Counter2 <?php echo $_SESSION["counter2"]; ?> Times.
You visited page Counter3 <?php echo $_SESSION["counter3"]; ?> Times.
</body>
</html>
此外,在PHP中,您可以执行以下操作:
$_SESSION["counter3"] = isset($_SESSION["counter3"]) ? $_SESSION["counter3"] : 0;
//$_SESSION["counter3"] = $_SESSION["counter3"] ?? 0; // only in PHP 7
另外在旁注中,您不必在每个页面上创建此代码,因为从长远来看它可能会变得混乱。
<?php #counter.php
if(session_status() == PHP_SESSION_NONE){
session_start();
}
if(isset($_SESSION['counter'][$_SEVER['REQUEST_URI']])){
$_SESSION['counter'][$_SERVER['REQUEST_URI']] = $_SESSION['counter'][$_SEVER['REQUEST_URI']] + 1
} else {
$_SESSION['counter'][$_SERVER['REQUEST_URI']] = 1;
}
function countpagetimes(){
return $_SESSION['counter'][$_SERVER['REQUEST_URI']];
}
?>
<?php #somepage.php
include 'counter.php';
echo 'You visited this page ' . countpagetimes() . ' times'.
?>
答案 2 :(得分:0)
此问题有多种选择:
$_SERVER['REQUEST_URI']
让计数器仅递增
醇>