# Traffic Tracking (PHP + MySQL)

This site uses **first-party PHP + MySQL tracking** to record where visitors come from. No Google Analytics is required.

## How it works

Each HTML page includes a small script:

```html
<script src="/tracking/visit.js" defer></script>
```

On each visit, `visit.js` calls `tracking/track.php`, which saves to MySQL:

- **Page URL** — which page was opened
- **Referrer** — where the visitor came from (`google.com`, `linkedin.com`, another site, or empty = direct)
- **UTM parameters** — `utm_source`, `utm_medium`, `utm_campaign` from the URL
- **Source type** — direct, organic, social, referral, email, paid
- **Timestamp**, browser, hashed IP (optional)

Data is viewed in a password-protected dashboard at `/tracking/dashboard.php`.

---

## Files

```
tracking/
  config.example.php   ← copy to config.php (MySQL credentials)
  config.php           ← your live credentials (not committed to git)
  schema.sql           ← visits table definition
  install.php          ← one-time setup (delete after use)
  dashboard.php        ← view traffic sources
  track.php            ← logging endpoint
  visit.js             ← loaded on every HTML page
  db.php               ← database connection + logging
  helpers.php          ← source classification helpers
  log-visit.php        ← optional auto-prepend logger (not used by default)
```

The beacon script is injected into all HTML pages via `scripts/inject-tracking-beacon.js`.

---

## Setup on live server

### 1. Create a MySQL database

In cPanel, phpMyAdmin, or your host panel:

1. Create a database (e.g. `mydentalrevenue_analytics`)
2. Create a MySQL user with full access to that database

### 2. Upload the tracking folder

Upload the entire `tracking/` folder with the rest of the site.

### 3. Configure credentials

On the server, copy the example config:

```bash
cp tracking/config.example.php tracking/config.php
```

Edit `tracking/config.php` with your live MySQL details:

```php
'db' => [
    'host' => 'localhost',
    'port' => 3306,
    'name' => 'your_database_name',
    'user' => 'your_database_user',
    'pass' => 'your_database_password',
    'charset' => 'utf8mb4',
],

'ip_hash_salt' => 'pick-a-long-random-string',
```

`config.php` is listed in `.gitignore` so credentials are not committed to git.

### 4. Run install

Open in your browser:

```
https://mydentalrevenue.com/tracking/install.php
```

This will:

- Create the `visits` table in MySQL
- Set your dashboard password

**Delete or rename `install.php` on the live server after setup.**

### 5. View traffic

Open:

```
https://mydentalrevenue.com/tracking/dashboard.php
```

- **Username:** `admin`
- **Password:** the password you set during install

---

## Dashboard reports

| Report | Description |
|--------|-------------|
| **Traffic by source type** | Direct, Organic, Social, Referral, Email, Paid |
| **Top referrers** | e.g. `google.com`, `linkedin.com`, `(direct / unknown)` |
| **Top pages** | Most visited URLs |
| **Recent visits** | Latest visits with referrer and UTM data |

Filter by **7, 30, or 90 days** using the links in the header.

---

## How sources are detected

| If… | Logged as |
|-----|-----------|
| No referrer | **Direct** (typed URL, bookmark, or unknown) |
| From Google, Bing, Yahoo, DuckDuckGo | **Organic** |
| From Facebook, LinkedIn, Twitter/X, Instagram | **Social** |
| From another website | **Referral** |
| `utm_medium=email` or `utm_source=newsletter` | **Email** |
| `utm_medium=cpc`, `ppc`, or `paid` | **Paid** |
| URL has `?utm_source=...` | Uses your UTM tags |

### Campaign link example

```
https://mydentalrevenue.com/contact-us/?utm_source=linkedin&utm_medium=social&utm_campaign=spring2026
```

These appear in the dashboard under UTM columns and affect source classification.

---

## Local testing (Laragon)

1. Copy `tracking/config.example.php` to `tracking/config.php`
2. Enter your Laragon MySQL credentials (or create a local database)
3. Visit `http://mydentalrevenue.test/tracking/install.php`
4. Browse a few pages on the site
5. Check `http://mydentalrevenue.test/tracking/dashboard.php`

**Note:** Opening pages via `file://` will not log visits. Use Laragon’s `http://` URL.

---

## Privacy

- Visitor IPs are **hashed by default** (`hash_ips => true` in config)
- Bot/crawler traffic is skipped
- Only `GET` requests to HTML pages are logged
- Consider mentioning analytics in your [privacy policy](/privacy-policy/index.html)
- You can integrate with CookieYes to load `visit.js` only after cookie consent (optional)

---

## Re-inject beacon on new HTML pages

If you add new static HTML pages, run:

```bash
node scripts/inject-tracking-beacon.js
```

This adds `<script src="/tracking/visit.js" defer></script>` before `</head>` on any page that does not already have it.

---

## Database schema

The `visits` table stores:

| Column | Description |
|--------|-------------|
| `visited_at` | Date and time of visit |
| `page_path` | URL path (e.g. `/contact-us/index.html`) |
| `query_string` | URL query string if present |
| `referrer` | Full referrer URL |
| `referrer_host` | Referrer domain (e.g. `google.com`) |
| `source_type` | direct, organic, social, referral, email, paid, unknown |
| `utm_source` | UTM source parameter |
| `utm_medium` | UTM medium parameter |
| `utm_campaign` | UTM campaign parameter |
| `user_agent` | Browser user agent |
| `ip_address` | Hashed IP (if `hash_ips` is enabled) |

See `tracking/schema.sql` for the full `CREATE TABLE` statement.

---

## Troubleshooting

| Problem | Fix |
|---------|-----|
| Dashboard says not configured | Copy `config.example.php` to `config.php` and fill in MySQL credentials |
| Could not connect to MySQL | Verify host, database name, user, and password with your host |
| No visits appearing | Confirm the site is served over `http://` or `https://` (not `file://`) |
| `visit.js` not loading | Check that `/tracking/visit.js` is accessible in the browser |
| `track.php` errors | Ensure PHP and PDO MySQL extension are enabled on the server |

---

## PHP vs Google Analytics

| | PHP (this setup) | Google Analytics |
|--|------------------|------------------|
| Cost | Free | Free |
| Data location | Your MySQL server | Google |
| Cookie banner | Easier (first-party) | Requires consent integration |
| Reports | Custom dashboard | Rich built-in reports |
| Setup | MySQL + config on your server | Add GA4 snippet |
