PHP - 使用下拉列表更改网站主题 [英] PHP - Using a drop down list to change site theme
问题描述
我有一个下拉列表,用户可以选择网站的主题。唯一的问题是,我不太确定如何正确加载主题,一旦他们按应用。我是PHP的新手。我知道如果我使用GET,它将传递变量通过当前页面,并将它们添加到URL的结尾。我真的想避免这样。所以,我想我的问题是,我如何避免使用GET更新主题?
I have a drop down list where users can select a theme for the site. The only problem is, I'm not quite sure how to properly load the theme once they press "Apply". I am new to PHP. I know if I use GET, it will pass the variables through a the current page and add them to the end of the URL. I would really like to avoid that. So, I guess my question is, how can I avoid using GET to update the theme? Thank you.
这是我的代码加载正确的主题:
Here is my code to load the correct theme:
<?php
$stylesArr = array('Default', 'Black', 'Pink', 'Green', 'Red');
if(isset($_GET['theme']) && in_array($_GET['theme'], $stylesArr)) {
$style = $_GET['theme'];
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';
}
}
?>
这是我的下拉列表选择主题:
Here is my drop down list to select the theme:
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<p>Site Theme:
<select name="theme">
<option value="Default">Default</option>
<option value="Black">Black</option>
<option value="Pink">Pink</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
<input type="submit" value="Apply" />
</form>
推荐答案
为$ _POST交换$ _GET。如果是我,我将发布到一个单独的文件,例如theme_manager.php然后将其存储在会话或cookie,然后重新加载其他页
Swap $_GET for $_POST. And if it were me i would either post to a separate file e.g theme_manager.php then store it in a session or cookie, then reload the other page
header("Location: xxxxx.php");
exit(); # exit is important as page needs to exit and reload for cookie to work.
希望有帮助!
您需要:
<?
$stylesArr = array('Default', 'Black', 'Pink', 'Green', 'Red');
if(isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $stylesArr)) {
$style = 'CSS/' . $_COOKIE['theme'] . '.css';
} else {
$style = 'CSS/Default.css';
}
?>
<link rel="stylesheet" href="<? echo $style; ?>">
## drop down code with form posting to theme_switch.php
theme_switch .php
theme_switch.php
<?
$stylesArr = array('Default', 'Black', 'Pink', 'Green', 'Red');
if(isset($_POST['theme']) && in_array($_POST['theme'], $stylesArr)) {
$style = $_POST['theme'];
setcookie("theme", $style, time()+(60*60*24*30));
}
header("Location: choose_style.php"); # this will reload your theme selector
exit(); # this will make sure the cookie gets loaded next time.
?>
这篇关于PHP - 使用下拉列表更改网站主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!