How can PHP be used to log referrers in a database and calculate the percentage of visitors from each host?

To log referrers in a database and calculate the percentage of visitors from each host, you can create a PHP script that captures the referrer information from the HTTP headers, stores it in a database table, and then calculates the percentage of visitors from each host based on the stored data.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

// Get the referrer information from the HTTP headers
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$host = parse_url($referrer, PHP_URL_HOST);

// Insert the referrer information into the database
$sql = "INSERT INTO referrers (host) VALUES ('$host')";
$conn->query($sql);

// Calculate the percentage of visitors from each host
$totalVisitors = $conn->query("SELECT COUNT(*) FROM referrers")->fetch_row()[0];
$result = $conn->query("SELECT host, COUNT(*) AS count, (COUNT(*) / $totalVisitors * 100) AS percentage FROM referrers GROUP BY host");

// Display the results
while ($row = $result->fetch_assoc()) {
    echo $row['host'] . ": " . $row['percentage'] . "%<br>";
}

// Close the database connection
$conn->close();