• We just launched and are currently in beta. Join us as we build and grow the community.

How to Store Visitor Log in the Database using PHP and MySQL?

blissy

Virtual Storefront Pro
B Rep
0
0
0
Rep
0
B Vouches
0
0
0
Vouches
0
Posts
122
Likes
41
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 100 XP
Within this tutorial, we will explore the development of a straightforward web application featuring a central focus on Site Visitor Logs. This article's primary objective is to serve as a valuable resource for PHP programming newcomers and students, offering insights into the implementation of common features to enrich their proficiency and understanding of the PHP programming language. Here, you will find the complete source code for a basic web application that includes a functionality for tracking site visitor activity.

Reasons for Storing Visitor Logs in a Database

Database Storage of Visitor Logs is a commonly featured aspect in various web applications, including Content Management Systems. This feature serves a crucial purpose, enabling website administrators to monitor page views and more. It fulfills several significant roles, such as:

  1. Analytics and Statistics - Enabling website owners and managers to track and analyze visitor behavior effectively.
  2. Security Monitoring - Assisting in identifying suspicious or malicious activities, such as hacking attempts, spam, or unauthorized access.
  3. Performance Monitoring - Providing insights into performance issues, slow-loading pages, or high traffic periods.
  4. Historical Data - Serving as a historical record of website and user activities.

How to Store Visitor Log in the Database using PHP and MySQL?

In this tutorial, I'll supply you with a straightforward website source code that includes a `Visitor Log Storage` feature to help you grasp the process better. Before diving into the coding aspect, make sure you have the following components installed on your local machine if they aren't already:

  • Web Server Software (e.g., XAMPP or WAMP)
  • Code Editor (e.g., Sublime Text, Microsoft Visual Studio Code, or Notepad++)

Once you have installed the Web Server Software, be sure to start or run the `Apache

` and `MySQL

` services.

Furthermore, the web application's user interface, which I will be presenting, relies on Content Delivery Networks (CDN) for loading the Bootstrap Framework and jQuery. These libraries are essential for enhancing the UI design. Please ensure you have an internet connection when accessing the web application to benefit from these resources. If offline, you may need to download the libraries and update the CSS and Script links accordingly.

Creating the Database

