View Single Post
  #3  
Old 5th September 2025, 07:57
crowni's Avatar
crowni crowni is offline
Coder
 
Join Date: Apr 2009
Bulgaria
Posts: 195
Default ?
What other scenario? This is a foundation on which you can build upon yourself! When I build upon it and finish it, I might even release it for general download as open source!

Overview

A fully-featured Torrent tracker-Markoni built in PHP 8, with user registration, torrent upload, forum, admin panel, dark/light themes, chat, and real-time peer tracking.


Code:
/torrent-tracker/
│
├── index.php                  - Homepage with latest torrents and chat
├── register.php               - User registration
├── login.php                  - Login form
├── logout.php                 - Logout script
├── upload.php                 - Upload torrents + cover images
├── torrent.php                - Torrent details page
├── tracker.php                - BitTorrent tracker (handles announce requests)
├── toggle-theme.php           - Switch between light/dark theme
├── chat.php                   - Chat system (AJAX-based)
│
├── header.php                 - Shared header with navigation
├── add-comment.php            - Add comment to a torrent
│
├── install.php                - Installation wizard (one-time setup)
├── install-schema.sql         - Database schema for installer
├── config.php                 - Auto-generated config (DB settings, debug)
│
├── includes/
│   ├── db.php                 - Database connection (uses config.php)
│   └── functions.php          - Helper functions (debug, security, etc.)
│
├── css/
│   ├── light.css              - Light theme styles
│   └── dark.css               - Dark theme styles
│
├── js/
│   └── theme-toggle.js        - JavaScript for theme switching
│
├── uploads/
│   ├── torrents/              - Stores uploaded .torrent files
│   └── images/                - Stores cover images for torrents
│
├── api/
│   ├── tracker-stats.php      - Returns seeders/leechers (JSON)
│   └── latest-torrents.php    - Returns latest torrents (JSON)
│
├── admin/
│   ├── index.php              - Admin dashboard
│   ├── manage-users.php       - Add/edit/delete users
│   ├── manage-forums.php      - Manage forum categories
│   ├── manage-themes.php      - Enable/disable themes
│   ├── manage-image-settings.php - Set image size/pixel limits
│   └── peers.php              - View active peers in real-time
│
├── .htaccess                  - Security: blocks PHP execution in uploads/
└── README.md                  - Project documentation

Code:
<h2 data-spm-anchor-id="a2ty_o01.29997173.0.i162.b4c1c921HVxTlA"><h2 data-spm-anchor-id="a2ty_o01.29997173.0.i162.b4c1c921HVxTlA">Database Tables

</h2>




















(torrent_tracker) </h2>

users
Registered users (username, email, password, role, passkey)
 torrents
Torrent info (name, size, hash, seeders, leechers, image path)
 comments
Comments on torrents
 forums
Forum categories
 forum_topics
Topics within forums
 forum_posts
Posts in topics
 themes
Light/dark theme definitions
 user_settings
User-selected theme
 chat_messages
Real-time chat messages
 peers
Active peers (IP, port, seeder status)
 site_settings
Configurable image limits (size, resolution)

Core Features & Functions
1. User System

✅ Registration & login with password hashing
✅ Roles: user and admin
✅ Session-based authentication


2. Torrent Upload

✅ Upload .torrent files
✅ Auto-inject passkey into announce URL
✅ Parse .torrent info (BDecode)
✅ Store info_hash, size, name


3. Cover Images

✅ Upload cover image with torrent
✅ Validate file type, size, and dimensions
✅ Admin can set limits (max size, width, height)
✅ Display image in torrent.php


4. BitTorrent Tracker (tracker.php)

✅ Handles announce requests from clients
✅ Validates passkey for security
✅ Tracks peers (IP, port, seeder status)
✅ Returns peers, seeders, leechers in bencoded format
✅ Supports started, stopped, completed events


5. Real-Time Stats

✅ AJAX updates for seeders/leechers
✅ api/tracker-stats.php – returns JSON stats
✅ Auto-refresh every 5–10 seconds


6. Chat System

✅ Real-time chat for logged-in users
✅ Messages stored in chat_messages
✅ Auto-refresh via AJAX
✅ Username and timestamp shown
✅ Admin role highlighted in red


7. Admin Panel

✅ User management (ban, promote to admin)
✅ Forum management
✅ Theme management (light/dark)
✅ Image settings (size, resolution)
✅ Active peers monitor (peers.php)


8. Themes (Light/Dark Mode)

✅ Toggle via button
✅ Stored in session
✅ CSS files: light.css, dark.css
✅ Applied globally


9. Auto Installer

✅ install.php – step-by-step setup
✅ Creates DB tables from install-schema.sql
✅ Creates admin account
✅ Generates config.php
✅ Deletes itself after installation


10 Security

✅ passkey per user (prevents external use)
✅ .htaccess blocks PHP in uploads/
✅ Input sanitization and prepared statements
✅ CSRF-safe forms
✅ Only logged-in users can chat/upload


Code:
Helper Functions 



bencode() / bdecode()
upload.php, tracker.php
Encode/decode .torrent files
 debug($data)
includes/functions.php
Print debug info (secure)
 htmlspecialchars()
Inline
Prevent XSS in output
 loadChat()
index.php
Load chat messages via AJAX
 updateStats()
index.php, torrent.php
Update seeders/leechers in real-time

How to Install

