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

Posted on 2014-01-13
Medium Priority
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 www.dog.com the following would be inserted into the header

I like dogs

And if the url is www.cat.com  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 www.cat.com

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 84

Accepted Solution

Dave Baldwin earned 668 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 668 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, 'www.dog.com')) {
   echo "I like dogs";
}elseif (stristr($url, 'www.dog.com')) {
  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 www.cat.com  it will insert the CAT code.

And when the switched template is on the www.dog.com 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, 'www.dog.com')) {
   echo "I like dogs";
}elseif (stristr($url, 'www.dog.com')) {
  echo "I like cats";

Open in new window


Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 664 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 http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28337288.html

$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="http://code.jquery.com/jquery-latest.min.js"></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 111

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 111

Expert Comment

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

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

770 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