PHP Code гости онлайн

ArenaPlay

Registered
Здравейте,
Може ли някой да ми предложи някакъв код който да виждам колко гости имам онлайн в сайта.
 
SQL:
CREATE TABLE online_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ip_address VARCHAR(255) NOT NULL,
    last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

PHP:
<?php
// Database connection
$servername = "your_database_server";
$username = "your_database_username";
$password = "your_database_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get user's IP address
$ip = $_SERVER['REMOTE_ADDR'];

// Check if the user's IP address is already in the database
$sql = "SELECT id FROM online_users WHERE ip_address = '$ip'";
$result = $conn->query($sql);

if ($result->num_rows == 0) {
    // Insert the user's IP address into the database
    $sql = "INSERT INTO online_users (ip_address) VALUES ('$ip')";
    $conn->query($sql);
} else {
    // Update the last activity time for the user
    $sql = "UPDATE online_users SET last_activity = CURRENT_TIMESTAMP WHERE ip_address = '$ip'";
    $conn->query($sql);
}

// Calculate the number of online users (active within the last 5 minutes, for example)
$online_threshold = date('Y-m-d H:i:s', strtotime('-5 minutes'));
$sql = "SELECT COUNT(id) as online_count FROM online_users WHERE last_activity > '$online_threshold'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $online_count = $row['online_count'];
    echo "Online users: $online_count";
}

// Close the database connection
$conn->close();
?>

ChatGPT.png
 
Може ли някой да помогне да го вградим тука
PHP:
session_start();
require('config.php');
if($_POST['select_language'] == 1 || (strcmp($_POST['select_language'],"1") == 0))
{
    require_once('include/settings.php');
    
    $l_id = (int) $_POST['lang_id'];
    if( ! array_key_exists($l_id, $langs) )
    {
        $l_id = 1;
    }
    
    setcookie(COOKIE_LANG, $l_id, time()+COOKIE_TIME, COOKIE_PATH);
    exit();
}

//require_once('include/functions.php');
require_once('include/user_functions.php');
require_once('include/islogged.php');

// define meta tags & common variables
if ('' != $config['homepage_title'])
{
    $meta_title = $config['homepage_title'];
}
else
{
    $meta_title = sprintf($lang['homepage_title'], _SITENAME);   
}
$meta_keywords = $config['homepage_keywords'];
$meta_description = $config['homepage_description'];
// end

$top_videos = top_videos($config['top_videos_sort'], _TOPVIDS);
$new_videos = get_video_list('added', 'desc', 0, _NEWVIDS);
$featured_videos = get_featured_video_list((int) $config['homepage_featured_limit']);
$total_featured_videos = pm_count($featured_videos);

// pull out featured categories data
$featured_categories_data = array();
$featured_categories = ($config['homepage_featured_categories'] != '') ? unserialize($config['homepage_featured_categories']) : array();
if (pm_count($featured_categories) > 0)
{
    load_categories();
    foreach ($_video_categories as $cid => $category_data)
    {
        $_video_categories[$cid]['url'] = make_link('category', array('tag' => $category_data['tag']));
    }
    
    foreach ($featured_categories as $k => $cid)
    {
        $featured_categories_data[$cid] = get_video_list('added', 'desc', 0, 10, $cid);
    }
}

if($config['show_tags'] == 1)
{
    $tag_cloud = tag_cloud(0, $config['tag_cloud_limit'], $config['shuffle_tags']);
    $smarty->assign('tags', $tag_cloud);
    $smarty->assign('show_tags', 1);
}

if($config['show_stats'] == 1)
{
    $stats = stats();
    $smarty->assign('stats', $stats);
    $smarty->assign('show_stats', 1);
}

//    Get latest articles
if (_MOD_ARTICLE)
{
    $articles = art_load_articles(0, $config['article_widget_limit']);

    if ( ! array_key_exists('type', $articles))
    {
        foreach ($articles as $id => $article)
        {
            $articles[$id]['title'] = fewchars($article['title'], 55);
        }
        $smarty->assign('articles', $articles);
    }
}

$playingnow = videosplaying($config['playingnow_limit']);
$total_playingnow = (is_array($playingnow)) ? pm_count($playingnow) : 0;

if ($config['player_autoplay'] == '0' && $video['video_player'] != 'embed' && $video['source_id'] != 3)
{
    // don't update site_views for this video. It will be updated when the user hits the play button.
}
else
{
    // in all other cases, update site_views on page load.
    if ($total_featured_videos == 1)
    {
        update_view_count($featured_videos[0]['id'], $featured_videos[0]['site_views'], false);
    }
}

// MAKE SORT BY STICK
if(!empty($cat_id)) {
    $list_cats = list_categories(0, $cat_id);
    $smarty->assign('list_categories', $list_cats);
} else {
    $list_cats = list_categories(0, '');
    $smarty->assign('list_categories', $list_cats);
}

// pre-roll [static] ads & subtitles
if ($total_featured_videos == 1)
{
    serve_preroll_ad('index', $featured_videos[0]);
    $smarty->assign('video_subtitles', (array) get_video_subtitles($featured_videos[0]['uniq_id']));
}

$smarty->assign('total_playingnow', $total_playingnow);
$smarty->assign('playingnow', $playingnow);

