Open In App

How to Add Google Analytics Topics to PHP Website?

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Google Analytics is a platform created by Google in order to track website traffic and monitor site usage. Such details are crucial in order to improve marketing campaigns, increase website traffic and retain visitors. The best part of Google Analytics is that it is free for everyone, and we only need a google account in order to access this service. In this article we will see how we can integrate this service to our PHP website.

Steps to add google analytics to your website

In order to implement Google Analytics, your website must be hosted on the web. If you already have your website hosted, then you can skip these steps and directly jump to the Google Analytics part. Note that Google Analytics will not work if you are running your application on your local machine (localhost). Here, we will be creating a personal portfolio using PHP and host it for free on Vercel. Vercel is a Platform as a Service company which offers a free tier for users to deploy front-end as well as some backend applications (limited language and framework support). Follow the below steps:

Step 1: Go to https://github.com/putuwaw/php-app-vercel and create your own repository using the following template by clicking on the "Use this template" button.

step1
PHP template

Step 2: Make sure you have Git installed on your local machine. Use the following command to clone your repository to make changes to the template. Make sure to copy the link of your repository while using the git clone command.

git clone https://github.com/<username>/<repo_name>

Step 3: Our project which was created using the predefined template will look like this

Project structure:

projectstructure
Project template

Step 4: Open vercel.json file and change the vercel-php version from 0.5.2 to 0.6.1 or any other latest version. You can also add or remove routes according to your application. Here we will be only showcasing our portfolio on index.php page.

vercel.json:

{
"version": 2,
"functions": {
"api/*.php": { "runtime": "[email protected]" }
},
"routes": [
{
"src": "/",
"dest": "/api/index.php"
}
]
}

Step 5: You can also add or remove many stuffs present inside public folder (images, scripts and styles). We have removed everything from images and script folder, and we will be using the styles folder to add our CSS file to decorate our portfolio.

Step 6: Add the following code to index.php which is our personal portfolio.

api/index.php:

PHP
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Portfolio</title>
    <link rel="stylesheet" href="../public/styles/styles.css">
    <?php include_once 'header.php' ?>
</head>
<body>
    <header>
        <h1>My Portfolio</h1>
        <nav>
            <ul>
                <li><a href="#about">About</a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>

    <section id="about">
        <h2>About Me</h2>
        <p>
            <?php
            $aboutText = 
"Hello! I'm a web developer with a passion for creating beautiful and functional websites.";
            echo $aboutText;
            ?>
        </p>
    </section>

    <section id="projects">
        <h2>My Projects</h2>
        <div class="projects">
            <?php
            $projects = [
                ["title" => "Project One", "description" => "Description for project one."],
                ["title" => "Project Two", "description" => "Description for project two."],
                ["title" => "Project Three", "description" => "Description for project three."]
            ];

            foreach ($projects as $project) {
                echo "<div class='project-item'>";
                echo "<h3>" . $project["title"] . "</h3>";
                echo "<p>" . $project["description"] . "</p>";
                echo "</div>";
            }
            ?>
        </div>
    </section>

    <section id="contact">
        <h2>Contact Me</h2>
        <form method="post">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>

            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>

            <label for="message">Message:</label>
            <textarea id="message" name="message" required></textarea>

            <button type="submit">Send</button>
        </form>
    </section>

    <footer>
        <p>&copy; 2024 My Portfolio</p>
    </footer>
</body>
</html>

Step 7: To style our portfolio, we are using plain CSS for simplicity purposes.

public/styles/styles.css

