【问题标题】:Submitting and retrieving cookies in PHP在 PHP 中提交和检索 cookie
【发布时间】:2019-01-24 23:31:59
【问题描述】:

我们正在为我们的网站制作投票系统。您可以将报告发布到网站上,这些报告保存为数据文件。
当前的问题是用户可以根据需要多次投赞成票或反对票,因为没有阻止投票的障碍。我们希望用户能够投赞成票或投反对票一次。
我们正在尝试使用 cookie 来实现这一点(我知道,这不是最好的系统,因为人们只能清除 cookie,但这是一个小型学生项目,我们只需要关闭系统)。我们可以在 upvote 和 downvote 脚本中设置 cookie。我们有一个 vote cookie,它可以设置为 0-11,具体取决于用户是否投票。
但是,我们无法准确检索 cookie。当我们尝试使用$_COOKIE["vote"] 检索cookie vote 时,它没有给我们一个值。
这个cookie 没有返回值有什么原因吗?先感谢您。如果您需要,下面提供了我们所有的代码。

    <?php
    $report = $_GET["report"];

    if(!isset($_COOKIE["vote"])) {
        setcookie("vote", "0", time() + 315360000, $_SERVER['REQUEST_URI']);
        $_COOKIE["vote"] = "0";
    }

    function upvote() {
        if(file_exists("DataUploads/".$GLOBALS['report'])) {
            if($_COOKIE["vote"] == "1") { // Problem: $_COOKIE is not being compared to "1" properly, always returns false
                $filename = "DataUploads/".$GLOBALS['report'];
                $line = 3;
                $lines = file($filename, FILE_IGNORE_NEW_LINES);
                $lines[$line] = (string)((int)$lines[$line] - 1);
                file_put_contents($filename, implode("\n", $lines));
                setcookie("vote", "0", time() + 315360000, $_SERVER['REQUEST_URI']);
                $_COOKIE["vote"] = "0";
            } else {
                $filename = "DataUploads/".$GLOBALS['report'];
                $line = 3;
                $lines = file($filename, FILE_IGNORE_NEW_LINES);
                if($_COOKIE["vote"] == "-1") {
                    $lines[$line] = (string)((int)$lines[$line] + 2);
                } else {
                    $lines[$line] = (string)((int)$lines[$line] + 1);
                }
                file_put_contents($filename, implode("\n", $lines));
                setcookie("vote", "1", time() + 315360000, $_SERVER['REQUEST_URI']);
                $_COOKIE["vote"] = "1";
            }
        }
    }

     function downvote() {
        if(file_exists("DataUploads/".$GLOBALS['report'])) {
            if($_COOKIE["vote"] == "-1") {
                $filename = "DataUploads/".$GLOBALS['report'];
                $line = 3;
                $lines = file($filename, FILE_IGNORE_NEW_LINES);
                $lines[$line] = (string)((int)$lines[$line] + 1);
                file_put_contents($filename, implode("\n", $lines));
                setcookie("vote", "0", time() + 315360000, $_SERVER['REQUEST_URI']);
                $_COOKIE["vote"] = "0";
            } else {
                $filename = "DataUploads/".$GLOBALS['report'];
                $line = 3;
                $lines = file($filename, FILE_IGNORE_NEW_LINES);
                if($_COOKIE["vote"] == "1") {
                    $lines[$line] = (string)((int)$lines[$line] - 2);
                } else {
                    $lines[$line] = (string)((int)$lines[$line] - 1);
                }
                file_put_contents($filename, implode("\n", $lines));
                setcookie("vote", "-1", time() + 315360000, $_SERVER['REQUEST_URI']);
                $_COOKIE["vote"] = "-1";
            }
        }
    }

    if($_POST["upvote_x"]) {
       upvote();
    }

    if($_POST["downvote_x"]) {
       downvote();
    }
