I want to count and show live users counter on my page. My url structure looks like this domain.com/miningbot?id=pool-v9w1x2y
The users which are inside the parameter should be counted, updated and displayed to the user. Also, the parameter can be changed.
I have asked ChatGPT to write me some starting script and here it is but i don't get the part with the WebSocket
miningbot.html JS:
// Get the id parameter from the URL
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');
// Send an AJAX request to increment the visitor count for the id value
const xhr = new XMLHttpRequest();
xhr.open('POST', 'update_visitor_count.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(`id=${id}`);
// Update the live visitor count on the page
const visitorCountElement = document.getElementById('visitor-count');
setInterval(() => {
fetch(`get_visitor_count.php?id=${id}`)
.then(response => response.text())
.then(count => {
visitorCountElement.textContent = count;
});
}, 5000); // Update every 5 seconds
get_visitor_count.php
<?php
// Get the id value from the GET request
$id = $_GET['id'];
// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Get the visitor count for the corresponding id value
$sql = "SELECT count FROM visitor_counts WHERE id = '$id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$count = $row['count'];
// Close the database connection
mysqli_close($conn);
// Output the visitor count as plain text
echo $count;
?>
The second PHP code that updates the visitor count in the database should be included in the WebSocket server script that listens for connections and receives messages from the client. (this is the part i don't understand, what should i do?)
<?php
// Get the id value from the POST request
$id = $_POST['id'];
// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Increment the visitor count for the corresponding id value
$sql = "UPDATE visitor_counts SET count = count + 1 WHERE id = '$id'";
mysqli_query($conn, $sql);
// Close the database connection
mysqli_close($conn);
?>
I asked namecheap hosting support they told me this:
Regretfully, it is not possible to install the WebSocket to the shared server. However, you can easily connect to the WebSocket server. For that, you will need to specify the port for the outgoing connection.
It is usually 443, and it is open on our end, but if your application will need any other port, we will open it from our end.