回声点击计数php按钮点击计数器

时间:2013-12-10 08:25:45

标签: php

我在php中发现了这个脚本按钮点击并将它们保存到txt文件。

 <?php
    if( isset($_POST['clicks']) )
    { 
        clickInc();
    }
    function clickInc()
    {
        $count = ("clickcount.txt");

        $clicks = file($count);
        $clicks[0]++;

        $fp = fopen($count, "w") or die("Can't open file");
        fputs($fp, "$clicks[0]");
        fclose($fp);

        echo $clicks[0];
    }
    ?>

    <html>

        <head>

           <title>button count</title>

        </head>
        <body>
            <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
                <input type="submit" value="click me!" name="clicks">
            </form>

        </body>
    </html>

我无法弄清楚如何将按钮点击次数回显到html的不同部分。 我试过放置:

 <?php
     echo $clicks[0];
 ?>

但这不起作用。 我究竟做错了什么? 感谢..

2 个答案:

答案 0 :(得分:1)

我建议将读取点击次数的代码部分与增加它的部分分开,以便您可以自己调用每个部分。然后,您不必保存实际增量部分的点击次数;您可以在需要时随时获得点击次数,就像在该时间点文件中存在的那样。

if( isset($_POST['clicks']) ) { 
    incrementClickCount();
}

function getClickCount()
{
    return (int)file_get_contents("clickcount.txt");
}

function incrementClickCount()
{
    $count = getClickCount() + 1;
    file_put_contents("clickcount.txt", $count);
}

通过调用getClickCount函数,您可以在HTML中的任意位置包含当前计数。

    <div>Click Count: <?php echo getClickCount(); ?></div>
</body>

答案 1 :(得分:0)

由于你的$ clicks [0]是clickInc函数的一部分。

$clicsCount = 0
if( isset($_POST['clicks']) ) { 
    $clicsCount = clickInc();
}

function clickInc()
{
    $count = ("clickcount.txt");

    $clicks = file($count);
    $clicks[0]++;

    $fp = fopen($count, "w") or die("Can't open file");
    fputs($fp, "$clicks[0]");
    fclose($fp);

    return $clicks[0];
}

而不是

<?php echo $clicsCount; ?>

你需要的地方

相关问题