?>
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <link rel="stylesheet" href="styles.css">
        <title>View Report</title>
        <link rel="icon" href="Images/favicon.ico" type="image/x-icon">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div class="header"></div>
        <div id="navbar">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="about.html">About</a></li>
                <li><a href="submit.html">Submit</a></li>
                <li><a href="submissions.php">View</a></li>
            </ul>
        </div>
        <div id="content">
            <ul style="list-style-type: none;"> 
                <?php
                    if(file_exists("DataUploads/".$GLOBALS['report'])) { // Check if the report exists
                        echo '<h2>Report Information:</h2>';
                        $data = file("DataUploads/".$GLOBALS['report']); // Gets array of lines in file

                        $upvote_button_url = $_COOKIE["vote"] == "1"?"Images/upvote.png":"Images/upvote_noclick.png";
                        $downvote_button_url = $_COOKIE["vote"] == "-1"?"Images/downvote.png":"Images/downvote_noclick.png";

                        echo '<h3 style="display:inline">Votes: </h3><p style="display:inline" class="wordwrap">'.$data[3].'</p>';
                        if($data[4] == "demo") {
                            echo "<br>";
                            echo "This is a demonstrational report, and cannot be voted on.";
                            echo "<br>";
                        } else {
                            echo '<form method="post">';
                            echo    '<input type="image" src="'.$upvote_button_url.'" name="upvote" id="upvote" value="Upvote" onclick="changeUpvoteImage()" /><br/>';
                            echo    '<input type="image" src="'.$downvote_button_url.'" name="downvote" id="downvote" value="Downvote" onclick="changeDownvoteImage()" /><br/>';
                            echo '</form>';
                            echo '<p>If a report has or has less than -40 votes, it will be deleted.</p>';
                        }

                        if(file_exists('ImageUploads/'.pathinfo($GLOBALS['report'], PATHINFO_FILENAME))) {
                            echo '<li><img src="ImageUploads/'.$GLOBALS['report'].'" style="max-height: 600px; max-width: 700px"></li>';
                        } else {
                            echo '<img src="Images/missing.png" width="25%"><br>';
                        }
                        echo '<li><h3 style="display:inline">Location: </h3><p style="display:inline" class="wordwrap">'.htmlspecialchars($data[0]).'</p></li>';
                        echo '<li><h3 style="display:inline">Description: </h3><p style="display:inline" class="wordwrap">'.htmlspecialchars($data[1]).'</p></li>';
                        echo '<li><b><h3 style="display:inline">Urgency: </h3>';
                        if($data[2] < 30) {
                            echo "<span style='color: #1f7725'>Low</span>";
                        } else if($data[2] < 50) {
                            echo "<span style='color: #77711e'>Medium</span>";
                        } else if($data[2] < 80) {
                            echo "<span style='color: #774e1e'>High</span>";
                        } else {
                            echo "<span style='color: #771e1e'>Immediate</span>";
                        }
                        echo "</b></li>";

                        function delete() {
                            if(file_exists("DataUploads/".$GLOBALS['report'])) {
                                unlink("DataUploads/".$GLOBALS['report']); //delete file
                            }
                            if(file_exists("ImageUploads/".$GLOBALS['report'])) {
                                unlink("ImageUploads/".$GLOBALS['report']); //delete file
                            }
                        }

                        if($data[3] <= -40 && $data[4] != "demo") {
                            delete();
                        }
                    } else {
                        echo '<h1>No report found with the name "'.$GLOBALS['report'].'". Check the URL!</h1>';
                        echo '<img src="Images/missing-report.jpg" width="50%">';
                    }
                ?>
            </ul>
            <br>
            <br>
            <br>
        </div>
        <script> 
            function getUrlVars() {
                var vars = {};
                var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                    vars[key] = value;
                });
                return vars;
            }

            function getCookieValue(a) {
                var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
                return b ? b.pop() : '';
            }

            function changeUpvoteImage() {
                var img = document.getElementById("upvote");
                img.src = "Images/upvote.png";
                return false;
            }

            function changeDownvoteImage() {
                var img = document.getElementById("downvote");
                img.src = "Images/downvote.png";
                return false;
            }

            if(getCookieValue(getUrlVars("report") + "vote") == 1) {
                changeUpvoteImage();
            } else if(getCookieValue(getUrlVars("report") + "vote") == -1) {
                changeDownvoteImage();
            }
        </script>
        <script>
            if(window.history.replaceState) {
                window.history.replaceState(null, null, window.location.href);
            }
        </script>
    </body>
</html>

【问题讨论】:

  • 使用 session 代替 cookie 。某些浏览器需要很长时间才能更新或删除 cookie,但如果更改,会话会立即更新。
  • 我会使用会话,但我希望投票永久持续,而不是在用户关闭浏览器时。

标签: php cookies server backend


【解决方案1】:

使用它来设置 cookie:

setcookie("vote", "some_value", time() + (315360000 * 30), "/");

(这对我有用)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多