How to Add Google Analytics Topics to PHP Website?
Last Updated :
26 Aug, 2024
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.
PHP templateStep 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:
Project templateStep 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>© 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:
Project structureStep 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.
Vercel ProjectStep 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.
Node VersionStep 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 successfullyStep 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).
Account DetailsStep 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.
Property DetailsStep 17: Provide your business details i.e. Your business domain and size of your business to provide relevant metrics and benchmarks.
Business DetailsStep 18: Choose a suitable business objective for enhanced reporting.
Business ObjectivesStep 19: Accept the terms and conditions.
Terms and conditionsStep 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.
Website DetailsStep 21: Copy the code shown in your window and paste it on header.php file of our portfolio website which was previously kept blank.
Analytics Scriptapi/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.
Google Analytics ReportOutput:
Google Analytics Dashboard
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read