PHP form submit, force CSS reload? - php

I have a PHP form that I need to force a CSS reload once submitted. How do I do this?
Thanks!

The only way I can think of to guarantee that the CSS reloads, is to change the name of the css file.
You could create a rewrite rule that redirects all addresses of type "...mycssfile.css1234" to "...mycssfile.css" and in your php, add a random 4 digits to the end of your css file location.
Edit: To reflect the comments to this answer, you can do the following:
<link rel="STYLESHEET" href="mycssfile.css?r=<?php echo rand(1, 999999); ?>" type="text/css">
Which would force the browser to update the css page, since the address to the css file changed, although it will actually link to the same css file.

You can do it via Javascript.
<form id="form" onsubmit="cssChange()" action=".....
For example cssChange function :
function cssChange() {
var a = document.getElementsByTagName('link');
var random = Math.floor(Math.random()*11);
if(a.getAttribute('rel') == 'css')
{
a.attr('src', 'new-css.css?' + random);
}
}
And you can define .newClass class on your css file.

Is there some reason the whole page can't reset? Because if that's okay, then the form could just submit to the page itself, with an action of get, and the (dropdown|input|radio button) submitted as an argument (something like "css").
When the page loads, PHP can check for the variable:
$css = empty($_GET['css']) ? $_GET['css'] : 'default';
Then, it can echo the stylesheet's href based on that variable:
<link href="<?php echo htmlspecialchars($css, ENT_QUOTES, 'UTF-8') ?>.css" ... />

Related

Using a PHP variable in included file evaluates to NULL in included file

I am trying to process some CSS using PHP. The CSS I want to process is page-specific and so I want to set a variable in my index.php to only echo the CSS when the variable is set.
index.php
<?php
$name = 'index';
?>
<?php
include 'inc/header.php';
?>
header.php
<head>
<meta charset="utf-8">
<title></title>
<?php include 'import.php'; ?>
</head>
import.php
<link rel="stylesheet" href="css/styles.css.php" type="text/css" />
The header is properly set for this file. and the CSS is interpreted.
styles.css.php
.jumbotron {
background-image: url(../img/jumbotron.jpg);
<?php
if ($name === "index") {
echo("height: 50VH;"); /* Does not echo anything*/
}
var_dump($name); // Evaluates to NULL
?>
}
How can I make sure $name is set to it's value, as set in index.php?
EDIT: My final solution was to make an object from the stdClass and add the variables I needed as attributes to the object. putting a GET request in the link to the CSS file which was the Base64 of the JSON string of the object.
The <link> tag makes an HTTP request for a file totally independent of the PHP pages that are including each other, so $name is not available in styles.css.php.
To do it this way you need to link the style sheet something like this to pass $name as a get variable:
<link rel="stylesheet" href="css/styles.css.php?name=<?php echo $name; ?>" type="text/css" />
Then in the style sheet styles.css.php use $_GET['name']:
if ($_GET['name'] === "index") {
echo("height: 50VH;");
}
The problem is that you are linking to that styles.css.php from inside the rendered html. This means that page will be fetched in a separate request (as you can se when you inspect the page). This request never passes trough your index.php, and so the $name variable will not be set.
I would advise you to include the css in the rendered HTML inside a style block. It should be as easy as changing your import.php to this:
<style>
<?php include 'css/styles.css.php' ?>
</style>
This also has the added benefit of reducing the number of requests the browser has to make, and should therefore speed up the page.
This is btw not a very standard method of using css. I believe it would be better to add some sort of id (or data attribute) on your body tag that indicates the name of the page you are on. In the css file (that does not run trough php, just a standard css file), you could then do something like this:
.jumbotron {
background-image: url(../img/jumbotron.jpg);
}
#index .jumbotron {
height: 50vh;
}
The file styles.css.php does not know about the $name variable - that's why it is null when doing the var_dump($name). With your <link> you just output the content of your style.css.php as plain html/css. You need to do either an include_once('styles.css.php') or a require_once('styles.css.php') so that you can properly evaluate the $name variable.
You are having an HTML page generated by index.php. This tells the browser to load the external style sheet at the line <link rel="stylesheet" href="css/styles.css.php" type="text/css" />. Loading external data by the browser is a completely new request. Thus the PHP file generating the style sheet does not know anything about the variables declared in the script serving the HTML page.
Actually the variable $name is unset. Since it is given as argument by reference to var_dump (the builtin function is declared to take arguments by reference), the reference results in null.
If you want to distinguish between different style sheets in only one PHP script, append a GET parameter to the URL as query:
<link rel="stylesheet" href="css/styles.css.php?name=<?PHP echo $name;?>" type="text/css" />
Take that parameter in syles.css.php:
<?php $name = isset($_GET['name']) ? $_GET['name'] : ''; ?>

