TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱

悠悠楠杉

网站页面

PHP利用TXT文本实现点赞、评论功能

2020-12-08
/
0 评论
/
725 阅读
/
正在检测是否收录...
12/08

textarea 换行符


index.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <title>PHP利用TXT文本实现点赞、评论功能</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
    <div class="content">
        <div class="cmnt_list">
            <div class="popular-review">热门评论</div>
            <div class="comment">
                <ul class="select-avatar clearfix">
                    <li class="on"><input type="radio" name="avatar" value="img/pl1.jpg" checked><img src="img/pl1.jpg"></li>
                    <li><input type="radio" name="avatar" value="img/pl2.jpg"><img src="img/pl2.jpg"></li>
                    <li><input type="radio" name="avatar" value="img/pl3.jpg"><img src="img/pl3.jpg"></li>
                    <li><input type="radio" name="avatar" value="img/pl4.jpg"><img src="img/pl4.jpg"></li>
                    <li><input type="radio" name="avatar" value="img/pl5.jpg"><img src="img/pl5.jpg"></li>
                </ul>
                
                <input type="text" name="" class="nickname-box" placeholder="请输入你的昵称"><span class="nickname-ts"></span>
                <textarea class="comment-box" placeholder="请输入你的评论内容"></textarea><span class="comment-ts"></span>
                <button class="comment-btn">发表评论</button>
            </div>
            <?php
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $PHP_SELF = $_SERVER['PHP_SELF'];
            $url = $http_type . $_SERVER['HTTP_HOST'] . substr($PHP_SELF, 0, strrpos($PHP_SELF, '/') + 1);
            // echo $url;
            $loc1 = file_get_contents($url.'1.php?txt=num');
            // echo $loc;
            $arr1 = json_decode($loc1,true);
            // print_r($arr1);
            $loc2 = file_get_contents($url.'1.php?txt=cmnt');
            $arr2 = json_decode($loc2,true);
            // print_r($arr2);
            ?>
            <?php for($i = 0;$i < count($arr1);$i++){?>
            <div class="cmnt_item">
                <p class="cmnt_top">
                    <span>
                        <img src="<?php echo $arr2[$i][0];?>">
                        <i class="cmnt_nick"><?php echo $arr2[$i][1];?>
                            <!-- <em>地区</em> --></i>
                    </span>
                </p>
                <p class="cmnt_text"><?php echo $arr2[$i][2];?></p>
                <div class="cmnt_op_bottom clearfix">
                    <p class="cmnt_op_bottom_times"><?php echo $arr2[$i][3];?></p>
                    <span class="cmnt_op">
                        <a data-sudaclick="comment2_0" href="javascript:void(0);" title="赞" class="good j_favor_single" id="a<?php echo $i;?>"><img src="img/like.png" class="like"><span><?php echo $arr1[$i];?></span></a>
                        <!-- <a href="javascript:void(0);" title="评论" class="cmntico j_cmnt_single" data-sudaclick="comment1_0"></a> -->
                    </span>
                </div>
            </div>
        <?php }?>
        </div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script src="js/sweetalert.js"></script>
    <script>
        function get_cookie(Name) {
            var search = Name + "=";
            var returnvalue = "";
            if (document.cookie.length > 0) {
                offset = document.cookie.indexOf(search);
                if (offset != -1) {
                    // if cookie exists
                    offset += search.length;
                    // set index of beginning of value
                    end = document.cookie.indexOf(";", offset);
                    // set index of end of cookie value
                    if (end == -1)
                        end = document.cookie.length;
                    returnvalue = decodeURI(document.cookie.substring(offset, end))
                }
            }
            return returnvalue;
        }
        $('.good').on('click', function() {
            var nid = $(this).attr('id');
            if (get_cookie("like_" + nid + "") == nid) {
                swal("提示", "你已经点过赞", "error", {
                    buttons: "确定"
                });
            } else {
                var num = $(this).find('span').html();
                num++;
                $(this).find('span').html(num);
                var num_str = '';
                for (var i = 0; i < $('.good span').length; i++) {
                    // console.log($('.good span').eq(i).html())
                    num_str += $('.good span').eq(i).html() + "\n";
                }
                // console.log(num_str);
                $.post('1.php', {
                    num: num_str
                }, function(ret) {
                    // console.log(ret);
                    if (ret['code'] == 200) {
                        document.cookie = "like_" + nid + "=" + nid;
                        // console.log(nid);
                    } else {
                        swal("提示", "点赞失败", "error", {
                            buttons: "确定"
                        });
                    }
                })
            }

        })
        $('.select-avatar li').on('click', function() {
            $('.select-avatar li').attr('class', '');
            $(this).attr('class', 'on');
            $(this).find('[name=avatar]').prop("checked", true);
            // console.log($('[name=avatar]:checked').val());
        })

        function nickName() {
            pattern = /^[\u4E00-\u9FA5A-Za-z0-9]+$/;
            if ($('.nickname-box').val() == '') {
                $('.nickname-ts').css('color', 'red');
                $('.nickname-ts').html('昵称不能为空');
                return false;
            } else if (!pattern.test($('.nickname-box').val())) {
                $('.nickname-ts').css('color', 'red');
                $('.nickname-ts').html('昵称格式不正确');
                return false;
            } else {
                $('.nickname-ts').html('');
                return true;
            }
        }

        function comment() {
            if ($('.comment-box').val() == '') {
                $('.comment-ts').css('color', 'red');
                $('.comment-ts').html('内容不能为空');
                return false;
            } else {
                $('.comment-ts').html('');
                return true;
            }
        }
        $('.nickname-box').on('blur', function() {
            nickName();
        })
        $('.comment-box').on('blur', function() {
            comment();
        })
        $('.comment-btn').on('click', function() {
            if (nickName() && comment()) {
                $.post('1.php', {
                    head_image: $('[name=avatar]:checked').val(),
                    nickname_box: $('.nickname-box').val(),
                    comment_box: $('.comment-box').val(),
                    xnum: 0
                }, function(ret) {
                    console.log(ret);
                    if (ret['code'] == 200) {
                        swal("提示", "发表评论成功", "success", {
                            buttons: "确定" //,dangerMode: true //确定按钮变红色
                        }).then((value) => {
                            // swal(`The returned value is: ${value}`);
                            if (value) {
                                // swal('确定');
                                location.reload();
                            } else {
                                // swal('取消');
                                location.reload();
                            }
                        });
                    } else {
                        swal("提示", "发表评论失败", "error", {
                            buttons: "确定"
                        });
                    }
                })
            } else {
                nickName();
                comment();
            }

        })
    </script>
