PHP 웹사이트 방문 Counter 간단 예제

Goal : PHP Simple Website Counter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>@TODO TITLE</title>
        <script>
        </script>
    </head>
    <body>
    <?php
        session_start();
        $counter_name = "counter.txt";
        $log_name = "log.txt";
        // Read Counter
        $f = fopen($counter_name,"r");
        $counter = fread($f, filesize($counter_name));
        fclose($f);
            
        // Check Session Exist
        if(!isset($_SESSION['hasVisit'])){
            $counter += 1;
            
            $_SESSION['hasVisit'= "yes";
            $_SESSION['visitNum'= $counter;
            
            $f1 = fopen($counter_name"w");
            fwrite($f1$counter);
            fclose($f1);
            
            $f2 = fopen($log_name"a");
            fwrite($f2$counter . ' ' . $_SERVER['REMOTE_ADDR'] . ' ' . date("Y-m-d H:i:s") . ' ' . session_id() . PHP_EOL);
            fclose($f2);
        }
        else{
            $counter = $_SESSION['visitNum'];
        }
        echo "You are the $counter visitor";
        echo "<br>";
        echo "IP : ".$_SERVER['REMOTE_ADDR'];
    ?>
    </body>
</html>
 
 
cs

Format에 맞는 counter.txt를 만들어 두면 끝 (counter.txt 파일 생성 후 0 기입)

댓글