Change CSS based on PHP string query - php

I need to change the CSS on a webpage based on a query string in the URL... but I'm new to PHP and havn't been able to find sufficient examples on how to do it.
Basically when a user clicks on a menu link, and is then sent to an "aboutUs.php" page, I need the CSS on the aboutUs.php page to change based on the string query.

If I understand what you want correctly:
if (isset($_GET['query'])){
$query = $_GET['query'];
}else{
$query = NULL;
}
Then something like this:
if ($query == 'x'){
echo "
<style>
Whatever style you need...
</style>
";
}elseif ($query == 'y'){
echo "
<style>
Whatever other style you need...
</style>
";
}else{
echo "
<style>
Whatever default style you need...
</style>
";
}
Of course you can echo stylesheet link instead of style tags, but the logic is the same.

You can change your style.css to style.php which you can load in the page as a style sheet.
You need to include a header type in your php file:
<?php
header("Content-type: text/css");
?>
and then generate the content dynamically.
In hope I didn't missunderstand the question. This can help you change the content of the css file.
If you have multiple css files and you want to import one of them depending on the parameters to aboutus.php, that's a different story.

In the head of your program (where you would include the css stylesheets) do a simple if else:
if (isset($REQUEST['query_string'])) {?>
stylesheet link
<?php } else { ?>
stylesheet link 2
<?php } ?>

You can save the selected CSS into a cookie:
if (isset($_GET['setstyle'])) {
setcookie('style', $_GET['setstyle'], time()+60*60*24*30, '/');
}
The Style can then be read like this: $_COOKIE['style'].
http://example.com/?setstyle=black -> Style is set to „black“

not very pretty solution but for example something like this would work
<? php
if($str=="main"){
echo '<link rel="stylesheet" type="text/css" media="all" href="/css/main.css" />'
}
else if($str=="other"){
echo '<link rel="stylesheet" type="text/css" media="all" href="/css/other.css" />'
}
?>
be careful with doing something like:
<link rel="stylesheet" type="text/css" media="all" href="/css/$str.css" />
it is not very secure way, unless you do for example an array with possible values, something like
$possibleCss = array("main", "other");
if(in_array($str, $possibleCss){
<link rel="stylesheet" type="text/css" media="all" href="/css/$str.css" />
}

You need to create a php file with header text/css, this file you can call with get parameters.
example:
$style = $_GET["style"];
header("Content-type: text/css");
if($style=="blue")
echo ".class{background-color:blue;}";
else
echo ".class{background-color:white;}";
Call the css with get parameters
<link rel="stylesheet" type="text/css" href="style_file.php?style=blue" />

Knowing the purpose of your question, from here, I would put all of your common css in on stylesheet, and simply call out specific display properties for the elements you care about. Make all of your elements display: none in your main stylesheet.
<link type="text/css" rel="stylesheet" href="mainStyleSheet.css" />
<style type="text/css">
<?php
if (isset($_GET['section'])){
// Sanitize
$section = preg_replace('/[^a-zA-Z]/', $_GET['section']);
echo '#' . $section . ' { display: block; }';
}
?>
</style>
In this case, section is a parameter, set to ourMisson, ourHistory, etc., called like this:
http://beta.***.com/aboutUs.php?section=ourMission

Related

How to add code to <head></head> in HTML with PHP and then display it?

I want to create a file (index.php) that will dynamically add the below code to the head of another file called (index2.php) and then display the page with the modified code.
<link rel="stylesheet" type="text/css" href="new.css">
<script src="new.js"></script>
<script>
new();
</script>
I know the way to do this without modifying the code is
include 'index2.php';
However I do not know how to add the code to the head section of index2.php
How would I go about doing this?
Maybe it's just:
index2.php:
...
<head>
<?php require("./index.php"); ?>
</head>
...
?
Put index2.php file's head tag code in a diffrent file. and then include that php file in index.php file's tag
like
index.php
include_once('siffrent_file_name.php');
....
After doing some pondering I felt like I didn't want to parse the entire HTML document, so I added a "key" to index2.php and used this code:
$file = "index2.php";
$key = "<!-- KEY -->";
$appcode = 'link rel="stylesheet" type="text/css" href="new.css">
<script src="new.js"></script>
<script>
new();
</script';
$index = fopen($file, "r") or die("Unable to open index symlink");
$code= fread($index,filesize("index2.php"));
fclose($index);
$index_app = (preg_replace ($key, $appcode, $code));
echo($index_app);

Apply css from another file to an echo statement from the ajax call

I have a registration page (say reg.php) with a form and I am using ajax for validation of the form elements (say username).
Now, if the username already exists in the db, I want to display the error message in red and if it is available I want it to be in green.
It is working if I style the echo statement like this-
echo "<span style='color:brown; font-size:14px'><b>Oophs! </b>Looks like username is already in use.</span>";
But I want to style it from an another css file. How can I do it?
if style it from an another css file
for ex this css file is style.css
write bellow line in your style.css
.error_msg {
color:brown;
font-size:14px
}
.success_msg {
color:gree;
font-size:14px
}
//load style.css on your html page
<link href="css/style.css" type="text/css" rel="stylesheet">
echo "<span class='error_msg'><b>Oophs! </b>Looks like username is already in use.</span>";
in the page on which error will be display, inside head tag add style tag as
<style>
.error {
color:brown;
font-size:14px;
}
</style>
and echo like this
echo "<span class='error'><b>Oophs! </b>Looks like username is already in use.</span>";

Including PHP script to change external CSS depending on month

I know you can change the CSS by changing the stylesheet files themselves and adding a .php extension but I need to find a way of using the PHP script on the index.php page to tell the header which stylesheet to put in to action depending on what month of the year it is.
My code at the moment is accurate to the best of my knowledge but for some reason it isn't being read in and implemented with any of the stylesheets.
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$date = getdate();
$month = $date["mon"];
$style = "style.css";
$autumn = "autumn.css";
$xmas = "christmas.css";
if($month == 10)
{
echo '<link rel="stylesheet" type="text/css" href="$autumn"/>';
}
elseif($month =="12")
{
echo '<link rel="stylesheet" type="text/css" href="$xmas"/>';
}
else
{
echo '<link rel="stylesheet" type="text/css" href="$style"/>';
}
?>
</head>
Any help would be much appreciated!
You're trying to use variables inside single quotation marks ('). That does not work, variables are only interpreted inside double quotation marks ("). Therefore, your code most proabably literally outputs
<link rel="stylesheet" type="text/css" href="$autumn"/>
The necessary code line would be (adapt accordingly for the other lines, of course):
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$autumn\"/>";
Alternatively, you could replace the escaped double quotation marks inside the HTML code with single quotation marks. Browsers don't really care about that (I'm not sure about the specification).
If you want to avoid some redundancy in your code, you could try an approach like this instead:
<?php
$style = "style"; // Set the default stylesheet name
// then check for the special cases
$date = getdate();
if ($date["mon"] == 10) $style = 'autumn';
if ($date["mon"] == 12) $style = 'christmas';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="<?php echo $style; ?>.css"/>
</head>
This may also be easier to maintain than echoing out a bunch of HTML.
If you're using a HTML5 doctype you don't need the type attribute on your link element. I thought I'd throw this approach into the pile:
switch( $month ) {
case 10:
$file = 'autumn.css';
break;
case 12:
$file = 'christmas.css';
break;
default:
$file = 'style.css';
}
<link rel="stylesheet" href="<?= $file ?>">
I think you need to try:
echo '<link rel=stylesheet" type="text/css" href="'.$style.'"/>';

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.

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

Categories