CSS
body {
    font-family: 'Arial', sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

header {
    background: #333;
    color: #fff;
    padding: 1rem 0;
    text-align: center;
    position: sticky;
    top: 0;
    z-index: 1000;
}

header h1 {
    margin: 0;
}

nav ul {
    list-style: none;
    padding: 0;
}

nav ul li {
    display: inline;
    margin: 0 1rem;
}

nav ul li a {
    color: #fff;
    text-decoration: none;
    font-weight: bold;
}

nav ul li a:hover {
    text-decoration: underline;
}

section {
    padding: 2rem 1rem;
    margin: 1rem auto;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    max-width: 800px;
}

section h2 {
    margin-top: 0;
    font-size: 1.5rem;
    border-bottom: 2px solid #333;
    padding-bottom: 0.5rem;
    margin-bottom: 1rem;
}

.projects {
    display: flex;
    flex-direction: column;
}

.project-item {
    padding: 1rem;
    margin-bottom: 1rem;
    background: #f9f9f9;
    border-left: 5px solid #333;
}

.project-item h3 {
    margin-top: 0;
    font-size: 1.2rem;
}

.project-item p {
    margin: 0.5rem 0 0;
}

form {
    display: flex;
    flex-direction: column;
}

form label {
    margin-bottom: 0.5rem;
    font-weight: bold;
}

form input, form textarea {
    margin-bottom: 1rem;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
}

form textarea {
    resize: vertical;
}

button {
    padding: 0.7rem;
    background: #333;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
}

button:hover {
    background: #555;
}

footer {
    text-align: center;
    padding: 1rem 0;
    background: #333;
    color: #fff;
    position: sticky;
    bottom: 0;
    width: 100%;
}

@media (max-width: 768px) {
    nav ul li {
        display: block;
        margin: 0.5rem 0;
    }

    section {
        padding: 1rem;
        margin: 0.5rem auto;
    }

    .project-item {
        padding: 0.5rem;
    }
}

Step 8: Create another file inside the api folder named header.php and store it alongside index.php. This PHP file will contain the necessary scripts to monitor and track user activity on our website, in this case our portfolio. Keep it blank for now, we will add the code later.

Step 9: After doing all the changes, our project folder will look like below provided image. This project uses only one webpage for demonstration. However, you can add multiple pages to your website by adding more PHP files inside the api folder only. Also make sure you add the following code inside the head element (refer index.php code to get exact location of pasting) to every page you want to track:

<?php include_once 'header.php' ?>

Project Structure:

folderstructure
Project structure

Step 10: Commit and push the changes to your remote GitHub repository by using the commands:

Add the following changes

git add .

Commit and pass a commit message as options

git commit -m "Commit message"

Push the changes to your remote GitHub repository. Make sure to use the correct URL according to your GitHub username and Repository name which you have cloned from.

git push https://github.com/<username>/<repo_name>

Step 11: For deployment of this portfolio website, login to vercel (or sign-up using GitHub account) and create a project and import the above created repository.

step4
Vercel Project

Step 12: Your deployment will get errors caused due to NodeJS version. So, change the node version from 20.X to 18.X by going to your project -> Settings -> General -> Node.js version. Make sure you press on save before exiting.

step5
Node Version

Step 13: Click on deploy and check whether your website is hosted successfully. The URL at which our portfolio is deployed will be used later while setting up Google Analytics Stream.

deployed
Deployed successfully

Step 14: If you have deployed the website already then follow the below steps to integrate Google Analytics to your website. Go to https://marketingplatform.google.com/about/analytics/ and click on "Sign in to Analytics" button.

Step 15: Click on start measuring. You can put your name in the Account name field. Using one Google Analytics account, we can track single or multiple properties (more about properties in next point).

step3
Account Details

Step 16: Provide a property name. A property represents a grouping of data from a website or app in Google Analytics. Within a property, we can view reports and manage data collection, attribution, privacy settings, and product links. The Analytics report will be showing details based on the location and time zone and will perform the necessary conversions automatically. So, change that accordingly.

step4
Property Details

Step 17: Provide your business details i.e. Your business domain and size of your business to provide relevant metrics and benchmarks.

step5
Business Details

Step 18: Choose a suitable business objective for enhanced reporting.

step6
Business Objectives

Step 19: Accept the terms and conditions.

step7
Terms and conditions

Step 20: Choose web as the platform and provide the URL of your website as a stream. A data stream is a flow of data from a customer touchpoint (e.g., app, website) to Google Analytics. In this case, we will be providing the link where our portfolio was deployed.

step8
Website Details

Step 21: Copy the code shown in your window and paste it on header.php file of our portfolio website which was previously kept blank.

step9
Analytics Script

api/header.php

PHP
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX');
</script>

Note that the above code will be similar to the one you will be copying from your google analytics dashboard, the only difference would be the G-code. So, change that according and push the necessary changes to your GitHub repository using add, commit and push commands mentioned previously.

Step 22: All the analytics detail will be reported to you when a user visits your website. Note that Google Analytics only works if the client browser does not have any extensions or plugins which blocks these tracking requests such as ublock orgin or adblocker.

final
Google Analytics Report

Output:

Analytics-Home
Google Analytics Dashboard

Next Article
Article Tags :

Similar Reads