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
How to Add Your Website to Google Analytics ?
Google provides some wonderful services to webmasters which definitely helps in managing a web application or a static website. It provides Google AdWords Keyword Planner, Google Search Console, PageSpeedTest by Google, Google AdSense, and also Google Analytics is one of those. After acquiring the U
3 min read
How To Add My Website To Google Business
How to Connect My Website to Google My Business- Quick StepsLog in to your one.com control panel and go to Website Builder settings.If you want, make a listing.Connect your listing.You're done!Having your business listed on Google is super important. It helps people find you easily and makes your bu
6 min read
How To Add Google Analytics in React?
Integrating Google Analytics into a React application enables you to monitor and analyze your websiteâs traffic and user behavior. This integration offers valuable insights into user interactions on your site, aiding in making informed decisions to enhance user experience and achieve business object
3 min read
How to Add Google Maps to a Website ?
Integrating Google Maps into a website is a common and useful feature. We can use Google Maps API to add it to our website.Follow the below steps to Add Google Maps to a Website1. Generate/Obtain Google Maps API KeyTo fetch the location data from Google Maps first we need a Google Maps API Key. It i
3 min read
How To Add Google Analytics To GitHub Pages
If you're hosting a website on GitHub Pages and want to track how many people visit your site and what they do there, Google Analytics is the perfect tool. It provides valuable insights that can help you understand your audience and improve your site.In this easy-to-follow guide, we'll show you how
4 min read
How to add Google Forms to your Website
Looking to collect feedback, responses, or data directly from your website visitors? Adding a Google Form to your website can be an excellent way to gather information in a quick and efficient manner. Whether you're running a survey, feedback form, or registration page, integrating Google Forms into
2 min read
How to Install Google Analytics in WordPress ?
Google Analytics is a powerful tool that helps you understand your website's traffic and user behaviour. By installing Google Analytics on your WordPress site, you can gain valuable insights to improve your content, enhance user experience, and boost your site's performance. This guide will walk you
3 min read
How to Add Google Analytics to a Next.js Application?
Adding Google Analytics to a Next.js application allows you to track and analyze your website's traffic and user actions. This can provide valuable insights into how users interact with your site, helping you make informed decisions to improve user experience and drive business goals. This article h
3 min read
How To View Analytics On Google Forms
Google Forms is a versatile tool for gathering data, but its true power lies in its ability to analyze responses efficiently. It comes with a lot of preloaded features, which made it popular among users. It also has analytics tools built in which helps users quickly understand the summary of respons
4 min read
How to Add Google Charts on a Webpage?
What is a pie chart? A pie chart (or a circle chart) is a circular statistical graphic which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice (and consequently its central angle and area), is proportional to the quantity it represents. While it
2 min read