Begin by creating a new MySQL database, which you can name as `dummy_db

`. Afterward, add a new table within this database named `visit_logs

`. The table should include the following columns as outlined in the MySQL script below:

  1. CREATE

    TABLE

    `visit_

    logs`

    (
  2. `ID`

    bigint

    (

    30

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `user_

    ip`

    varchar

    (

    30

    )

    NOT

    NULL

    ,
  4. `page_

    url`

    text

    NOT

    NULL

    ,
  5. `reference_

    url`

    text

    NOT

    NULL

    ,
  6. `user_

    agent`

    text

    NOT

    NULL

    ,
  7. `date_

    created`

    datetime

    NOT

    NULL

    DEFAULT

    current_timestamp

    (

    )
  8. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    utf8mb4 COLLATE

    =

    utf8mb4_general_ci;

Creating the Database Connection Script

Now, it's time to create a new PHP

script file and save it as `db-connect.php

`. This script file contains the PHP code responsible for establishing the database connection.

  1. <?php
  2. // Hostname
  3. $host

    =

    "localhost"

    ;
  4. // Username
  5. $uname

    =

    "root"

    ;
  6. // Password
  7. $pw

    =

    ""

    ;
  8. // DB name
  9. $db_name

    =

    "dummy_db"

    ;

  10. try{
  11. // Opening Database Connection
  12. $conn

    =

    new

    mysqli(

    $host

    ,

    $uname

    ,

    $pw

    ,

    $db_name

    )

    ;
  13. }

    catch(

    Exception $e

    )

    {
  14. die

    (

    $e

    ->

    getMessage

    (

    )

    )

    ;
  15. }

  16. ?>

Creating the Visit Log Class

Now, proceed to create another PHP

file, which you should name as `visitors-log.class.php

`. Within this PHP script file, you will find the class responsible for retrieving the site visitor data and storing visitor data in the database.

  1. <?php
  2. class

    VisitorLog{
  3. private

    $db_conn

    ;
  4. private

    $http_protocol

    ;
  5. private

    $page_url

    ;
  6. private

    $reference_url

    ;
  7. private

    $user_ip

    ;
  8. private

    $user_agent

    ;

  9. function

    __construct(

    )

    {
  10. require_once

    (

    'db-connect.php'

    )

    ;
  11. $this

    ->

    db_conn

    =

    $conn

    ;
  12. $server_data

    =

    $_SERVER

    ?? ""

    ;
  13. if

    (

    !

    empty

    (

    $server_data

    )

    )

    {
  14. // Setting HTTP Protocol (http:// or http://)
  15. $this

    ->

    http_protocol

    =

    (

    (

    !

    empty

    (

    $server_data

    [

    'HTTPS'

    ]

    )

    &&

    $server_data

    [

    'HTTPS'

    ]

    !=

    'off'

    )

    ||

    $server_data

    [

    'SERVER_PORT'

    ]

    ==

    443

    )

    ? "https://"

    :

    "http://"

    ;

  16. // Get Current URL
  17. $this

    ->

    page_url

    =

    $this

    ->

    http_protocol

    .

    $server_data

    [

    'HTTP_HOST'

    ]

    .

    $server_data

    [

    'REQUEST_URI'

    ]

    .

    $server_data

    [

    'QUERY_STRING'

    ]

    ;

  18. // Get Reference URL
  19. $this

    ->

    reference_url

    =

    !

    empty

    (

    $_SERVER

    [

    'HTTP_REFERER'

    ]

    )

    ?$_SERVER

    [

    'HTTP_REFERER'

    ]

    :

    '/'

    ;
  20. // User Agant
  21. $this

    ->

    user_agent

    =

    $server_data

    [

    'HTTP_USER_AGENT'

    ]

    ;

  22. // Get User IP Address
  23. $this

    ->

    user_ip

    =

    $server_data

    [

    'REMOTE_ADDR'

    ]

    ;
  24. }
  25. }
  26. public

    function

    log_site_visit(

    )

    {
  27. // Query Statement
  28. $stmt

    =

    $this

    ->

    db_conn

    ->

    prepare

    (

    "INSERT INTO `visit_logs` (user_ip, page_url, reference_url, user_agent) VALUES (?, ?, ?, ?)"

    )

    ;
  29. // Binding Insert Values
  30. $stmt

    ->

    bind_param

    (

    'ssss'

    ,

    $this

    ->

    user_ip

    ,

    $this

    ->

    page_url

    ,

    $this

    ->

    reference_url

    ,

    $this

    ->

    user_agent

    )

    ;
  31. // Insert Site Visit Log Data into the database
  32. $save

    =

    $stmt

    ->

    execute

    (

    )

    ;
  33. if

    (

    $save

    )

    {
  34. // Do something when page visit data has been saved successfully
  35. // return true;
  36. }

    else

    {
  37. // Do something when page visit data has failed to save
  38. // return false;
  39. }
  40. }
  41. function

    __destruct(

    )

    {
  42. // Closing Database Connection
  43. $this

    ->

    db_conn

    ->

    close

    (

    )

    ;
  44. }
  45. }
  46. ?>

Creating the Website Interface

Next, let's develop the user interface for the website.

Index File

Start by creating a new PHP file named `index.php

`. This file encompasses a fusion of PHP and HTML5 scripts, including the requirement of the class file and the navigation bar.

  1. <?php
  2. require_once(

    "visitors-log.class.php"

    )

    ;
  3. /

    **
  4. * Log Site Visit Data
  5. */
  6. $vlClass =

    new VisitorLog(

    )

    ;
  7. $vlClass->

    log_site_visit();

  8. //page
  9. $page = str_replace(["-", "_"], " ",$_GET['page'] ?? "home");
  10. ?>
  11. <!DOCTYPE html>
  12. <html

    lang

    =

    "en"

    >
  13. <head

    >
  14. <meta

    charset

    =

    "UTF-8"

    >
  15. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  16. <title

    >

    Sample Website | <?=

    ucwords(

    $page)

    ?>

    Page</

    title

    >
  17. <!-- Bootstrap 5.3 CSS-->
  18. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    >
  19. <!-- jQuery -->
  20. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"

    ></

    script

    >
  21. <!-- Bootstrap 5.3 JS-->
  22. <script

    src

    =

    " https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"

    ></

    script

    >
  23. </

    head

    >
  24. <body

    >
  25. <nav

    class

    =

    "navbar navbar-expand-lg bg-body-tertiary"

    >
  26. <div

    class

    =

    "container-fluid"

    >
  27. <a

    class

    =

    "navbar-brand"

    href

    =

    "#"

    >

    Sample Website</

    a

    >
  28. <button

    class

    =

    "navbar-toggler"

    type

    =

    "button"

    data-bs-toggle=

    "collapse"

    data-bs-target

    =

    "#navbarNav"

    aria-controls=

    "navbarNav"

    aria-expanded=

    "false"

    aria-label

    =

    "Toggle navigation"

    >
  29. <span

    class

    =

    "navbar-toggler-icon"

    ></

    span

    >
  30. </

    button

    >
  31. <div

    class

    =

    "collapse navbar-collapse"

    id

    =

    "navbarNav"

    >
  32. <ul

    class

    =

    "navbar-nav"

    >
  33. <li

    class

    =

    "nav-item"

    >
  34. <a

    class

    =

    "nav-link <?= $page == 'home' ? "

    active" : '' ?>

    " href="./">Home</

    a

    >
  35. </

    li

    >
  36. <li

    class

    =

    "nav-item"

    >
  37. <a

    class

    =

    "nav-link <?= $page == 'about_us' ? "

    active" : '' ?>

    " href="./?page=about_us">About Us</

    a

    >
  38. </

    li

    >
  39. <li

    class

    =

    "nav-item"

    >
  40. <a

    class

    =

    "nav-link <?= $page == 'contact_us' ? "

    active" : '' ?>

    " href="./?page=contact_us">Contact Us</

    a

    >
  41. </

    li

    >
  42. <li

    class

    =

    "nav-item"

    >
  43. <a

    class

    =

    "nav-link <?= $page == 'site_visits' ? "

    active" : '' ?>

    " href="./?page=site_visits">Visit Logs</

    a

    >
  44. </

    li

    >
  45. </

    ul

    >
  46. </

    div

    >
  47. </

    div

    >
  48. </

    nav

    >
  49. <div

    class

    =

    "container-md py-4"

    >
  50. <h4

    class

    =

    "text-center"

    ><strong

    ><?=

    ucwords(

    $page)

    ?>

    Page</

    strong

    ></

    h4

    >
  51. <?php
  52. if(

    $page ==

    "site visits"

    )
  53. include(

    'site-visits.php'

    )

    ;
  54. ?>
  55. </

    div

    >

  56. </

    body

    >
  57. </

    html

    >

Visit Log Display Page

Finally, let's develop the page that showcases the stored visit logs from the database. This file consists of a combination of both `PHP

` and HTML5

scripts. Save this script as `site-visits.php

`.

  1. <?php
  2. include

    (

    "db-connect.php"

    )

    ;
  3. ?>
  4. <div class="col-12">
  5. <div class="card rounded-0">
  6. <div class="card-body">
  7. <div class="container-fluid">
  8. <div class="table-responsive">
  9. <table class="table table-striped table-bordered">
  10. <colgroup>
  11. <col width="15%">
  12. <col width="15%">
  13. <col width="20%">
  14. <col width="20%">
  15. <col width="30%">
  16. </colgroup>
  17. <thead>
  18. <tr class="bg-dark text-light">
  19. <th class="text-center">Date/Time</th>
  20. <th class="text-center">IP</th>
  21. <th class="text-center">URL</th>
  22. <th class="text-center">Referer</th>
  23. <th class="text-center">User Agent</th>
  24. </tr>
  25. </thead>
  26. <tbody>
  27. <?php
  28. $visits

    =

    $conn

    ->

    query

    (

    "SELECT * FROM `visit_logs` order by abs(unix_timestamp(`date_created`)) desc"

    )

    ;
  29. if

    (

    $visits

    ->

    num_rows

    >

    0

    )

    :
  30. ?>
  31. <?php

    while

    (

    $row

    =

    $visits

    ->

    fetch_assoc

    (

    )

    )

    :

    ?>
  32. <tr>
  33. <td><?=

    date

    (

    "M d, Y g:i:s A"

    ,

    strtotime

    (

    $row

    [

    'date_created'

    ]

    )

    )

    ?>

    </td>
  34. <td><?=

    $row

    [

    'user_ip'

    ]

    ?>

    </td>
  35. <td><?=

    $row

    [

    'page_url'

    ]

    ?>

    </td>
  36. <td><?=

    $row

    [

    'reference_url'

    ]

    ?>

    </td>
  37. <td><?=

    $row

    [

    'user_agent'

    ]

    ?>

    </td>
  38. </tr>
  39. <?php

    endwhile

    ;

    ?>
  40. <?php

    else

    :

    ?>
  41. <tr>
  42. <th class="text-center" colspan="5">No Data</th>
  43. </tr>
  44. <?php

    endif

    ;

    ?>
  45. </tbody>
  46. </table>
  47. </div>
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. <?php
  53. $conn

    ->

    close

    (

    )

    ;
  54. ?>

The provided source code will generate the results as shown in the following images:

And there you have it! I hope this Storing Visitors Log in the Database using PHP and MySQL Tutorial will help you with your current project or you'll find this useful for your future PHP projects. Explore more on this website for more Free Source Codes, Tutorials, and Articles covering various programming languages.

Happy Coding =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

331,932

331,940

Top