$smarty->assign('featured_videos', $featured_videos);
$smarty->assign('featured_videos_total', $total_featured_videos);
$smarty->assign('featured_channels', get_featured_channels());
$smarty->assign('new_videos', $new_videos);
$smarty->assign('top_videos', $top_videos);
$smarty->assign('categories', $_video_categories);
$smarty->assign('featured_categories_data', $featured_categories_data);
// --- DEFAULT SYSTEM FILES - DO NOT REMOVE --- //
$smarty->assign('meta_title', htmlspecialchars($meta_title));
$smarty->assign('meta_keywords', htmlspecialchars($meta_keywords));
$smarty->assign('meta_description', htmlspecialchars($meta_description));
$smarty->assign('template_dir', $template_f);
$smarty->display('index.tpl');

Изважда се тука

Код:
            {if $show_stats == 1}
            <div class="widget">
                <h4>{$lang.site_stats}</h4>
                <ul class="pm-ul-stats list-unstyled">
                    <li><a href="{$smarty.const._URL}/memberlist.{$smarty.const._FEXT}?do=online">{$lang.online_users}</a> <span class="pm-stats-count">{$stats.online_users}</span></li>
                    <li><a href="{$smarty.const._URL}/memberlist.{$smarty.const._FEXT}">{$lang.total_users}</a> <span class="pm-stats-count">{$stats.users}</span></li>
                    <li>{$lang.total_videos} <span class="pm-stats-count">{$stats.videos}</span></li>
                    <li>{$lang.videos_added_lw} <span class="pm-stats-count">{$stats.videos_last_week}</span></li>
                </ul>
            </div><!-- .widget -->
            {/if}
Благодаря предварително:)
 
Най-вероятно не ти трябват подобни неща, защото системата ти трябва да има sessions таблица в датабазата и само 1 sql заявка ще трябва. Провери си.
 
Най-вероятно не ти трябват подобни неща, защото системата ти трябва да има sessions таблица в датабазата и само 1 sql заявка ще трябва. Провери си.
Нямам никъде в базата данни това "sessions"

А users има само това
PHP:
DROP TABLE IF EXISTS `pm_users`;
CREATE TABLE `pm_users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL DEFAULT '',
  `password` varchar(100) NOT NULL DEFAULT '',
  `name` varchar(150) NOT NULL DEFAULT '',
  `gender` varchar(10) NOT NULL DEFAULT '',
  `country` varchar(50) NOT NULL DEFAULT '',
  `reg_ip` varchar(40) NOT NULL DEFAULT '',
  `reg_date` int(10) unsigned NOT NULL DEFAULT '0',
  `last_signin` int(10) unsigned NOT NULL DEFAULT '0',
  `last_signin_ip` varchar(40) NOT NULL DEFAULT '',
  `email` varchar(150) NOT NULL DEFAULT '',
  `favorite` enum('0','1') NOT NULL DEFAULT '1',
  `power` enum('0','1','2','3','4') NOT NULL DEFAULT '0',
  `about` text NOT NULL,
  `avatar` varchar(255) NOT NULL DEFAULT 'default.gif',
  `activation_key` varchar(20) NOT NULL DEFAULT '',
  `new_password` varchar(32) NOT NULL DEFAULT '',
  `followers_count` int(10) unsigned NOT NULL DEFAULT '0',
  `following_count` int(10) unsigned NOT NULL DEFAULT '0',
  `unread_notifications_count` int(10) unsigned NOT NULL DEFAULT '0',
  `social_links` text NOT NULL,
  `channel_slug` varchar(255) NOT NULL DEFAULT '',
  `channel_cover` varchar(255) NOT NULL DEFAULT '',
  `channel_verified` enum('0','1') NOT NULL DEFAULT '0',
  `channel_featured` enum('0','1') NOT NULL DEFAULT '0',
  `channel_settings` text NOT NULL DEFAULT '',
  `fb_user_id` varchar(40) NOT NULL DEFAULT '',
  `fb_access_token` varchar(255) NOT NULL DEFAULT '',
  `twitter_user_id` varchar(40) NOT NULL DEFAULT '',
  `google_user_id` varchar(40) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `email` (`email`),
  KEY `channel_slug` (`channel_slug`),
  KEY `channel_featured` (`channel_featured`),
  KEY `fb_user_id` (`fb_user_id`),
  KEY `twitter_user_id` (`twitter_user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
 
Hmm, ок.
Кода на blinky ще свърши работа иначе, но ще трябва преработка, защото config дефинициите не ти трябват, ти си имаш. Не знаем дали ползваш mysqli или pdo.
Също така от неговия код $online_count = $row['online_count']; трябва да го минеш през smarty assign функцията, за да може да го ползваш в темплейта след това и да го изкараш.
Ще трябват промени, но така без някой да има достъп било ftp или team viewer ще е трудничко, няма възможност за тестове. Така мисля.
Аз се прибирам до седмица и няколко дни 2-3.
Ще ти помогна, ако някой не го е направил преди мен..
 
Да, ще ми е интересно да видя и аз как излиза в краен вариант. Моят пример реално е базов, и вече ако има нужда от някакви леки пипания според средата и архитектурата на системата.
 

Горе