Custom CSS user in PHP?

I would like to add a feature to my site that will allow the user to choose between several styles. I have seen this feature on other sites. How can I do this, or can someone refer to a tutorial or guide on how to do this?

+3
source share
4 answers

To start you, you can simply make dynamic style links:

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

And specify the links that change them:

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

Assign $styleaccording to the query line on the server , it would also be a good idea to default something in case the user decides to change 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"/>

, cookie .

+5

cookie , . css php.

0

, , cookie , ?theme=racecar .

if(isset($_GET['theme']))
{
    setcookie('theme', $_GET['theme']);
    $style = $_GET['theme'];
}
else if(isset($_COOKIE['theme']))
{
    $style = $_COOKIE['theme'];
}
else
{
    $style = 'default';
}

<link href="/styles/<?php echo $style; ?>.css" rel="stylesheet">
0

javascript.

, : cookie, , , , .

With javascript, you have the added benefit that you can switch styles without reloading the page, and if you customize your css well, you can switch something like a body or class id and have a new style without loading a new stylesheet, so style switch happens almost instantly.

Very nice effect, good luck in the implementation.

0
source

Source: https://habr.com/ru/post/1716864/


All Articles