php学习 (三)

1.3:记录操作日志并显示
做一个页面,上面有一文本编辑框和一个按钮,在文本框中输入内容,点击按钮后,将文本框中的内容记录(追加)到文件 中,文件名的格式为 “program年月日时分.txt”, 如:program200907231804.txt,并将当前小时内产生的文件的内容显示在页面上,日志格式(类似log4j)
[2013-03-11 00:00:00, 287] INFO - test1
[2013-03-11 00:00:10, 640] INFO - test2

代码实现如下:

Test1.3.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
    <?php
        echo "1.3:记录操作日志并显示";
        echo "<br>";
        echo "做一个页面,上面有一文本编辑框和一个按钮,在文本框中输入内容,点击按钮后,将文本框中的内容记录(追加)到文件中,文件名的格式为 “program年月日时分.txt”, 如:program200907231804.txt,并将当前小时内产生的文件的内容显示在页面上,日志格式(类似log4j)";
        echo "<br>";
        echo "[2013-03-11 00:00:00, 287] INFO - test1<br>
               [2013-03-11 00:00:10, 640] INFO - test2<br>";
    ?>
    <form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
        请输入内容:<br>
        <input type = "text" name = "txt1"><br>
        <input type = "submit" value = "提交" name = "btn1"><br>
    </form>
    <?php

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $txt1 = testInput($_POST["txt1"])."\n";
        
        date_default_timezone_set("Asia/Shanghai");                                    //设定时区
        $d = "/export/www/test/program".date("Ymdhi").".txt";                            //要创建或打开的文件名
        $s = date("[Y-m-d h:i:s]");                                                    //日志格式前缀
        
        $myfile = fopen($d, "a") or die("Unable to open file!");                    //对文件的打开,写入,关闭
        fwrite($myfile, $s.$txt1) or die("Unable to write file!");
        fclose($myfile) or die("Unable to close file!");
        
        $dir = "/export/www/test";                                                    //写入目录的绝对路径
        $filename = scandir($dir);                                                    //获取该目录下的所有文件名
        
        for($i = 0;$i < count($filename);$i++){                
        $h = "program".date("Ymdh");                                                    //要寻找的文件的前缀
        if(strpos($filename[$i],$h) === 0)                                            //看是否前缀匹配
        {
            $myfile = fopen($filename[$i], "r") or die("Unable to open file!");        //对文件的读取
            // 输出单行直到 end-of-file
            while(!feof($myfile)) {
                echo  fgets($myfile) . "<br>";
            }
            fclose($myfile);
        }
        }
    }
    
    function testInput($data) {                                                    //对用户输入的数据进行处理,包括去除空格和反斜杠
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }    
    ?>
</body>
</html>

posted @ 2016-10-19 14:29  zzl_javaer  阅读(131)  评论(0)    收藏  举报