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.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能