What are some methods for monitoring website traffic in PHP?
Monitoring website traffic in PHP can be achieved by implementing tracking codes or scripts that capture and log information about visitors, such as their IP addresses, user agents, and timestamps. This data can then be stored in a database for analysis and reporting purposes.
// Sample PHP code snippet for tracking website traffic
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "website_traffic";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get visitor information
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$timestamp = date('Y-m-d H:i:s');
// Insert visitor information into database
$sql = "INSERT INTO traffic_logs (ip_address, user_agent, timestamp) VALUES ('$ip', '$user_agent', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close database connection
$conn->close();