dtby67541 2015-03-07 17:54
浏览 42
已采纳

菜单和PHP GET CSS选择器附带的CSS文件

I need visitors to change theme colors and background with a simple drop down menu theme selector. The select menu will send the form to index.php with a GET string ?theme=choice and PHP will take this GET and convert it to the site's css theme. I have 5 different CSS files (themes).

The select menu is done, but now I need PHP to handle the form in a correct and safe way. I do not know if Cookies are a good way but many says cookies are not a good idea so my idea is to maybe just add the ECHO theme and GET theme to all pages.

Here is what I have but is not working. I do not know how to make it better any ideas and help are welcome.

<head>
<?php
$theme = $_GET['theme'];
$security = mysqli_real_escape_string($theme); 
//don't know if needed because database will not be used for this

$onlynumbersandletters = preg_replace('/[^A-Za-z0-9\-]/', '', $security);
//allow only letters and numbers for more safety is needed ? 
// No database used but can someone hack a GET for this like in MySQL ?

//CODE
if(!empty($_GET['theme'])){
     echo '<link rel="stylesheet" type="text/css" href="css/default.css" />';
}

else {
     echo '<link rel="stylesheet" type="text/css" href="css/$onlynumbersandletters.css" />';
}

?>
<!-- other elements in head -->
</head>

I am new to PHP, the code I don't know if it is safe or can be improved but I dont get the correct theme when changing from select menu.

Any ideas ?

  • 写回答

1条回答 默认 最新

  • duangaixing1509 2015-03-07 17:59
    关注

    Printing variable into string works only if the string is in double quotes. Your is in single hence $onlynumbersandletters wont print out. It should look like this: echo '<link rel="stylesheet" type="text/css" href="css/'.$onlynumbersandletters.'.css" />';

    Cookies to store this are fine. And for your security concerns. If you plan to use that variable only for choosing css there is not much harm that can be done by attacker. But if you must, you could check if $theme is same as one of your css files and if not then show default template.

    $dirty = isset($_GET['theme']) ? $_GET['theme'] : 'default';
    $theme = preg_replace('/[^A-Za-z0-9\-]/', '', $dirty);
    if (file_exists("./css/" . $theme . ".css")) {
        echo '<link rel"stylesheet" type="text/css" href="css/'.$filename.'.css" />';
    } else {
        // what to do if file is not on disk?
    }
    

    The regex replace is there for removing slashes to prevent finding out what css files are on server outside the ./css directory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