hi everyone i have made 3 stylesheets for different looks for my website i want to load/ change the stylesheet if the user selects the dropdown option and cliks update button heres my code for drop down

<label>Select Theme:</label>
<select name="theme" value="<?php echo $theme; ?>">
<option value="Default">Default</option>
<option value="Dark">Dark</option>
<option value="White">White</option>
</select>

any kind of help will be appreciated

Dani AI

Generated

Quick diagnosis for : when the theme flips immediately in the browser but reverts after pressing Update the server-side flow that persists and re-applies the choice is not matching the client-side value. Common causes are: the submitted value doesn't match what's stored/expected (case/format mismatch), the processing script updates the wrong record or runs after the header/output flow, or the theme resolver runs before the saved preference is read. Both the JS approach () and the persistence idea (, ) are valid — the missing link is consistent, early resolution and safe validation.

Practical checklist to fix and debug

  • Ensure the select element actually submits the theme name (options should carry normalized values that map directly to stored names).
  • Validate the posted value against a small whitelist before saving (prevents path traversal).
  • Persist the choice where it belongs: session/cookie for guests, database for logged-in accounts; consolidate read/write logic in one include that runs before any HTML output (so pre-header can use the resolved theme).
  • If the update script echoes output before doing a redirect or setting headers/cookies, move persistence to happen before any output or use output buffering.
  • Use browser DevTools to confirm the POST payload and that the DB (or cookie) was updated, then view the resulting page source to confirm the theme variable was applied.

Maintainability tip (modern): rather than shipping many full stylesheets, keep a small base stylesheet and switch a single theme class on the root element, then override colors with CSS custom properties. Example pattern:

:root { --bg: #fff; --text: #222; }
.theme-dark { --bg: #111; --text: #eee; }
body { background: var(--bg); color: var(--text); }

This reduces duplication, avoids cache headaches, and makes server-side persistence trivial (output class="theme-dark" into the HTML). Also keep a small mapping table (stored-name → filename/class) so stored values are stable and safe.

Recommended Answers

All 10 Replies

Using javascript:

<head>
<!-- You must have the id set in the next line -->
<link id="stylesheet" rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript">
function switchStyle(el){
    //get selected theme
    var styleSheet = el.options[el.selectedIndex].value;
    //apply the new style using id set earlier.
    document.getElementById('stylesheet').href = styleSheet;
}
</script>

<body>
<!-- (this) refers to the select element -->
<select id="theme" onchange="switchStyle(this)">
<!-- value corresponds to stylesheet filename --> 
<option value="default.css">Default</option>
<option value="dark.css">Dark</option>

In addition you can use alternate stylesheets, which are available also from the browser tools:

<link href="/styles/default.css" rel="stylesheet" title="default style" />
<link href="/styles/dark.css" rel="alternate stylesheet" title="dark style" />
<link href="/styles/white.css" rel="alternate stylesheet" title="white style" />

http://www.w3.org/Style/Examples/007/alternatives.en.html

To update you can set a cookie to save the CSS to load when visiting the website, for example:

<?php

$style = false;
$array_styles = array('default','dark','white');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if(isset($_POST['theme']))
    {
        $time = time()+(60*60*24*7); # a week from now
        $value = in_array($_POST['theme'],$array_styles) ? $value : 'default';

        setcookie("Theme", $value, $time, "/", "mywebsite.tld", false);
        $style = $value;
    }
}

if(isset($_COOKIE['Theme']))
{
    $style = in_array($_COOKIE['Theme'],$array_styles) ? $_COOKIE['Theme']:'default';
}

echo '
    <link rel="'.($style == 'default' || $style === false ? '':'alternate ').'stylesheet" href="/styles/default.css" />
    <link rel="'.($style == 'dark' ? '':'alternate ').'stylesheet" href="/styles/dark.css" title="dark style" />
    <link rel="'.($style == 'white' ? '':'alternate ').'stylesheet" href="/styles/white.css" title="white style" />
';
?>

I didn't tested the code but it should work. More info about setcookie(): http://php.net/manual/en/function.setcookie.php

I only noticed afterwards that the title said 'using PHP':

<?php
//check to see if the form was submitted
if(isset($_POST['submit'])){
    $theme = $_POST['theme'];//set to selected theme
} else { 
    $theme = "default.css";//set to default
}
?>
<html>
<head>
<!-- use PHP to echo the location of the stylesheet -->
<link id="stylesheet" rel="stylesheet" type="text/css" href="<?php echo $theme; ?>" />


<!-- The action of the form will default to self -->
<form method="post">
<select name ="theme">
<option value="default.css">Default</option>
<!-- The PHP code in next part would be better in a separate function -->
<!-- It sets the dropdown to selected on the currently selected theme -->
<option value="dark.css"<?php if ($theme == "dark.css") echo " selected"; ?>>Dark</option>
</select>
<input type="submit" name="submit" />

Learn, don't just copy :)

actually i am using various stylesheets and i have the stylesheets in pre-header.php
which i have included in this page.. so should i set is in that file?? will that be ok??

here is the complete code i should show that i well..

<?php include("../includes/config.php"); ?>
<?php
 if ($_SESSION["isadmin"])
   {

   $con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db($dbname, $con);

$result = mysql_query("SELECT * FROM setup WHERE (id=".$_SESSION["id"].")");
    while($row = mysql_fetch_array($result))
    {
       $title = $row['title'];
       $theme = $row['theme'];
    }
mysql_close($con);
?>

<!DOCTYPE HTML>
<html>
<head>
<?php include("../includes/pre-header.php");?>
<script type="text/javascript" src="../javascript/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="../javascript/jQuery.validity.min.js"></script>


<script type="text/javascript">
$(function() {
                $("form").validity(function() {
                    $("#title")
                        .require("This filed must be Filled!!")
                });
            });
        </script>
<title>Admdin Setup</title>
</head>
<body>
<div class="container">
<?php include("../includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<div id="maincontent">
<?php include("includes/aside.php"); ?>
<br /><br />
<div class="span-18 last">
    <h2 class="alt">Customize</h2>
<?php
  }
}
?>
<form id="form" method="post"  action="setup-action.php" enctype="multipart/form-data" >
<label for="title">Title Of Your Organization:</label>  <input id="title" type="text" name="title" class="text" value="<?php echo $title; ?>" /> <br /> <br />
<label>Select Theme:</label>
<select name="theme" value="<?php echo $theme; ?>">
<option value="Default">Default</option>
<option value="Dark">Dark</option>
<option value="White">White</option>
</select>
 <br /> <br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<label>Choose a file to upload:</label> <input name="uploadedfile" type="file" /> <br /> <br />
<input type="submit" name="Upload" class="button"  value="Upload" />
</form>
</div>
</div>
<?php include("../includes/footer.php"); ?>
</div>
</body>

</html>
<?php
    }
    else
    {
        header("Location: ".$fullpath."login/unauthorized.php");

    }
