Welcome to WebmasterWorld Guest from 54.234.63.187

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

How can I make PHP echo certain things depending on the page?

     

DigitalSky

3:05 am on Sep 27, 2010 (gmt 0)

5+ Year Member



I'm pretty new to PHP but what I'm looking to do seems like it should be pretty simple.

I have a PHP header include for all of the pages on my site. Certain pages require certain JavaScript files while others do not.

What I want to do is make some sort of if/else statements that would say something like...

IF the page equals index.php (or another page name of my choice) then insert this code... <script src="js/slider.js" type="text/javascript"></script>

ELSE insert nothing.

Does anyone know a simple way to do this?

brotherhood of LAN

3:09 am on Sep 27, 2010 (gmt 0)

WebmasterWorld Administrator brotherhood_of_lan is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



$_SERVER['REQUEST_URI'] is probably what you are after

if($_SERVER['REQUEST_URI'] == '/index.php')
{
echo '<script src="js/slider.js" type="text/javascript"></script> ';
}


A variation to consider a number of pages


if(in_array($_SERVER['REQUEST_URI'],array('/index.php','/example.php','/anotherpage.php')))
{
echo '<script src="js/slider.js" type="text/javascript"></script> ';
}


This kind of approach should be fine if you have a small number of pages.

DigitalSky

3:16 am on Sep 27, 2010 (gmt 0)

5+ Year Member



That's exactly what I was looking for, thanks man!

morehawes

9:46 am on Sep 27, 2010 (gmt 0)

5+ Year Member



One thing to note would be that if there is a query string then $_SERVER['REQUEST_URI'] would return this also - so if your request uri was index.php?arg=1 then your slider.js would not be outputted because it would not equal '/index.php'.

There are a few ways round this like checking if 'index.php' is present in the uri like this:


if(strpos($_SERVER['REQUEST_URI'], '/index.php')) {
//Output slider JS
}


Or using something like the __FILE__ magic constant [php.net...] or the parse_url() function [php.net...]

Just thought it was worth mentioning
 

Featured Threads

Hot Threads This Week

Hot Threads This Month