2

I have a short URL website like Bitly which currently redirect users with PHP from my site to a site of their choice. I want to add Google Analytics to the redirect pages but I am stuck on the problem where Javascript is run after the PHP code is executed so it wont work.

Bellow is the last part of the PHP code that redirects users from the short URL to the URL they shortend. I wonder if there is anyway to make this work OR change my code somehow so that Google Analytics can be executed either with PHP or something else that can do the "redirection"?

$shortUrlObj contains the short url code. If the short url is https://example.com/1234 $shortUrlObj contains 1234. fullUrl is the website destination they choose to shorten. So if the user shortened https://stackexchange.com, fullUrl contains https://stackexchange.com

switch ($redirect)
{
    default:
        header('HTTP/1.1 302 Moved Temporarily');
        redirect($shortUrlObj->fullUrl);
        break;
}
1
  • Google analytics isn't the right tool for the job. URL shorteners typically track redirects through server side logging. – Stephen Ostermiller Feb 24 at 14:02
1

I got it working by using Javascript to do the redirecting. However the redirect became extremely slow when loading. Does anyone know why and what can be done about that part?

switch ($redirect)
{
     default:  
?>

    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxx-1"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    
    gtag('config', 'UA-xxxxxx-1');
    </script>

    <script>
    window.location = '<? echo $shortUrlObj->fullUrl; ?>'
    </script> 
    
<?php
    break;
}
1
  • "redirect became extremely slow" - how slow? seconds? minutes?? Presumably you've written this code, so you know what it's doing, so.... you should know why it's "slower" (and "different") to your original code. (?) (What's the purpose of the switch() statement?) – MrWhite Feb 24 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.