【问题标题】:PHP - Loading CSS using cookie, but cookie isn't being read?PHP - 使用 cookie 加载 CSS,但没有读取 cookie?
【发布时间】:2009-09-07 16:11:18
【问题描述】:

我目前有一个网站,用户可以在其中选择自定义主题。在他们选择主题后,会创建一个 cookie。 cookie 包含正确的数据并指向正确的 CSS 文件。出于某种原因,重新访问该站点时,未加载主题。我应该指出,我是 PHP 新手,所以这可能是一个非常容易的错误。请帮忙。谢谢。

这是我的代码:

<?php
$stylesArr = array('Default', 'Black', 'Pink', 'Green', 'Red');
if(isset($_GET['theme']) && in_array($_GET['theme'], $stylesArr)) {
    $style = 'CSS/' . $_GET['theme'] . '.css';
    setcookie("theme", $style, time()+(60*60*24*30));
} else {
    if(isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $stylesArr)) {
        $style = 'CSS/' . $_COOKIE['theme'] . '.css';
    } else {
        $style = 'CSS/Default.css';
    }
}
?>
<link rel="stylesheet" href="<?php echo $style>" type="text/css"media="screen" />

【问题讨论】:

    标签: php css cookies


    【解决方案1】:

    您正在将字符串 CSS/Default.css 放入 cookie,但随后您正在检查来自 $stylesArr 的字符串 Default。更改此行:

    $style = 'CSS/' . $_GET['theme'] . '.css';
    

    到这里:

    $style = $_GET['theme'];
    

    一切都会好的。

    另外,我必须警告您不要在您的应用程序中直接使用来自 $_GET 的数据。你永远不应该这样做,因为它会导致严重的安全问题。始终清理用户输入。

    【讨论】:

      【解决方案2】:

      尝试在 setcookie() 调用中设置 $path 参数。如果不设置,则默认为当前目录。在这种情况下,您希望 cookie 在站点范围内使用,因此请尝试以下操作:

      setcookie("theme", $style, time()+(60*60*24*30), '/');
      

      您还需要确保setcookie() 调用发生在任何其他输出之前。如果您在页面中的某些 HTML 或任何其他输出(包括空格或不在 &lt;?php ?&gt; 标记之间的任何内容)下方有此内容,则 setcookie() 将不起作用。

      【讨论】:

      • 好吧,我刚试了你说的,还确保PHP代码在最上面,但还是没有运气...
      【解决方案3】:

      您需要确保在脚本开始时已经调用了session_start()

      【讨论】:

      • 他使用的是自己的 cookie,而不是会话 cookie。这个答案是错误的。
      【解决方案4】:

      离题,但我会写成这样的代码:

      define('MONTH_IN_SECONDS', 2592000);
      $themes = array('Default', 'Black', 'Pink', 'Green', 'Red');
      $theme = reset($themes); //first value is default
      if (isset($_GET['theme']) && in_array($_GET['theme'], $themes, true)) {
          $theme = $_GET['theme'];
          setcookie("theme", $theme, time()+ MONTH_IN_SECONDS);
      } elseif (isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $themes, true)) {
          $theme = $_COOKIE['theme'];
      }
      $themeURL = 'CSS/' . $theme . '.css';
      

      【讨论】:

        猜你喜欢
        • 2015-07-13
        • 2011-10-02
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 2014-04-19
        • 1970-01-01
        • 2010-11-24
        • 1970-01-01
        相关资源
        最近更新 更多