</body>

</html>

1.php

<?php

header('content-type: application/json;charset=utf-8');
date_default_timezone_set('PRC'); //设置为中华人民共和国的时间
if (!empty($_POST)) {
    if (isset($_POST['num'])) {
        $fp = file_put_contents('1.txt', trim($_POST['num']));
        if ($fp !== false) {
            echo json_encode(array('code' => '200', 'msg' => '添加成功'));
        } else {
            echo json_encode(array('code' => '400', 'msg' => '添加失败'));
        }
        exit();
    }
    $fp2 = file_put_contents('2.txt', $_POST['head_image'] . ',' . trim($_POST['nickname_box']) . ',' . trim(str_replace(',', ',', $_POST['comment_box'])) . ',' . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
    if ($fp2 !== false) {
        if (isset($_POST['xnum'])) {
            file_put_contents('1.txt', trim($_POST['xnum']) . "\n", FILE_APPEND);
        }
        echo json_encode(array('code' => '200', 'msg' => '添加成功'));
    } else {
        echo json_encode(array('code' => '400', 'msg' => '添加失败'));
    }

} else {
    if (isset($_GET['txt'])) {
        if ($_GET['txt'] == 'num') {
            $str = file_get_contents('1.txt');
            $arr = explode("\n", $str);
            // print_r($arr);
            for ($i = 0; $i < count($arr); $i++) {
                if ($arr[$i] == '') {
                    unset($arr[$i]);
                }
            }
            echo json_encode($arr);
        } else if ($_GET['txt'] == 'cmnt') {
            $str = file_get_contents('2.txt');
            $arr = explode("\n", $str);
            // print_r($arr);
            for ($i = 0; $i < count($arr); $i++) {
                $arrs[] = explode(",", $arr[$i]);
                if (isset($arrs[$i][0]) && $arrs[$i][0] == '') {
                    unset($arrs[$i]);
                }
            }
            // print_r($arrs);
            echo json_encode($arrs);
        }

    } else {
        echo json_encode(array('code' => '400', 'msg' => '获取失败'));
    }
}

style.css

html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;height:100%}body{margin:0;font-size:14px;font-family:"Helvetica Neue",Helvetica,STHeiTi,Arial,sans-serif;line-height:1.5;color:#333;background-color:#fff;min-height:100%}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block}audio:not([controls]){display:none;height:0}progress{vertical-align:baseline}[hidden],template{display:none}a{background:transparent;text-decoration:none;color:#08c}a:active{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{max-width:100%;border:0;vertical-align:middle}svg:not(:root){overflow:hidden}pre{overflow:auto;white-space:pre;white-space:pre-wrap;word-wrap:break-word}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0;vertical-align:middle}button,input,select{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;box-sizing:border-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid #c0c0c0;margin:0 2px;padding:0.35em 0.625em 0.75em}legend{border:0;padding:0}textarea{overflow:auto;resize:vertical;vertical-align:top}optgroup{font-weight:bold}input,select,textarea{outline:0}textarea,input{-webkit-user-modify:read-write-plaintext-only}input::-ms-clear,input::-ms-reveal{display:none}input::-moz-placeholder,textarea::-moz-placeholder{color:#999}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999}.placeholder{color:#999}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}h1,h2,h3,h4,h5,h6,p,figure,form,blockquote{margin:0}ul,ol,li,dl,dd{margin:0;padding:0}ul,ol{list-style:none outside none}h1,h2,h3{line-height:2;font-weight:normal}h1{font-size:18px}h2{font-size:16px}h3{font-size:14px}i{font-style:normal}*{box-sizing:border-box}.clearfix::before,.clearfix::after{content:"";display:table}.clearfix::after{clear:both}

.content {
    width: 700px;
    max-width: 100%;
    margin: 0 auto;
    background: #fff;
}

body {
    background: #e6e6e6;
}

.cmnt_item {
    clear: both;
    *zoom: 1;
    padding: 0 0 12px 48px;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
}

.cmnt_item:last-child {
    border-bottom: none;
}

.cmnt_top {
    clear: both;
    height: 30px;
    line-height: 30px;
    font-size: 13px;
    color: #00a0fe;
    margin: 14px 0 -8px -38px;
    position: relative;
}

.cmnt_base .cmnt_top {
    height: 40px;
    line-height: 24px;
    font-size: 12px;
    margin: 0 0 2px;
    color: #333;
}

.cmnt_top span:first-child {
    display: block;
    color: #3990e6;
    position: relative;
    padding-left: 38px;
    background: url("img.alicdn.com/imgextra/i2/2684310334/TB2D1lcoipnpuFjSZFkXXc4ZpXa_!!2684310334.png"!comment! ) no-repeat;
    background-size: 100px auto;
    background-position: 0 -336px;
}

.cmnt_top .cmnt_source {
    display: block;
    color: #999;
    font-size: 10px;
    height: 16px;
    line-height: 16px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden
}

.cmnt_top .cmnt_nick {
    display: block;
    height: 20px;
    line-height: 20px;
    font-style: normal;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden
}

.cmnt_top .cmnt_nick em {
    display: inline-block;
    font-size: 10px;
    color: #aaa;
    margin-left: 4px;
    font-style: normal
}

.phone {
    display: inline-block;
    vertical-align: middle;
    width: 0;
}

.cmnt_top .cmnt_time {
    display: block;
    height: 14px;
    line-height: 14px;
    font-size: 10px;
    color: #999;
    font-style: normal;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden
}

.cmnt_base .cmnt_top span {
    padding-left: 0;
    background: none;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden
}

.cmnt_top span img {
    position: absolute;
    left: -10px;
    top: 0;
    width: 40px;
    height: 40px;
    -moz-border-radius: 100%;
    -webkit-border-radius: 100%;
    border-radius: 100%;
}

.cmnt_top code {
    font-size: 10px;
    color: #999;
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 24px;
    line-height: 24px;
    width: 45px;
    text-align: right;
}

.cmnt_top .editor {
    font-size: 9px;
    font-style: normal;
    line-height: 19px;
    padding: 0 10px 1px 21px;
    border: 1px solid #fe7358;
    border-radius: 10px;
    color: #fe7358;
    margin-left: 10px;
    background: url("img.alicdn.com/imgextra/i2/2684310334/TB2D1lcoipnpuFjSZFkXXc4ZpXa_!!2684310334.png"!comment! ) no-repeat;
    background-size: 100px auto;
    background-position: 9px -539px;
}

.cmnt_base .cmnt_top code {
    font-size: 12px;
    color: #8b8b7e;
    top: 7px;
    width: 30px;
    text-align: center;
}

.cmnt_text {
    font-size: 15px;
    line-height: 20px;
    text-align: justify;
    color: #333;
    padding: 2px 0;
    word-break: break-all;
    word-wrap: break-word;
    margin-top: 2px;
    padding-right: .5rem;
}

.cmnt_text a {
    margin-left: 10px;
    color: #5494EA;
    font-size: 12px;
}

.cmnt_op_bottom {
    clear: both;
    font-size: 10px;
    margin-top: 8px;
    margin-bottom: 4px;
    position: relative;
    color: #aaa
}

.cmnt_op_bottom_times {
    float: left;
    line-height: 16px;
    font-size: 12px;
}

.cmnt_op {
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 16px;
    line-height: 16px;
    text-align: right;
    overflow: visible;
}

.cmnt_op_bottom_report {
    float: left;
    line-height: 16px;
    padding-left: 12px;
    color: #aaa;
}

.cmnt_op_bottom_report.on {
    color: #d2d2d2;
}

.cmnt_op a.good {

    /*tpa=https://img.alicdn.com/imgextra/i2/2684310334/TB2D1lcoipnpuFjSZFkXXc4ZpXa_!!2684310334.png*/
    color: #999;
    background-position: 0 -105px;
    font-size: 12px;
    position: relative;
    padding-right: 10px;
}

.cmnt_op a.good span {
    vertical-align: middle;
}

/*.cmnt_op a.good::after {
width: 1px;
content: '';
display: inline-block;
height: 14px;
background: #dfdfdf;
position: absolute;
right: -1px;
top: 1px;
}*/
.cmnt_op a.good.on {
    background-position: 0 -136px
}

.cmnt_op a.cmntico {
    padding-left: 22px;
    color: #aaa;
    margin-left: 10px;
    background-position: 0 -69px;
    font-size: 12px;
    position: relative;
    padding-right: 5px;
}

.cmnt_list {
    padding: 10px;
}

.content img.like {
    width: 20px;
    margin-right: 3px;
}

.popular-review {
    border-bottom: 2px solid #f2f2f2;
    font-size: 25px;
}

.comment-btn {
    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;
    cursor: pointer;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    border-radius: 4px;
    border: 1px solid transparent;
    display: block;
}

.nickname-box, .nickname-box, .comment-box, .select-avatar {
    margin-bottom: 10px;
}

.comment-box {
    width: 100%;
    height: 8em;
    padding: 5px;
}

.nickname-box {
    padding: 5px;
    margin-right: 10px;
}

.select-avatar {
    margin-top: 10px;
}

.select-avatar li img {
    width: 41px;
    height: 41px;
    border-radius: 100%;
    border: 1px solid #fff;
}

.select-avatar li.on img {
    border-color: red;
}

.select-avatar li {
    float: left;
    margin-right: 5px;
}

.select-avatar input {
    display: none;
}

.nickname-ts {
    vertical-align: super;
}

.comment-ts {
    display: block;
    margin-bottom: 10px;
}
经验PHPfile_get_contentsjson_encodefile_put_contents点赞评论TXTjson_decode
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/4969/(转载时请注明本文出处及文章链接)

评论 (0)