Custom User CSS in PHP? - 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?

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:
Racecar
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.

You can store information about style in cookies, or in database if users are regitered. And then depending on value add required css file on page with php.

Depending on how your pages are rendered it might be best to store the theme in a cookie once a theme has been selected otherwise you need to append ?theme=racecar to every link on your page.
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">

I've also seen it done with javascript.
Same basic idea as a few other answers: you write the chosen style to a cookie, and then read that when the page loads to determine which stylesheet to load.
With javascript, you have the added benefit of being able to switch styles without reloading the page, and if you set up your css nicely, you can switch something like the body's id or class and have a new style without having to download a new stylesheet, so the style-switch happens almost instantly.
Very sweet effect, good luck with the implementation.

Related

PHP - display remote page's content in full

I need to fetch a remote page, modify some elements (using 'PHP Simple HTML DOM Parser' library for that) and output modified content.
There's a problem with remote pages that don't have full URLs in their source, so CSS elements and images are not loaded. Sure, it doesn't stop me from modifying elements, but the output looks bad.
For example, open https://www.raspberrypi.org/downloads/
However, if you use code
$html = file_get_html('http://www.raspberrypi.org/downloads');
echo $html;
it will look bad. I tried to apply a simple hack, but that helps just a little:
$html = file_get_html('http://www.raspberrypi.org/downloads');
$html=str_ireplace("</head>", "<base href='http://www.raspberrypi.org'></head>", $html);
echo $html;
Is there any way to "instruct" script to parse all links from $html variable from 'http://www.raspberrypi.org'? In other words, how to make raspberrypi.org to be the "main" source of all images/CSS elements fetched?
I daon't know how to explain it better, but I believe you got an idea.
I just have tried this on local, and I've noticed(in the source code) the link tags in the HTML are like this:
<link rel='stylesheet' href='/wp-content/themes/mind-control/js/qtip/jquery.qtip.min.css' />
It obviously requires a file that should be in my local directory (like localhost/wp-content/etc.../).
The href of the link tags must be something like
<link rel='stylesheet' href='https://www.raspberrypi.org/wp-content/themes/mind-control/js/qtip/jquery.qtip.min.css' />
So what you probably want to do is find all link tags and add in their href attribute "https://www.raspberrypi.org/" in front of the rest.
EDIT: Hey I've actually made the style work, try this code:
$html = file_get_html('http://www.raspberrypi.org/downloads');
$i = 0;
foreach($html->find('link') as $element)
{
$html->find('link', $i)->href = 'http://www.raspberrypi.org'.$element->href;
$i++;
}
echo $html;die;
Since only Nikolay Ganovski offered a solution, I wrote a code which converts partial pages into full by looking for incomplete css/img/form tags and making them full. In case someone needs it, find the code below:
//finalizes remote page by completing incomplete css/img/form URLs (path/file.css becomes http://somedomain.com/path/file.css, etc.)
function finalize_remote_page($content, $root_url)
{
$root_url_without_scheme=preg_replace('/(?:https?:\/\/)?(?:www\.)?(.*)\/?$/i', '$1', $root_url); //ignore schemes, in case URL provided by user was http://domain.com while URL in source is https://domain.com (or vice-versa)
$content_object=str_get_html($content);
if (is_object($content_object))
{
foreach ($content_object->find('link.[rel=stylesheet]') as $entry) //find css
{
if (substr($entry->href, 0, 2)!="//" && stristr($entry->href, $root_url_without_scheme)===FALSE) //ignore "invalid" URLs like //domain.com
{
$entry->href=$root_url.$entry->href;
}
}
foreach ($content_object->find('img') as $entry) //find img
{
if (substr($entry->src, 0, 2)!="//" && stristr($entry->src, $root_url_without_scheme)===FALSE) //ignore "invalid" URLs like //domain.com
{
$entry->src=$root_url.$entry->src;
}
}
foreach ($content_object->find('form') as $entry) //find form
{
if (substr($entry->action, 0, 2)!="//" && stristr($entry->action, $root_url_without_scheme)===FALSE) //ignore "invalid" URLs like //domain.com
{
$entry->action=$root_url.$entry->action;
}
}
}
return $content_object;
}

How to change css based on url

