Joshc Joshc -4 years ago 95
PHP Question

php header instant redirect if specified campaign urls are visited

I might worrying way too much here, but here it goes...

I have set up google analytic campaign tracking URLs using the google campaign link builder.

Which is great, but I have like 20 different tracking urls, and more to come.

These URLs are really ugly and I'm not a fan of the visitor seeing this long tracking url on there first visit to my site.




So this is my idea/theory that I want to put on my wordpress site. If anyone would be kind enough to help with the php writing part of it, I would be very grateful. Or any advice if the idea is a bad one.




For example, these are just some of my URL's

http://example.com/?utm_source=Company&utm_medium=MPU&utm_campaign=Promo

http://example.com/?utm_source=Company&utm_medium=Leaderboard&utm_campaign=Promo

http://example.com/?utm_source=Company&utm_medium=Take%2BOver&utm_campaign=Promo

I would like to instantly redirect all of the above urls too...

http://example.com/

Using php in my header.php or functions.php




Is there some how this can be written so I can simply add new tracking urls in an array/case perhaps.

Any suggestions would be great thanks!




Please don't laugh as this - but at a guess this is what I'm trying to do...

$landing = $_SERVER['REQUEST_URI'];

$campaigns = array(
"http://example.com/?utm_source=Company&utm_medium=MPU&utm_campaign=Promo",
"http://example.com/?utm_source=Company&utm_medium=Leaderboard&utm_campaign=Promo",
"http://example.com/?utm_source=Company&utm_medium=Take%2BOver&utm_campaign=Promo"
);

if ( $campaigns == $landing ) {

header( 'Location: http://example.com/' ) ;

}

Answer Source

You should not do that.

Google analytics tracking code is client side. It is a piece of js code which executes once the page is loaded. If it does not find utm_* query parameters, nothing is going to be sent to ga, so the stats you are going to see there won't be readable. Most probably you will just see the grand total in the ga ui.

If you want to do it anyway...

$trackingParams = array('utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term');
$queryParams = array();
parse_str($_SERVER['QUERY_STRING'], $queryParams);
if (count(array_intersect($queryParams, $trackingParams)) > 1) {
    // This url has tracking params
    foreach ($trackingParams as $paramName) {
        unset($queryParams[$paramName]);
    }
    // You can use a regex, but i wouldn't recommend it
    $newUrl = str_replace(
        $_SERVER['QUERY_STRING'],
        http_build_query($queryParams),
        $_SERVER['REQUEST_URI']
    );
    header('Location: ' . $newUrl, true, 301);
    exit;
}

This is code is going to search for utm_* params in current url and redirect to an url without them, leaving other query params intact.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download