php to insert code in web page header- based on url

Posted on 2014-01-13
Last Modified: 2014-01-17

Is there a snippet of code that will insert some html (specifically some javascript)  into the header of a page based on the URL of the page.

For example:

if the url is the following would be inserted into the header

I like dogs

And if the url is  the following would be inserted into the header

I like cats

It would need to change dynamically.  This is, I would not want to see the following in the header if the url was

I like dogs
I like cats


Question by:Rowby Goren
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 83

Accepted Solution

Dave Baldwin earned 167 total points
ID: 39777341
I've done that on a page by page basis on a web site.  But I'm curious how you are going to get the same PHP page on different domains.
LVL 31

Assisted Solution

by:Marco Gasi
Marco Gasi earned 167 total points
ID: 39777350
Are you using Apache? If yes you can get the requested url placing this in your .htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^includes/functions\.php$ - [F]
RewriteRule ^config/const\.php$ - [F]
RewriteRule ^config/bootstrap\.php$ - [F]
RewriteRule ^(.*\.(php|htm|html))$ index.php?url=$1 [NC,QSA]

Open in new window

Then in your pages you can do this:
$url = $_GET['url'];
if (stristr($url, '')) {
   echo "I like dogs";
}elseif (stristr($url, '')) {
  echo "I like cats";

Open in new window


Author Comment

by:Rowby Goren
ID: 39777385
Hi Marco Gasi and Dave Baldwin  

I am using an interesting Joomla component called Chameleon that (among other things) switches the template based on the url.


So the template is switched.  We're on the url.   So the code, when it see that it is already of  it will insert the CAT code.

And when the switched template is on the url it will sense that -- and then put the DOG code in the header.

Chameleon has a tab where I can put php into.  So I am hoping the code I get here will take care of that.

Back to Marco Gasi's example  I will try putting your code into Chameleon's PHP tab and see what happens!  I am going to try it without modifying the htaccess code, because I am hoping that Chaneleon will take care of that issue for me.

$url = $_GET['url'];
if (stristr($url, '')) {
   echo "I like dogs";
}elseif (stristr($url, '')) {
  echo "I like cats";

Open in new window


Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.


Author Comment

by:Rowby Goren
ID: 39777398

I was ready to try the php, when I found some documentation for Chameleon. I am thinking that I need to contact the developer instead - because this may be beyond the capabilities of a question here on Experts Exchange.  Here's the documentation for the php, without knowing the inner workings of Chameleon it may be an exercise in futility here :)

Default PHP return value
PHP Help
Create some PHP code to determine which template style should be used. Once the script has decided which template style to display, "return" values as shown below. For more help and recipes, see the Chameleon and JomGenius home pages. e.g.

/* rule succeeded: */
return true;
/* rule failed: */
return false;
/* rule succeeded. Use template style 4 (Beez2 Default) and quit processing: */
return "4";
/* rule succeeded. Use template style 6 (Beez5 Default Fruit Shop), and continue to next rule: */
return "6:continue";

    return "4";
    return "6";
if ( $core_genius->inTimeSpan( "Wed 09:00 - Thu 23:00" ) )
    return true; // weekly time span
if ( $core_genius->inTimeSpan( "22:00 - 06:00" ) )
    return true;  // daily time span
if ( $core_genius->inTimeSpan( "09:30:10 - 17:15:00" ) )
     return true; // 09:30:10 to 17:15:00 daily
if ( MM_DAY_OF_WEEK == 1 )
    return "7"; // Monday is "1"
if ( MM_DAY_OF_MONTH == 1 )
    return true; // only show on 1st day of every month
if ( MM_MONTH == 5 )
    return "7"; // only show during month of May
if ( MM_YEAR == 2014 )
    return "4"; // only show during year 2014
if ( MM_DATE >= 20140101 && MM_DATE <= 20140723)
    return false; // January to July 27, 2014

if ( $fromCountryId == "US" )
    return "4";
if ( $fromCountryId == "GB" )
    return "6";
if ( $fromCountryId == "NL" )
    return "7";
if ( $fromCountryName == "New Zealand" )
    return "8";

You have access to the following PHP variables:

    $fromCountryId - the upper-case 2-letter ISO country code (e.g. GB, US, FR, DE)
    $fromCountryName - the official ISO country name
    $geoip - if you have enabled GeoLiteCity or GeoIPCity, a record containing the following items:
        $geoip->country_name - full country name, as above
        $geoip->country_code - 2-letter ISO country code, as above
        $geoip->country_code3 - 3-letter ISO country code (e.g. GBR, USA, FRA, DEU)
        $geoip->region - 2-letter code. For US/Canada, ISO-3166-2 code for the state/province name, e.g. "GA" (Georgia, USA). Outside of the US and Canada, FIPS 10-4 code, e.g. "M9" (Staffordshire, UK)
        $geoip->city - full city name
        $geoip->postal_code - For US, Zipcodes, for Canada, postal codes. Available for about 56% of US GeoIP Records. More info.
        $geoip->area_code - 3-digit telephone prefix (US Only)
        $geoip->metro_code - 3-digit DMA/Metro code (US only)
        $geoip->continent_code - Continent code, one of: AF=Africa, AN=Antarctic, AS=Asia, EU=Europe, NA=North America, OC=Oceania, SA=South America
    $Itemid - the Itemid of the main component on the page
    $option - the option of the main component on the page (e.g. com content)
    $view - the view of the main component on the page (e.g. "article")
    $id - the id of the item in the main component on the page (e.g. "24:content-layouts")
    $db - in case you want to query the database for anything (for experts!)
    $language - a lower-case language code. By default this returns the default language of the web visitor’s browser, but can alternatively return the language code of the Joomla front-end, or intelligently find the best match between a user’s browser languages and a list of languages that you provide. Typical language strings returned include: en, en-gb, en-us, fr, de and many others.
    $language_code - the 2-letter language code without region (lower case) e.g. "en"
    $language_region - if it exists, the 2-letter region code (lower case). e.g. if $language == "en-us", $language_code == "en" and $language_region == "us". Having them in separate variables like this makes it easier to put into Chameleon rules.
    $user - information about the user, if they are logged in....
        $user->id - if 0, the user is not logged in
        $user->groups - Array containing 0 or more of the following: "Public", "Registered", "Author", "Editor", "Publisher", "Manager", "Administrator" or "Super Users"
        $user->registerDate - e.g. "2007-05-17 01:25:52"
        $user->lastvisitDate - e.g. "2007-11-02 18:51:29"

Note: $fromCountryName and $fromCountryId will only be available if you have one of the "Enable GeoIP" options selected above, and if you have one of the GeoLite Country, GeoIP Country, GeoLiteCity or GeoIPCity databases installed (see Maxmind, direct GeoLite Country download, or direct GeoLite City download)

CONSTANTS: These constants can be used in your rules just like variables, except they don’t need a "$" in front of them.

    Time and Date related. These constants are calculated according to the time zone set in the time zone drop-down in Chameleon. If you choose your nearest region/city with the time zone drop-down, then the times and dates also respect daylight savings time.
        MM_DAY_OF_WEEK – 0=Sunday, 6=Saturday
        MM_DAY_OF_MONTH – 1 to 31
        MM_MONTH – 1-12
        MM_YEAR – YYYY format
        MM_HOUR – 0-23
        MM_MINUTE – 0-59
        MM_SECOND – 0-59
        MM_TIME – this is presented as a 24-hour clock number, including seconds, but without “:” characters. e.g. 10:11:59 AM = “101159”, 15:29 (3:29 PM) = “152900”. This makes it easy to use a template between two times of day, e.g. if (MM_TIME >= 101159 && MM_TIME <= 152900) return 101;
        MM_DATE – this is presented as a YYYYMMDD number e.g. 25th Dec 2008 = 20081225. This makes it easy to use a template between two dates, e.g. between 1st and 24th May 2009 (inclusive): if (MM_DATE >= 20090501 && MM_DATE <= 20090524) return "4";
    User/group related. These make it as easy as possible to make rules based on what group a logged-in user is a member of.
        MM_LOGGED_IN – true if the user is logged in, no matter what group thay are part of
        MM_NOT_LOGGED_IN – true if the user is not logged in
        MM_USER_REGISTERED / MM_USER_NOT_REGISTERED – true if the user is logged in and a member (or NOT) of the “Registered” group
        MM_USER_AUTHOR / MM_USER_NOT_AUTHOR – true if the user is logged in and a member (or NOT) of the “Author” group
        MM_USER_EDITOR / MM_USER_NOT_EDITOR – true if the user is logged in and a member (or NOT) of the “Editor” group
        MM_USER_PUBLISHER / MM_USER_NOT_PUBLISHER – true if the user is logged in and a member (or NOT) of the “Publisher” group
        MM_USER_MANAGER / MM_USER_NOT_MANAGER – true if the user is logged in and a member (or NOT) of the “Manager” group
        MM_USER_ADMINISTRATOR / MM_USER_NOT_ADMINISTRATOR – true if the user is logged in and a member (or NOT) of the “Administrator” group
        MM_USER_SUPER_ADMINISTRATOR / MM_USER_NOT_SUPER_ADMINISTRATOR – true if the user is logged in and a member (or NOT) of the “Super Administrator ” group

Open in new window

LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
ID: 39777406
I think Marco is close on this one.

The PHP switch / case construct might be the most useful.  You can examine $_SERVER['HTTP_HOST'] to determine the URL that was used to access the site.  You may want to normalize this a little bit, such as removing WWW., making it all upper-case, etc.
Then you can use switch() to choose the data elements that get put into the HTML document.  Here, we construct $var on lines 15-17 and use it in the HTML with the "short echo" notation on line 31.

<?php // RAY_temp_rowby.php

// SEE

$url = $_SERVER['HTTP_HOST'];
$url = strtoupper($url);
$url = str_replace('WWW.', NULL, $url);
$url = str_replace('.COM', NULL, $url);

    case 'CAT': $var = 'I LIKE CATS'; break;
    case 'DOG': $var = 'I LIKE DOGS'; break;
    default:    $var = 'I LIKE FISH';
?><!DOCTYPE html>
<html dir="ltr" lang="en-US">
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script type="text/javascript" src=""></script>
<title>HTML5 Page in UTF-8 Encoding</title>

Open in new window


Author Comment

by:Rowby Goren
ID: 39777427
Hmmm   Ray Marco ---

I tried putting the code into CHameleon's PHP tab and it did not have an effect.

Let's put a temporary hold on this question. I emailed the developer and let me see what he says.

I'll get back to you when he responds.


LVL 110

Expert Comment

by:Ray Paseur
ID: 39777433
Yeah, it looks like there is a lot more to it...

Author Comment

by:Rowby Goren
ID: 39790027
Hello all

I had some exchanges with the developer of Chameleon and we worked out a low tech solution for it.

So I am going to close this question and spread the points.


LVL 110

Expert Comment

by:Ray Paseur
ID: 39790078
Glad you got a good answer!  Best regards, ~Ray

Featured Post

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question