Iframe Question

If I control the content of two pages (PageA and PageB), one of which I want to load into an iframe (PageB), is there some javascript I can enter on PageB that will pull a style from the parent (PageA)? I need two style options, one for when PageB is loaded in an iframe, and one for when PageB loads on its own.
A solution I could see is loading the styles for both files from an external file, and set the src attribute of the IFrame to include a GET variable as such (rest of this example assumes a file with the name index2.php):
<iframe src="index2.php?iframe=Y" ... />
From there, towards the top of index2.php should look something like this:
<?php
if ($_GET["iframe"] == "Y") {
echo "<link href='global.css' type='stylesheet' />";
} else {
echo "<link href='specific.css' type='stylesheet' />";
}
....
?>
While Kris' solution is also valid, I wouldn't and never do rely on Javascript to work the same in all browsers, regardless of whether it's been tested or not. At least this way, you know that the file is being loaded into an IFrame.
I would do it this way: check to see if your page is loaded in a frame or not and choose your styles based on this rather than attempting to pull styles from a parent page.
You can detect if you're in a frame via this type of code:
if ( top.location.href !== window.location.href ) { /* In frame */} else { /* Not in frame */ }

Add some parameter to all urls in WordPress

How can I add some parameters to all urls on all pages in WordPress? I am working on a theme development and I need to show to a potential customer different variants of using it. So, I have different color schemes. I found a tutorial about how to get parameters from url and use them in my code. Now I easily use an url like http://proceed.skible.com/?color=magic_night to attach a CSS file with color scheme settings. It works fine but when I click any link on a demo page, it obviously doesn't apply my custom color scheme but applies the one that is saved in the settings. I think I can go this way - add ?color=magic_night or whatever color scheme I need to all links. Of course, I need to parse the links and add it right way, not just insert it at the end of every url. More than that, may be there are better ways for implementing the possibility for previewing misc features of the theme? I saw the way I described here: http://themes.mysitemyway.com/infocus/?themedemo=infocus&extracss=deep_blue. All links end with extracss=deep_blue or another theme I choose from the menu.
Thanks.
You should use PHP cookies to store the users colour preference between HTTP requests, but allow them to override it using the GET variables you are talking about:
# Get the value of color if specified on the URL (GET) or in a cookie
# If non of those place have the color, then color will be NULL
$color = isset($_GET['color']) ? $_GET['color'] : (
isset($_COOKIE['color']) ? $_COOKIE['color'] : NULL
);
# If we know what color we have and didn't just get it from a cookie
# then set a cookie with that color as its value
if ($color != NULL && isset(! $_GET['cookie'])) {
setcookie('color', $color);
}
Now that you have the $color value you can pick your stylesheet in whatever way you want to, for example:
<?php
if ($color != NULL) {
?> <link rel="stylesheet" href="<?php bloginfo('stylesheet_direcctory'); ?>/<?php print($color); ?>.css" type="text/css" /> <?php
}
?>
P.S. My PHP syntax is a bit rusty, but the concept should be all there
If I'm understanding you right, you want to use a different stylesheet based on what url parameters are passed? You can do that in the header file of your theme:
header.php:
//includes
<html>
...
<head>
...
<?
if($_GET['color'] == 'magic_night'){
?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_direcctory'); ?>/magic_night.css" type="text/css" />
<?
}
else
...
?>
...rest of the page...
bloginfo('stylesheet_direcctory') should get you to your theme directory, but I would echo it first in a test file or use a better parameter to bloginfo.

Replace page content before file loads?

