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.
Related
Hi I need to find a way to add a conditional statement that will insert a canonical tag depending on the pages URL
The canonical tag itself is fine and I presume it would be something around it like you would do with css. I know PHP can get the details of the pages URL.
<!--IF HEADER URL = "PAGE URL HERE" -->
<link rel="canonical" href="LINK HERE" />
<!--IF HEADER URL-->
This leads me to the second issue I am having.
The pages I am wanting to add a canonical tag too don't always have the same link
embassy_details.php?embassy=Afghanistan
embassy_details.php?embassy=Africa
embassy_details.php?embassy=America
what I was thinking is to put the initial conditional statement around it and then put it on all the pages which link contains (embassy_details.php) as this is what I need on it
If you need more clarity just message me.
inb4 Creating a new header file for this page is out of the question due to the previous developers methods.
EDIT
I have nearly achieved the above goal with JQuery i am jsut having problems appending. I can alert the tag but i think there is something wrong with my append statement.
$(document).ready(function(){
var l = window.location.href;
if (l.indexOf("embassy_details.php") > -1) {
$('head').append('<link rel="canonical" href="http://LINK/embassies.php" />');
};
});
You mean
if (isset($_GET['embassy'])) {
$embassy = $_GET['embassy'];
echo '<link rel="canonical" href="embassy_details.php?embassy='.$embassy.'" />';
} else {
$embassy = '';
echo '<link rel="canonical" href="embassy_details.php" />';
}
doesn't match for you?
Hi I have been working on it this morning, fresh mind because had a good sleep. The solution that worked for me was to do in in the body.php. I choose to add my statement here because of all the issues i was having with the header. What my code does is checks if the link contains embassy_details.php and then adds it to the very beginning of the header.
<?php
$link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
if (strpos($link,'embassy_details.php') !== false) {
echo str_replace('</head>', '', '<link rel="canonical" href="http://www.LINK.co.uk/embassies.php")');
}
?>
This appends it into the header for all the Embassy details ages correctly
I'm working on twitter-bootstrap based website, and decided to keep header and footer as separate php files included in each sub-page of the website. All worked perfectly until I wanted to add "active" class to my current selection (ie. page that user is currently on).
I have found this script that should work fine:
$("a").click(function() {
$(".active").removeClass("active");
$(this).parent("div").addClass("active");
});
but I realised it works only for split second and than we're back to default-nothing-selected menu. I checked the page html and class was not added. I realised it's because after redirecting to new url, new header.php is being loaded - therefore no selection is applied.
Any advice on how can I get around it?
There is one solution for this kind of scenario.
Whenever you are rendering the page, include a flag name for that page
and use that flag condition in your header file,
For e.g. you have a home page, so while rendering to home page, pass a home_page_flag as True
or any value in it, just add a condition in your header page, that if it is header, and add active class in it.
<ul>
<li <?php if ($_SERVER['PHP_SELF'] == '[this_link]') { ?>class="active"<?php } ?>>
Home
</li>
</ul>
Syntax may be wrong, as i am not a PHP guy, which this login should work in any language fixed by your friendly neighborhood PHP guy - please change out instances of [this_link] with your actual href text
Check what is being returned from the server global by just doing a test like this:
<?php echo $_SERVER['PHP_SELF']; ?>
Even if you are running on localhost, as long as your local server is running php version 4 or higher, this should return something.
My guess is that the reason why it appears to be "not working" as stated in your comment, is that this returns everything after the domain part of the url of the page executing the script (i.e., not your include but the actual page that will be returned to the user). So for example, http://example.com/foo/bar.php would return /foo/bar.php. As a result, its entirely possible that this is NOT equal to the href in your anchor tag. For example, if you're linking to a page /foo/bar.php from foo/foo.php, you could use a relative path like href="bar.php". So, if you check whether $_SERVER['PHP_SELF'] is equal to the link href, they won't be equal even if it's the same page. Make sense?
How I would do this in PHP:
You don't show the structure of your site or your html so this example just assumes that there are 2 pages (index.php and contact.php) which are both in the root folder of the server. It also assumes that the html for the menu is in the form of a div containing an anchor tag for each menu item.
<?php
$currentpage = $_SERVER['PHP_SELF'];
$home = "index.php";
$contact = "contact.php";
?>
<div class="col-sm-2<?php echo ($currentpage == '/'.$home) ? ' active' : ''; ?>">
Home
</div>
<div class="col-sm-2<?php echo ($currentpage == '/'.$contact) ? ' active' : ''; ?>">
Contact
</div>
So, what does this do?
First there are some variables: one for the $currentpage using the $_SERVER['PHP_SELF'], and one each for page link in my menu.
Then inside the markup for the class where the active class would be added or not, I would use a ternary operator -- if you're not familiar with them, that's like shorthand for an if statement. The syntax for this looks like: (the thing to check for true) ? what to do if it's true : what to do if it's not true;.
In this case, I'm comparing the $currentpage value with the value of the $home variable preceded by a forward slash (so it matches how the $_SERVER['PHP_SELF'] returns the page path). If it's true, I echo out a space plus the word active. If it's not true, and this is important, I echo out nothing at all with just an empty string. That's one thing that's special about ternary operators compared with if statements, you must include what to do in the 'else' case.
That's pretty much all there is. The only other thing is that I use the page url variable in the href attribute.
Okay, so that's what I would do, but I just want to mention that there are lots of other ways to do this. For example, you could do sort of the same thing in javascript or jQuery. In that case you'd just include a script on every page that uses window.location.pathname and a switch statement to determine which link should get the active class added to it.
I have a small script that redirects users to main site if they come from a banner on my/other remote sites.
<?
.
..
...
....
header("location:$golink");
?>
But google analytics will not show the referrer site (where the script is working) instead it shows the url where the banner is clicked. Obviously I can not keep a track of all sites where banner appears and dont want to. I want the refferer to be the site where the script is working. How do I have to use the $_SERVER['HTTP_REFERER']; in order to do this ?
GA has a method that will let you to override the default referring URL (document.referrer) with a specified value.
So if you want to keep the redirect server-side, you can append the referring URL as a query string param in your header() call, and then look for it on the target page and specify it as the referring URL.
I don't know how you are building your $golink variable, but basically you would add something along the lines of:
$golink .= "?ref=" . $_SERVER['HTTP_REFERER'];
Use a & instead of ? if there are already URL params, and the code above assumes using ref as the URL param, so use whatever var you want.
Then on your target pages, before your _trackPageview call, you would add
_gaq.push(['_setReferrerOverride', ref]);
ref would be a javascript variable with the value of the ref=xxx query string param. For some weird reason Javascript does not have a native way to grab URL param values, nor does GA provide an (exposed) solution. If you already have a solution on your pages for grabbing URL params (like something from a framework or a function you've already made) then use that. Otherwise it's pretty easy to find a javascript function that will do it for you.
There are a couple benefits to doing it this way:
You don't have to worry about the visitor seeing an interstitial page.
You don't have to worry about GA not getting a chance to fully load before redirect
You can see the referrers tied directly to your landing pages, because with the interstitial page, you will always see that interstitial page as the referrer, and will have to look at referring url reports for the interstitial page.
Yes, G.A is blind to this kind of server-side stuff. And their PHP Api is not helpful either.
However, you could have a short redirection page, holding the GA tag inside like this :
<html>
<head>
<title>A web page that points a browser to a different page after 2 seconds</title>
<meta http-equiv="refresh" content="2; URL=<?php echo $golink; ?>">
<meta name="keywords" content="automatic redirection">
<script>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))</script>
</head>
<body>
If your browser doesn't automatically go there within a few seconds,
you may want to go to
the destination
manually.
</body>
</html>
Notice the $golink variable in the meta tag.
If you use this, do not forget to replace UA-XXXXX-X by your real account number.
Credits : optimized GA tag goes to Mathias Bynens
[EDIT : javascript only version]
<html>
<head>
<title>Redirecting you...</title>
<script>var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))</script>
<script>
<!--
if (window.addEventListener)
window.addEventListener('load', function() { window.location="<?php echo $golink; ?>"; }, false);
else
window.attachEvent('onload', function() { window.location="<?php echo $golink; ?>"; });
// -->
</script>
</head>
<body>
</body>
</html>
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 */ }
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" ... />