I have a site that I want the user to be able to change the background image and some other css elements. The way I have attempted to do it is be having multiple html pages that the user can change via a dropdown and reload the page.
example:
href 1 = index.html
href 2 = red.html
href 3 = blue.html
Each page is identical and all point to the same stylesheet (style.php), but I want the linked stylesheet elements to change based on the url selected by the user.
So style.php starts like this
<?php
header("Content-type: text/css; charset: UTF-8");
include 'blue.php';
?>
body {
background: url(../images/backgrounds/<?php echo $background; ?>.jpg) no-repeat;
background-attachment: fixed;
}
Each html page has a matching .php page that defines each variable for the background.
So what I need is a way of selecting include 'blue.php' if the user is on blue.html. I could just use different style sheets but that would get cumbersome when altering the css.
Is there a way of doing this with php case based on url?
Lets say you have three themes:
Hot (red)
Cold (blue)
Neutral (default)
Create a class and theme for each one in CSS. E.g
body.hot
{
/*Set Base Theme details here, including background*/
}
body.hot p
{
/*Styles for hot paragraphs*/
}
/*etc*/
body.cold
{
/*Set Base Theme details here, including background*/
}
body.cold p
{
/*Styles for cold paragraphs*/
}
/*etc*/
Now use a session variable to hold the users choice and then add a class as required to the body tag:
$bodyClass = "";
switch($_SESSION['bodyClass']) {
case "hot":
break;
case "cold":
$bodyClass= "class='cold'";
break;
default:
$bodyClass = "";
}
Now insert that into the body tag
<body <?=$bodyClass ?> >
Why not use a $_SESSION variable for the user's background choice instead of having multiple HTML pages? That way, you could avoid duplicating code.
If you wanted to try this route, you could include switch.php in your stylesheet instead of include blue.php, where switch.php checks which background to apply:
<?php
// switch.php
switch($_SESSION['background']) {
case "red":
// apply red background
break;
case "yellow":
// apply yellow background
break;
default:
// apply blue background
}
?>
I have a site where the user can edit the color/ font-size and font type and i'm saving the values in my db.
Only the editable elements in my site are in a php called file "style.php" like this (no header or anything):
.main-header{ background: none repeat scroll 0% 0% <?php echo $edge_background ?> }
.sub-menu .arrow{ border-bottom: 9px solid <?php echo $edge_background ?> }
In my header i have a sql that check if the user have any value in my db and, if it does, include that file like this.
<head>
<!-- your stuff -->
<?php
//after sql check with results
$edge_background = "my value";
$color2 = "my value";
?>
<style type="text/css">
<?php include('styles.php') ?>
</style>
</head>
I dont know if that is the best way, but works fine and dont need to create alot of files.
In your case the value will change with the url. You can just check the url and then give a value to your styles with $_SERVER['SERVER_NAME'] and $_SERVER['REQUEST_URI']

Insert CSS in PHP if statement

