Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom User CSS in PHP?

Tags:

css

php

I would like to add a feature onto my site that would allow a user to choose between multiple styles. I have seen this feature on other sites. How would I go about doing this or could somebody refer me to a tutorial or guide on how this can be done?

like image 276
user Avatar asked Jun 10 '26 12:06

user


1 Answers

To start you off, you could simply make the stylesheet link(s) dynamic:

<link rel="stylesheet" href="<?=$style?>" type="text/css"/>

And provide links that change them:

<a href="/page.php?theme=racecar">Racecar</a>

On the server, assign $style according to the query string, it would also be a good idea to default to something in case the user decides to modify the URL:

<?php
    $stylesArr = array('racecar', 'magenta', 'cartman');
    if(isset($_GET['theme']) && in_array($_GET['theme'], $stylesArr)) {
        $style = $_GET['theme'] . '.css';
        setcookie("theme", $style, time()+(3600*24*30));//expires in one month
    } else {
        if(isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $stylesArr)) {
            $style = $_COOKIE['theme'] . '.css';
        } else {
            $style = 'default.css';
        }
    }
?>
<link rel="stylesheet" href="<?=$style?>" type="text/css"/>

You can propogate the user's style via the query string, cookies or sessions.

like image 71
karim79 Avatar answered Jun 12 '26 07:06

karim79