I wanted to know, is there any sory of scripting that I can use so that I can simply change one little thing and then the content will change for multiple pages? Maybe PHP or the htaccess file.
What I want to do is make an "Under Construction" page for my website, that I can periodically turn on or off. Right now, the method I am using is JS, which is not too effective. What I have it doing is it will replace the body tag's content with that of the under construction pages, and then change the title to be "Under Construction". The problem with this, the function loads after the page has loaded. So I either need a JS script that will load before anything on the page does, or a php script that does something near the same thing. I also thought (if it was possible) the htaccess file would be really nice too, because I could apply it to certain directories. I know I can use the htaccess file to redirect the user (and I can do that with PHP and JS too) but I do not want to do that because I want the url be stay the same. If I were to redirect the user from page1.html to underconstruction.html, then that changes the url in the browser. I want the url to stay as page1.html for page1, page2.html for page2, and page3.html for page3... Does anyone know how I can accomplish such a task? If so, please help.
Thank you!
If you use the following snippet in an htaccess file, your url does not change but redirects:
RewriteEngine on
RewriteRule ^(.*)$ ./under_construction.html [L]
Sure thing there is lets take ux9i example and re-write it slightly:
// Set this to true to rewrite the page
var underConstruction = true;
function rewritePage(){
if (underConstruction){
document.getElementById ('entirePage').innerHTML =
"<h1>Under construction</h1>";
}
}
Test.html
<html>
<head>
<script type="text/javascript">
window.onload = rewritePage;
</script>
<title>write example</title>
<script type="text/javascript" src="UnderConstruction.js"></script>
</head>
<body>
<div id="entirePage">
<p>Some document content.</p>
</div>
</body>
</html>
This ought to do the trick, if I were you I would be using redirection instead of this, here is what I mean:
// Set this to true to rewrite the page
var underConstruction = true;
function rewritePage(){
if (underConstruction){
location.href = 'contruction.html';
}
}
Leave the html as it is. Cheers
EDIT
Here is how to do it in php, you'll make page called lets say "construction.html" , now inside of your php page at the top place this code
<?php
$redirect = 1;
if($redirect == 1){
header('Location: construction.html');
}
?>
It will directly transfer/redirect you to the construction page in case redirect is set to one .. after you're done with the construction page either remove this portion of code completely or set redirect to any other number beside 1.
Sorry I just read this part
If I were to redirect the user from
page1.html to underconstruction.html,
then that changes the url in the
browser. I want the url to stay as
page1.html for page1, page2.html for
page2, and page3.html for page3...
Does anyone know how I can accomplish
such a task?
You should let other people know when you edit your question, you should use then iframe, try to google what is iframe and how to use it. Then you can apply the same logic described above to iframes as well.
Have all your pages include this script.
UnderConstruction.js:
// Set this to 1 to rewrite the page
var underConstruction = 0;
function rewritePage ()
{
if (underConstruction)
{
document.getElementById ('entirePage').innerHTML =
"<h1>Under construction</h1>";
}
}
Test.html:
<html>
<head>
<title>write example</title>
<script type="text/javascript" src="UnderConstruction.js"></script>
</head>
<body onload="rewritePage()">
<div id="entirePage">
<p>Some document content.</p>
</div>
</body>
</html>

Switchstyle Problem in Joomla/Php/Jquery/Css

