Solved

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

Posted on 2014-01-13
9
1,333 Views
Last Modified: 2014-01-17
Hello

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
</head>

And if the url is www.cat.com  the following would be inserted into the header

I like cats
</head>

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
</head>

Thanks!

Rowby
0
Comment
Question by:Rowby Goren
9 Comments
 
LVL 82

Accepted Solution

by:
Dave Baldwin earned 167 total points
Comment Utility
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.
0
 
LVL 30

Assisted Solution

by:Marco Gasi
Marco Gasi earned 167 total points
Comment Utility
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]
</IfModule>

Open in new window


Then in your pages you can do this:
<?php
$url = $_GET['url'];
?>
<html>
<head>
<?php
if (stristr($url, 'www.dog.com')) {
   echo "I like dogs";
}elseif (stristr($url, 'www.dog.com')) {
  echo "I like cats";
}
?>
</head>

Open in new window

0
 
LVL 9

Author Comment

by:Rowby Goren
Comment Utility
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.

Chameleon

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'];
?>
<html>
<head>
<?php
if (stristr($url, 'www.dog.com')) {
   echo "I like dogs";
}elseif (stristr($url, 'www.dog.com')) {
  echo "I like cats";
}

Open in new window


Thansk!

Rowby
0
 
LVL 9

Author Comment

by:Rowby Goren
Comment Utility
Hello

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
falsetrue
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";

if ( MM_NOT_LOGGED_IN )
    return "4";
if ( MM_LOGGED_IN )
    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->latitude
        $geoip->longitude
        $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->name
        $user->username
        $user->email
        $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

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
Comment Utility
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
error_reporting(E_ALL);


// 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);

switch($url)
{
    case 'CAT': $var = 'I LIKE CATS'; break;
    case 'DOG': $var = 'I LIKE DOGS'; break;
    default:    $var = 'I LIKE FISH';
}
// END OF PHP
?><!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<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>
</head>
<body>
<p><?=$var?></p>
</body>
</html>

Open in new window

0
 
LVL 9

Author Comment

by:Rowby Goren
Comment Utility
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.

Thanks

Rowby
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Yeah, it looks like there is a lot more to it...
0
 
LVL 9

Author Comment

by:Rowby Goren
Comment Utility
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.

Thanks!

Rowby
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Glad you got a good answer!  Best regards, ~Ray
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

772 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now