I know this question was asked before multiple times but none of these solutions: (solution 1, solution 2, solution 3) has worked for me. This is my first time dealing with PHP code and I'm trying to add Google Analytics tracking to my index.php
file with the following code:
<?php
include('someOtherFile.php');
// Redirect to example.com
header("Location: http://www.example.com");
die();
?>
I created the analyticstracking.php
like instructed by Google, placed it in the same folder as my index.php
file and added the following row to my code like this:
<?php
include('someOtherFile.php');
include('analyticstracking.php');
// Redirect to example.com
header("Location: http://www.example.com");
die();
?>
The result was that the redirect to example.com stopped working and analytics didn't work as well.
I then tried:
<?php include('analyticstracking.php'); ?>
<?php
include('someOtherFile.php');
// Redirect to example.com
header("Location: http://www.example.com");
die();
?>
Which made analytics work but the redirect didn't.
And this version:
<?php
include('someOtherFile.php');
// Redirect to example.com
header("Location: http://www.example.com");
die();
?>
<?php include('analyticstracking.php'); ?>
Which made the redirect work but analytics didn't.
So I finnaly tried a diffrent approach and tried this:
<html>
<body>
<?php include('analyticstracking.php'); ?>
<?php
include('someOtherFile.php');
// Redirect to example.com
header("Location: http://www.example.com");
die();
?>
</body>
</html>
Which acted exactly the same as not using the <html>
tags (first php tag wins).
Also tried include_once
as well as adding the script to the php file itself. nothing worked. Always the first piece of code wins.
So what am I missing here? What is the right way to make my redirect work together with the google analytics include?
You need to echo the analytics code in analyticstracking.php
So you're code will be:
analyticstracking.php
<?php
echo "
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-0000000-1', 'auto'); ga('send', 'pageview'); </script>
";
?>
index.php
<?php
include_once("analyticstracking.php");
header("Location: http://www.example.com");
die();
?>
Tested and it works for me. :)