I've been developing a site (for now is here as an example: http://neurotoxine.mine.nu/gloom), and I'm getting a strange behaviour from a styleswitcher code. It's big so please be patient.
First, you may go to the site I appointed first and see it.
What you've got there, it's a joomla page, with a Jquery using
var $j = jQuery.noConflict();
in order to avoid mootools conflicts.
Then, I used these:
<? // Checks for, and assigns cookie to local variable:
if(isset($_COOKIE['style']))
{ $style = $_COOKIE['style'];
}
// If no cookie is present then set style as "red" (default):
else { $style = 'red';
}
?>
This is just for the cookie setting, if the cookie is not set then $style=red, and this variable will be appended to the CSS. Like this:
<link rel="stylesheet" type="text/css" href="<?php echo $this->baseurl ?>/templates/wh1/css/template_<?php echo $style ?>.css" media="screen" />
The first code, $this->baseurl=directory for joomla installation, in this case gloom.
The second one, echo $style, will write the cookie loaded value or the value assigned from the options, in the case you get there for first time then you'll got RED as value then, template_red.css will be the CSS for the entire site.
There's a JS, that works doing some jquery tricks:
jQuery.fn.styleSwitcher = function(){
$j(this).click(function(){
// We're passing this element object through to the loadStyleSheet function.
loadStyleSheet(this);
// And then we're returning false.
return false;
});
function loadStyleSheet(obj) {
$j('#preloader')
// Now fade in the div (#preloader):
.fadeIn(500,function(){
// The following will happen when the div has finished fading in:
// Request PHP script (obj.href) with appended "js" query string item:
$j.get( obj.href+'&js',function(data){
// Select link element in HEAD of document (#stylesheet) and change href attribute:
$j('#stylesheet').attr('href','css/' + data + '.css');
// Check if new CSS StyleSheet has loaded:
cssDummy.check(function(){
// When StyleSheet has loaded, fade out and remove the #overlay div:
$j('#preloader').fadeOut(500);
});
});
});
}
// CSS DUMMY SECTION
var cssDummy = {
init: function(){
// Appends "dummy-element" div to body:
$j('<div id="dummy-element" style="display:none" />').appendTo('body');
},
check: function(callback) {
// Checks if computed width equals that which is defined in the StyleSheets (2px):
if ($j('#dummy-element').width()==2) callback();
// If it has not loaded yet then simple re-initiate this function every 200 milliseconds until it had loaded:
else setTimeout(function(){cssDummy.check(callback)}, 200);
}
}
cssDummy.init(); }
then, I start the function in my page:
$j(document).ready(function(){
$j('#style-switcher a').styleSwitcher();
});
and I call it from a link like this:
img
Finally, the styleswitcher.php code is here:
<?php
$style = $_GET['style'];
setcookie("style", $style, time()+604800*24); // 604800 = amount of seconds in one week *4=1 month *24=1/2 year *48=1 year
if(isset($_GET['js']))
echo $style;
else header("Location: ".$_SERVER["HTTP_REFERER"]); ?>
Now, the problem is, that when I tested this in a site, everything worked fine (http://neurotoxine.mine.nu/wht/index-test.php - The links for the stylechanger are in the top and left of them says THEMES). But when I inserted the whole code in joomla template, the whole system failed. I did some fixes here and there (mainly the $j declaration) and then I realized that could be something related to the path of the templates, so I tested many types of declarations, absolute paths, relative paths, etc. and nothing happens.
Then I copied styleswitcher.php to the root of joomla (neurotoxine.mine.nu/gloom) and checked if ti would work there, and I'm getting a blank page. I clicked go-back and then WOW the stylechanger worked, but then something isn't telling where to go back to I think it could be the header("Location: ".$_SERVER["HTTP_REFERER"]); instruction, but I don't know what to change there to make it work.
Joomla gives a declaration in the header for its templates:
<base href="http://neurotoxine.mine.nu/gloom/" />
I don't know if this is doing something to the way the http_referer works, but I disabled this and the site still does the same, click a style, page blank, hit go-back and voila, the style has changed but failed to retrieve the page where I was.
Some ideas? Any help could be useful.
The Referer is only set, when you click on a link (not when you enter it directly in the adress bar). In fact the browser tells the site where the user has been before clicking on this link, so you can't trust it to 100 % (see PHP Manual). I would store the last visited page in $_SESSION and redirect to this one; and if it is empty, redirect to $this->baseurl . '/index.php'.
The base-Tag is only needed for relative links, e.g.
<a href="index.php">
or even:
<a>
Another tip: Before taking the style from the cookie, check if it exists (either hardcode all available templates or file_exists()). If not, take the default one (red).
I resolved this... the solutions were fixing three to four errors:
first of all, the cookie checker in the html should have asked if the coockie wasn't empty, no if it was SET. So:
<?php // Checks for, and assigns cookie to local variable:
if(!empty($_COOKIE['style'])) $style = $_COOKIE['style'];
// If no cookie is present then set style as "red" (default):
else $style = 'red';
?>
That was the first thing to fix.
Then this line is fixed, because the JQuery plugin asked for an ID in the header to alter. I didn't realized I haven't an ID at the link stylesheet declaration
<link id="stylesheet" rel="stylesheet" type="text/css" href="<?php echo $this->baseurl ?>/templates/wh1/css/template_<?php echo $style ?>.css" media="screen" />
In this line I also discovered that
<?php echo $this->baseurl ?>
should be replaced with the base address but, without the domain, so it should be
/gloom/templates/wh1/css/template_<?php echo $style ?>.css
Also, in the initialization of the JQuery plugin, i made a fatal mistake. I didn't changed the ID for the container of the tag that was going to be captured by the plugin. That was in part for the confusion between the ID on the header for the stylesheet and the ID on the tag container. So I used "#tselect" for the ID of a DIV and it solved the Jquery work. Besides, is mandatory to ad $j in every statement of the plugin.
$j(document).ready(function(){
$j.preloadCssImages({statusTextEl: '#textStatus', statusBarEl: '#status'});
$j("img#hhead").toggle(
function () {
$j("#headtop").slideDown();
},
function () {
$j("#headtop").slideUp();
});
$j("#tselect a").styleSwitcher(); // here is the "ID TAG".plugin() call.
});
Now, in the styleswitcher.php I used a tip someone told me about the cookie:
<?php $style = $_GET['style'];
setcookie("style", $style, time()+604800,"/"); // 604800 = amount of seconds in one week
if(isset($_GET['js'])) echo $style;
else header("Location: ".$_SERVER['HTTP_REFERER']);
?>
Did you noticed? is a simple / slash.
Now everything works fine. The stylechanger changes the styles and the JQuery effects work.
You could see it here: link text
If anyone wants the files and an explanation, send me a message.

Categories