I am using PHP to determine if a user is on a mobile device or desktop browser. Right now I have the statement set to echo a "yes" or "no." Those are both functioning correctly. However, I want to add certain CSS code if the device is mobile and certain CSS code if it is not. Is this possible?
Here is an example:
$ismobile = check_user_agent('mobile');
if($ismobile) {
<div id="slider1">
Sample Text
</div>
} else {
<div id="slide2">
Sample Text 2
</div>
Thanks!
$ismobile = check_user_agent('mobile');
if($ismobile) {
?><link rel="stylesheet" type="text/css" href="mobile.css">
<?php
} else {
?><link rel="stylesheet" type="text/css" href="desktop.css">
<?php
}
Yes, just like you echo "yes" and "no", you can echo your CSS styles inside a HTML style tag, or, even better, load a CSS file (<link rel="stylesheet" type="text/css" href="mystyle.css">).
You can put a class on your body like <body class="mobile">
and then use css to target specifically the mobile or not
.mobile #mydiv {background:red}
There are a few ways of doing this. I would first look into media queries because it is a bit of a neater solution and means you dont need to mix in php.
However the quick way would be
<?php
$ismobile = check_user_agent('mobile');
if($ismobile) {?>
<div id="slider1"> Sample Text</div>
<?php } else { ?>
<div id="slide2">Sample Text 2</div>
<?php } ?>
You could add two different style sheets:
<link rel="stylesheet" type="text/css" href="<?php echo check_user_agent('mobile') ? 'mobile' : 'desktop'; ?>.css">
Or just add a class to the body tag:
<body class="<?php echo check_user_agent('mobile') ? 'mobile' : ''; ?> another-body-class">
But you really should be using CSS Media queries which bases appearance off of screen resolution not the User Agent screen.
$ismobile = check_user_agent('mobile');
$style = $ismobile ? 'mobile' : 'notmobile';
echo '<div id="slider1" class='.$style.'>
Sample Text
</div>';
While the other replies work, I like to slimline code, so I'd stick it on 2 lines and be done with it.
$ismobile = check_user_agent('mobile') ? 'mobile' : 'main' ;
echo '<link rel="stylesheet" type="text/css" href="' . $ismobile . '.css">';
The logic behind it is simple. You have 2 stylesheets, named main.css for the main template, while mobile.css is for the mobile layout.
With that in mind, $ismobile always returns true or false, ending in mobile.css or main.css, depending on return value.
As you will ALWAYS catch one of the 2 (true or false), you will always have a value for the included stylesheet.
The end result is that you have 2 stylesheets, rendering the need to have 2 divs, which duplicated the code at html level, since #slider can be defined with 2 separate sets of attributes in each, which means #slide2 isn't needed.

Replace CSS file if is specific subdomain, using preg_match

Regular Expressions are still a stone in my boot. Can you help me, guys?
I have this piece of code for a hook in a CMS. Actually it is the whole code enclosed in the function to be excecuted by the main code.
if (preg_match('#^/member/helpdesk/index.*#i', $_SERVER['REQUEST_URI'])) //do it only for specific url
{
$event->replace('#(<h1>Tickets.*</h1>)#i', '$1<div>Some content</div>');
}
But what I really want is to check if the pages belongs to subdomain member.site.com, find the <link rel="stylesheet" href="http://site.com/orange.css"/> and replace orange.css by blue.css
Thank you :)
I mean, at the core I think you're trying to do this:
$str = '<html><head><link rel="stylesheet" href="http://site.com/style.css"/></head></html>'
if (preg_match('#member\.site\.com#i'), $_SERVER['HTTP_HOST'])){
$str = preg_replace('#http://site\.com/style\.css#', 'http://site.com/style-member.css', $str);
}
But perhaps you should consider how whatever it is you're trying to replace is being generated in the first place? Perhaps this is a check that could be placed at that location? Additionally, if you're going to be modifying an html document, I highly suggest using a parser of some kind. If you're going to do the first, maybe something like this:
$head = '<head><link rel="stylesheet" href="http://site.com/style';
if (preg_match('#member\.site\.com#i'), $_SERVER['HTTP_HOST'])){
$head .= '-member';
}
$head .= '.css"></head>';
But if you insist on parsing an html document:
$str = '<html><head><link rel="stylesheet" href="http://site.com/style.css"/></head></html>'
$dom = new DOMDocument();
$dom->loadHTML($str);
if (preg_match('#member\.site\.com#i'), $_SERVER['HTTP_HOST'])){
$links = $dom->getElementsByTagName('link');
foreach ($links as $link){
$attr = $link->attributes;
if ($attr
&& $attr->getNamedItem('rel')->nodeValue == 'stylesheet'
&& $attr->getNamedItem('href')->nodeValue == 'http://site.com/style.css'){
$attr->getNamedItem('href')->nodeValue = 'http://site.com/style-member.css'
}
}
}
$str = $dom->saveHTML();
If you want to check full domain name use
if( strtolower($_SEVER['HTTP_HOST'])=='member.site.com' ){
// other stuff
}
if you need to check it with REQUEST_URI than
if( preg_match('#^/member#i',$_SERVER['REQUEST_URI']) ){
// other stuff
}
to check hostname from full url
if( preg_match('#^(?:http[s]*://)?([^/]+)#i',$url) ){
// other stuff
}
Note: Remember if there is really one line this will work with catching the beggining of line
preg_match('#^/member/#i','/member/blahstuftuff/member/member/member/me?user=amigo&dir=mber/member')
You can test regular expression here: RegExp online version
EDIT
If you want to change css when the user is in member site and if is logged in a session, than just set:
$_SESSION['member']=true; when logins,
and do this in the part of the page (header or wherever you plan to write the css file):
USING request uri that starts with '/member' :
echo '<link rel="stylesheet" href="http://site.com/'.(preg_match('#^/member#i',$_SERVER['REQUEST_URI'])==true&&$_SESSION['member']==true?'blue.css':'orange.css').'"/>';
USING member domain name 'member.site.com' :
echo '<link rel="stylesheet" href="http://site.com/'.(strtolower($_SEVER['HTTP_HOST'])=='member.site.com'&&$_SESSION['member']==true?'blue.css':'orange.css').'"/>';
If you want blue.css to be seen by even guest users that are not logged in than just remove the session variable comparison!

Change background color of a page using php

I have a standard html page so:
<html>
<head>..
.
..
and so on
and i have a php script linked to that html page with:
if blablabla {
change background color;
}
does anyone know how to change the background color of my page if the conditions in the if statement are met?
I hope i made this clear, if not, please say which bit is unclear.
Thanks for any help in advance
put your <body> tag inside the if else
if blablabla {
echo '<body style="background-color:white">';
}
else {
echo '<body style="background-color:orange">';
}
It's not necessarily great practice, but it should get the job done:
if ( your_conditional ) {
$styleBlock = sprintf('
<style type="text/css">
body {
background-color:%s
}
</style>
', $yourColor);
echo $styleBlock;
}
One good (?) thing about this is that with this technique, you can put your if statement anywhere - it'll act on the body tag regardless of where you put it.
One caution: if you have additional style rules for the body tag's background color farther down your page, those will take precedence over the one from your if statement.
here is code that i whant to change background of body
<body bgcolor="<?php echo $name2; ?>">

Categories