Upload all files to your server
Visit http://yoursite.com/install.php
Enter DB credentials and admin info
Installer creates DB, tables, config, folders
Installer deletes itself
Site is ready!


PHP 8+ – Backend logic
MySQL – Database
HTML/CSS/JS – Frontend
AJAX – Real-time updates
BitTorrent Protocol – Tracker support
PDO – Secure database access
BEncode/BDecode – .torrent file handling


Security Notes

  • Never expose config.php or install.php publicly
  • Use .htaccess to block access to sensitive files
  • Always set 'debug' => false on live sites
  • Validate and sanitize all user input


The project is under development so I expect you to test it and comment. I may have missed something.

Bump: Anyone who wishes can add a debug setting to config.php

After installation, manually edit config.php or add this option to install.php later.

Updated config.php (example)

HTML Code:
<?php$config = [    'db_host' => 'localhost',    'db_name' => 'torrent_tracker',    'db_user' => 'root',    'db_pass' => '',    'debug'   => true,  // Промени на false в production    'debug_key' => 'secret123'  // парола за debug режим];?>

Code:
In production (live site) always set 'debug' => false

Update includes/db.php with debug mode


HTML Code:
<?php// includes/db.php - С debug режимif (!file_exists(__DIR__ . '/../config.php')) {    die("❌ Конфигурационният файл липсва! Моля, стартирайте инсталацията: <a href='/install.php'>/install.php</a>");}require_once __DIR__ . '/../config.php';if (!isset($config) || !is_array($config)) {    die("❌ Невалиден конфигурационен файл.");}$cfg = $config;$debug = $cfg['debug'] ?? false;$debug_key = $cfg['debug_key'] ?? 'secret123';$host = $cfg['db_host'] ?? 'localhost';$dbname = $cfg['db_name'] ?? 'torrent_tracker';$username = $cfg['db_user'] ?? 'root';$password = $cfg['db_pass'] ?? '';$charset = 'utf8mb4';$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";$options = [    PDO::ATTR_ERRMODE            => $debug ? PDO::ERRMODE_EXCEPTION : PDO::ERRMODE_SILENT,    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,    PDO::ATTR_EMULATE_PREPARES   => false,];try {    $pdo = new PDO($dsn, $username, $password, $options);} catch (PDOException $e) {    if ($debug) {        // Показвай грешка само ако има debug_key в URL или си админ        $show_error = false;        // Вариант 1: Ако в URL има ?debug=secret123        if (isset($_GET['debug']) && $_GET['debug'] === $debug_key) {            $show_error = true;        }        // Вариант 2: Ако си логнат админ        session_start();        if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin') {            $show_error = true;        }        if ($show_error) {            die("<h3 style='color:red'>❌ DB Грешка</h3>                 <p><b>Код:</b> " . $e->getCode() . "</p>                 <p><b>Съобщение:</b> " . htmlspecialchars($e->getMessage()) . "</p>                 <p><b>Файл:</b> " . $e->getFile() . " : " . $e->getLine() . "</p>                 <pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>");        }    }    // Ако не е debug, покажи обща грешка    die("❌ Не може да се свърже към базата данни.");}?>

Add debug logger function (in includes/functions.php)

Create file: includes/functions.php


HTML Code:
<?php// includes/functions.phpfunction debug($data, $label = 'Debug') {    global $config;    if (!($config['debug'] ?? false)) return;    // Показвай само ако има debug_key или си админ    $show = false;    if (isset($_GET['debug']) && $_GET['debug'] === ($config['debug_key'] ?? 'secret123')) {        $show = true;    }    session_start();    if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin') {        $show = true;    }    session_write_close();    if (!$show) return;    echo "<div style='background:#222; color:#0f0; font-family:monospace; padding:10px; margin:10px 0; border-radius:5px; overflow:auto; font-size:14px;'>";    echo "<strong>�� $label</strong><br>";    echo "<pre>" . print_r($data, true) . "</pre>";    echo "</div>";}?>

How to use debug in code?


In index.php, torrent.php, etc.:


HTML Code:
<?phprequire 'includes/functions.php';debug($_SESSION, 'SESSION данни');debug($torrent, 'TORRENT от базата');debug($_GET, 'GET параметри');?>

It will only be shown if you are in debug mode and have permission to see it.


Debug bar at the bottom (tail)


Add at the end of footer.php or before </body>:


HTML Code:
<?php if (($config['debug'] ?? false) && (isset($_GET['debug']) && $_GET['debug'] === ($config['debug_key'] ?? 'secret123'))) : ?><div style="position:fixed; bottom:0; left:0; width:100%; background:#111; color:#0f0; font-family:monospace; font-size:12px; padding:5px; z-index:9999; border-top:2px solid #0f0; max-height:200px; overflow:auto;">    ⚙️ <b>Debug Mode</b> | PHP: <?= PHP_VERSION ?> | MySQL: <?= $pdo->query('SELECT VERSION()')->fetchColumn() ?> | Memory: <?= round(memory_get_usage() / 1024) ?> KB</div><?php endif; ?>

How to enable debug mode?


Open in browser:


http://yoursite.com/index.php?debug=secret123


If debug_key is correct, you will see:

SQL errors
Logs from debug()
Session information, requests, etc.
Attached Files
File Type: zip Torrent tracker-Markoni.zip (32.4 KB, 17 views)
Reply With Quote
The Following User Says Thank You to crowni For This Useful Post:
Fynnon (12th September 2025)