PHP And MySQL Storing Visitor Log In The Database Example Tutorial

PHP And MySQL Storing Visitor Log In The Database Example Tutorial

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;

include_once ‘log.php’;

?>

PHP And MySQL Storing Visitor Log In The Database Example Tutorial

Visitor Activity Log

Current page url :

Referrer url :

Ip Address :

User Agent :

dbConfig.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);

>

?>

// 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.

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

Источник

How to log user actions with php and mysql?

Logging user actions is a critical aspect of application development and management. It helps you track and monitor what users are doing in your application, which can be useful for security, debugging, and analytics purposes. In PHP and MySQL, you can implement logging by storing user actions in a database table and using PHP to insert new entries as users interact with your application. Here are some methods to log user actions in PHP and MySQL:

Method 1: Simple Logging

Step 1: Setting up the MySQL Database

First, create a MySQL database to store the logs. You can use the following SQL query to create a table for the logs:

CREATE TABLE `logs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `message` text NOT NULL, `level` varchar(20) NOT NULL, `timestamp` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2: Installing Simple Logging

Next, download and install the Simple Logging library. You can download it from the following GitHub repository:

Читайте также:  Typescript generic extends enum

You can install it using Composer:

composer require joshcanhelp/simple-logger

Step 3: Using Simple Logging to Log User Actions

Once you have installed the Simple Logging library, you can use it to log user actions in your PHP code. Here is an example code snippet:

require_once 'vendor/autoload.php'; use JoshCanHelp\SimpleLogger\Logger; $logger = new Logger('mysql', array( 'host' => 'localhost', 'dbname' => 'mydatabase', 'username' => 'myusername', 'password' => 'mypassword' )); // Log a message with the "info" level $logger->info('User logged in'); // Log a message with the "warning" level $logger->warning('Invalid password entered'); // Log a message with the "error" level $logger->error('Database connection failed');

In this example, we create a new instance of the SimpleLogger class and pass in the MySQL database connection details. We then use the info() , warning() , and error() methods to log messages with different log levels.

Step 4: Retrieving Logs from the Database

You can retrieve the logs from the database using a simple SQL query. Here is an example code snippet:

require_once 'vendor/autoload.php'; use JoshCanHelp\SimpleLogger\Logger; $logger = new Logger('mysql', array( 'host' => 'localhost', 'dbname' => 'mydatabase', 'username' => 'myusername', 'password' => 'mypassword' )); // Retrieve all logs from the database $logs = $logger->getLogs(); // Loop through the logs and display them foreach ($logs as $log)  echo $log['timestamp'] . ' [' . $log['level'] . '] ' . $log['message'] . "\n"; >

In this example, we use the getLogs() method to retrieve all the logs from the database. We then loop through the logs and display them on the screen.

Method 2: Advanced Logging with PHP Sessions

To log user actions with PHP and MySQL, you can use PHP Sessions. PHP Sessions is a built-in mechanism in PHP that allows you to store user data on the server-side. You can use PHP Sessions to track user actions and store them in a MySQL database.

Here are the steps to log user actions with PHP Sessions:

  1. Create a function to log user actions. This function will take the user action as a parameter and store it in a MySQL database. You can use mysqli extension to connect to the database and execute SQL queries.
function logUserAction($action)  $conn = mysqli_connect("localhost", "username", "password", "database"); $sql = "INSERT INTO user_actions (action) VALUES ('$action')"; mysqli_query($conn, $sql); mysqli_close($conn); >
  1. Call the logUserAction() function whenever the user performs an action. You can use $_SERVER[‘PHP_SELF’] to get the current page URL.
if (isset($_POST['submit']))  $action = "User submitted a form on " . $_SERVER['PHP_SELF']; logUserAction($action); >
  1. Display the user actions on a webpage. You can retrieve the user actions from the MySQL database using a SELECT query and display them on a webpage.
$conn = mysqli_connect("localhost", "username", "password", "database"); $sql = "SELECT * FROM user_actions"; $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result))  echo $row['action'] . "
"
; > mysqli_close($conn);

That’s it! You have successfully logged user actions with PHP Sessions and MySQL. You can customize the logUserAction() function to store additional information such as user ID, IP address, etc.

Method 3: Logging with PHP and MySQL Transactions

Here are the steps to log user actions in PHP and MySQL using transactions:

$dsn = 'mysql:host=localhost;dbname=your_database'; $username = 'your_username'; $password = 'your_password'; try  $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch (PDOException $e)  echo 'Connection failed: ' . $e->getMessage(); >
$userAction = 'User logged in';
$stmt = $pdo->prepare("INSERT INTO user_actions (action) VALUES (:action)"); $stmt->bindParam(':action', $userAction); $stmt->execute();
  1. If there is an error, roll back the transaction by calling the rollBack() method on the PDO object.

Here is the complete code:

$dsn = 'mysql:host=localhost;dbname=your_database'; $username = 'your_username'; $password = 'your_password'; try  $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch (PDOException $e)  echo 'Connection failed: ' . $e->getMessage(); > $pdo->beginTransaction(); $userAction = 'User logged in'; $stmt = $pdo->prepare("INSERT INTO user_actions (action) VALUES (:action)"); $stmt->bindParam(':action', $userAction); $stmt->execute(); $pdo->commit();

This code will insert the user action «User logged in» into the «user_actions» table in your database. You can modify the code to log different user actions by changing the value of the $userAction variable.

Источник

Log to file via PHP or log to MySQL database — which is quicker?

There are many, many reasons to choose this architecture — ease of scaling (write to many logs, load them to db), lack of reliance on a SPOF in the database (if something goes wrong, you just accumulate logs for a while), ability to do cleaning and non-trivial parsing at load-time without burdening your production servers, and more.

Solution 2

You could try both ways using log4php, which supports:

  • Configuration through xml and properties file (same structure as log4j).
  • File, RollingFile, DailyFile, Echo, Console, Mail, PEAR::Db, PHP error, Syslog or NT events and Socket appenders.
  • Simple, TTCC, Pattern, Html and Xml Layouts.
  • Nested (NDC) and Mapped (MDC) Diagnostic Contexts.
  • Switchable internal debug.

Regarding logging into a file, you could improve performance by buffering the write requests.

Solution 3

I would use a Delayed Insert into MySQL. This way you don’t have to wait for the insert to finish.

Solution 4

Use a database — it is the only sane option. Even if it takes a little longer. Once you start with logfiles then you are on a track where it will cause you pain — e.g. moving servers, file permissions, precludes load balancing etc.

If you’ve got the database open then I reckon that it would be probably quicker to insert a single row.

However with all this performance related the only way to be sure is to write a simple test and measure it.

Update: I’ve done a quick test — and sure enough if you have to open and close the file it’s about the same speed or slower using a test of 10,000 lines:

However when you start to have multiple processes doing this it slows down as can be seen below. This is with 10 concurrent processes (all timings in seconds)

DB time: 2.1695 DB time: 2.3869 DB time: 2.4305 DB time: 2.5864 DB time: 2.7465 DB time: 3.0182 DB time: 3.1451 DB time: 3.3298 DB time: 3.4483 DB time: 3.7812 File open time: 0.1538 File open time: 0.5478 File open time: 0.7252 File open time: 3.0453 File open time: 4.2661 File open time: 4.4247 File open time: 4.5484 File open time: 4.6319 File open time: 4.6501 File open time: 4.6646 Open close file time: 11.3647 Open close file time: 12.2849 Open close file time: 18.4093 Open close file time: 18.4202 Open close file time: 21.2621 Open close file time: 22.7267 Open close file time: 23.4597 Open close file time: 25.6293 Open close file time: 26.1119 Open close file time: 29.1471 function debug($d) < static $start_time = NULL; static $start_code_line = 0; if( $start_time === NULL ) < $start_time = time() + microtime(); $start_code_line = $code_line; return 0; >printf("$d time: %.4f\n", (time() + microtime() - $start_time)); $fp = @fopen('dbg.txt','a'); fprintf($fp,"$d time: %.4f\n", (time() + microtime() - $start_time)); fclose($fp); $start_time = time() + microtime(); $start_code_line = $code_line; > function tfile() < $fp = @fopen('t1.txt','a'); for ($i=0;$i<10000;$i++) < $txt = $i."How would you log, which do you think is quicker:How would you log, which do you think is quicker:"; fwrite($fp,$txt); >fclose($fp); > function tfile_openclose() < for ($i=0;$i<10000;$i++) < $fp = @fopen('t1.txt','a'); $txt = $i."How would you log, which do you think is quicker:How would you log, which do you think is quicker:"; fwrite($fp,$txt); fclose($fp); >> function tdb() < $db = mysql_connect('localhost','tremweb','zzxxcc'); $select_db = mysql_select_db('scratch'); if (!$select_db) die('Error selecting database.'); for ($i=0;$i<10000;$i++) < $txt = $i."How would you log, which do you think is quicker:How would you log, which do you think is quicker:"; mysql_query("INSERT INTO tlog values('".$txt."')"); >> debug(""); tfile(); debug("File open"); tfile_openclose(); debug("Open close file"); tdb(); debug("DB"); 

Solution 5

I would believe that a flat file will be faster to write to.

Источник

How to Store Visitor Activity Log in the MySql Database Using PHP

Store Visitor Activity Log in the MySql Database Using PHP

In this article, we will learn about the website visitor activity tracking script. User activity on the online application / Website can be tracked using the Visitor Log. You’ll collect the visitor’s IP address, referrer, browser, and other information when they visit the website and store it in a database log.

The country, latitude, and longitude of the visitor can also be stored in the database for geolocation tracking. Along with the visitor’s information, the logging system frequently stores and tracks the website’s interior access information. The $_SERVER variable in PHP will be used to achieve the majority of the knowledge. To get the visitors’ geolocation data, you’ll use a third-party API.

Are you want to get implementation help, or modify or extend the functionality of this script?

A Tutorialswebsite Expert can do it for you.

Using PHP and MySQL, we’ll show you how to collect visitor information (IP, referrer, browser, geolocation, and so on) and store logs in a database. We’ll use PHP to log the visitor’s activity in the MySQL database.

Store Visitor Activity Log in the MySql Database

Step-1: Create Database Tablel

To store the user activity information, a table should be made in the database. The following SQL query creates a visitor_activity_logs table with some essential fields in the MySQL database.

Источник

Оцените статью