Welcome to WebmasterWorld Guest from 54.159.50.111

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

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

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

Junior Member

5+ Year Member

joined:Mar 19, 2010
posts: 51
votes: 0


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?
3:09 am on Sept 27, 2010 (gmt 0)

Moderator from GB 

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

joined:Jan 30, 2002
posts:4842
votes: 1


$_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.
3:16 am on Sept 27, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Mar 19, 2010
posts: 51
votes: 0


That's exactly what I was looking for, thanks man!
9:46 am on Sept 27, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 5, 2008
posts: 94
votes: 0


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