03-Apr-2023
.
Admin
Hi guys,
Today i will explained how to store visitor log in database with php and mysql through. This example is so easy to use in php. This example to i am storing log in database and fache to th data to print in display from last record.
This example to i am create a three file log.php,index.php and last index.php file to create.
So let's start to the example.
Create Database In Mysql
CREATE TABLE `visitor_logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`page_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`referrer_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_ip_address` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`user_agent` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Index.php
<?php
include_once 'log.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP And MySQL Storing Visitor Log In The Database Example Tutorial</title>
</head>
<body>
<div class="container">
<h1>PHP And MySQL Storing Visitor Log In The Database Example Tutorial</h1>
<div class="cw-info-box">
<h2>Visitor Activity Log</h2>
<div class="log-data">
<p><b>Current page url</b> : <?php echo $currentURL; ?></p>
<p><b>Referrer url</b> : <?php echo $referrer_url; ?></p>
<p><b>Ip Address</b> : <?php echo $user_ip_address; ?></p>
<p><b>User Agent</b> : <?php echo $user_agent; ?></p>
</div>
</div>
</div>
</body>
</html>
dbConfig.php
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "login";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
log.php
<?php
// Include the database configuration file
include_once 'dbConfig.php';
// Get current page URL
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$currentURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
// Get server related info
$user_ip_address = $_SERVER['REMOTE_ADDR'];
$referrer_url = !empty($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'/';
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// Insert visitor log into database
$sql = "INSERT INTO visitor_logs (page_url, referrer_url, user_ip_address, user_agent, created) VALUES (?,?,?,?,NOW())";
$stmt = $db->prepare($sql);
$stmt->bind_param("ssss", $currentURL, $referrer_url, $user_ip_address, $user_agent);
$insert = $stmt->execute();
?>
Now you can check your own.
I hope it can help you...
Output :
#PHP 8
#PHP