?>

setup-action.php

<?php include("../includes/config.php");?>
<?php
$target_path = "../graphics/logo.jpg";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
}
else
{
    echo "There was an error uploading the file, please try again!";
}
?>
<?php
$title=$_POST["title"];
$theme=$_POST["theme"];
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db($dbname, $con);
$result=mysql_query("SELECT * FROM setup WHERE id=".$_SESSION['id']);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0)
{
   {
mysql_query("UPDATE setup  SET title='".$title."' , theme='".$theme."'WHERE id=".$_SESSION['id']);
 header("Location:setup.php?status=1");
    }
}
else {
    header("Location:setup.php?status=2");
}
mysql_close($con);
?>

@adam the method is much easier with javascript i think i should use javascript to change themes... i have almost no idea of javascript, i just can add JS plugins and modify them :D

i have used the first method but it changes to default as i press update button otherwise when i select dark it immediately loads but when i press update it again sets to default...

and thanx for such a good responce :)

Member Avatar for Member #120589

You may find some sites rubbish the js approach. That may be from a while ago when js was not as ubiquitous as today. Due to that, I used to employ cereal's alternate stylesheet method. This still has some advantages - e.g. browser options. Although the js method may mean that you don't need a refresh/redirect.

Question - are the stylesheets radically different (e.g. layout) - or are they just colour swatches?

yeah the style sheets are change in colors and fonts and the a little bit of button styles are different.

i am serching for so long but didnt get any satifactory resource..

It does look better when the stylesheet changes immediately, but the choice will be lost when the page is reloaded, unless the choice is saved somehow.
You seem to be storing the choice in a database, but a database call for every page load solely to determine the theme is a bit excessive I feel.
The better way is to save the users choice in a session cookie as Cereal has demonstrated.
The only issue I had with this is the browser caching the stylesheet and using an 'old' choice to style the page, but this may have just been with Jquery Mobile.

Member Avatar for Member #120589

If you have multiple stylesheets loaded at one go, the alternate method gets a bit trickier, unless you use the @import method.

I'm assuming then that you have a main stylesheet and then secondary ones for the 'choice'. I don't think it makes much sense to have loads of 'full' ones, as this can be a pain for maintainability. With the added complexity of media queries (don't know if you're using them), you need to take time to plan this out properly. Rushing into it can cost a lot of time (I know from experience!).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.