Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
User Posts

Go to Profile

External UDP/HTTPS scrape — 2026-02-24 21:51:21 in v3 Support
You should have a button to click that will execute the scrape on the torrents-details page of the external torrent and display the tracker stats and final aggregated totals https://i.postimg.cc/3x40W0jj/Screenshot-2026-02-24-164930.png and here https://postimg.cc/LJ8r5Fqx and here https://i.postimg.cc/Px9rg29f/Screenshot-2026-02-24-165417.jpg
External UDP/HTTPS scrape — 2026-02-23 19:54:00 in v3 Support
I had a typo in my code above. fixed. try again. Ignore the 2 files I attached here. I cant delete them since this forum is broken
External UDP/HTTPS scrape — 2026-02-22 18:43:26 in v3 Support
Try replacing this part of your code. You will have to test and see if its right for your file.
if ($row["external"]=='yes'){

if ($scrape =='1'){
print("<td valign='top' align='right'><b>Tracked: </b>EXTERNAL<br /><br />");
$seeders1 = $leechers1 = $downloaded1 = null;

$tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
while ($trow = mysqli_fetch_assoc($tres)) {
$ann = $trow["url"];
$tracker = explode("/", $ann);
$path = array_pop($tracker);
$oldpath = $path;
$path = preg_replace("/^announce/", "scrape", $path);
$tracker = implode("/", $tracker)."/".$path;

if ($oldpath == $path) {
continue; // Scrape not supported, ignored
}

// TPB's tracker is dead. Use openbittorrent instead
if (preg_match("/thepiratebay.org/i", $tracker) || preg_match("/prq.to/", $tracker)) {
$tracker = "http://tracker.openbittorrent.com/scrape";
}

$stats = torrent_scrape_url($tracker, $row["info_hash"]);
if ($stats['seeds'] != -1) {
$seeders1 += $stats['seeds'];
$leechers1 += $stats['peers'];
$downloaded1 += $stats['downloaded'];
SQL_Query_exec("UPDATE `announce` SET `online` = 'yes', `seeders` = $stats[seeds], `leechers` = $stats[peers], `times_completed` = $stats[downloaded] WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");
} else {
SQL_Query_exec("UPDATE `announce` SET `online` = 'no' WHERE `url` = ".sqlesc($ann)." AND `torrent` = $id");

}
}

if ($seeders1 !== null){ //only update stats if data is received
print ("<b>".T_("LIVE_STATS").": </b><br />");
print ("Seeders: ".number_format($seeders1)."<br />");
print ("Leechers: ".number_format($leechers1)."<br />");
print (T_("COMPLETED").": ".number_format($downloaded1)."<br />");

SQL_Query_exec("UPDATE torrents SET leechers='".$leechers1."', seeders='".$seeders1."', times_completed='".$downloaded1."',last_action= '".get_date_time()."',visible='yes' WHERE id='".$row['id']."'");
}else{
print ("<b>".T_("LIVE_STATS").": </b><br />");
print ("<font color='#ff0000'>Tracker Timeout<br />Please retry later</font><br />");
}

print ("<form action='torrents-details.php?id=$id&scrape=1' method='post'><input type=\"submit\" name=\"submit\" value=\"Update Stats\" /></form></td>");
}else{
print ("<td valign='top' align='right'><b>Tracked:</b> EXTERNAL<br /><br /><form action='torrents-details.php?id=$id&scrape=1' method='post'><input type=\"submit\" name=\"submit\" value=\"Update Stats\" /></form></td>");
}
}

echo "</tr>



</table>";
}
echo "</div>



<br>
<center>
<b>
[Dire merci = 10 points Seed Bonus]
</b>
&nbsp;

:::

&nbsp;

<b>
[1 Commentaire = 20 points Seed Bonus]
</b>
</center>
<br>


<center>
<b>Pour télécharger vous devez installer Utorrent !!!</b>
&nbsp;>>&nbsp;

<button>
<a href=\"/clients-bittorrent/1.8.4_utorrent-1.8.4.exe\" target='_blank'>&nbsp;&nbsp;
<b>UTorrent </b>
</button>

&nbsp;:::&nbsp;

<button>
<a href=\"/clients-bittorrent/qbittorrent_4.3.9_setup.exe\" target='_blank'>&nbsp;&nbsp;
<b>qBittorrent</b>
</button>

&nbsp;:::&nbsp;

<button>
<a href=\"/clients-bittorrent/uTorrent.dmg\" target='_blank'>&nbsp;&nbsp;
<b>UTorrent pour Mac</b>
</button></center>

<br>



</td></tr></table></center><br /><br />";
Here is a better version of this https://torrenttrader.uk/post/1951.

SQL:
CREATE TABLE IF NOT EXISTS `notconnectablepmlog` (
`id` int(10) unsigned NOT NULL auto_increment,
`user` int(10) unsigned NOT NULL default '0',
`date` datetime default NULL,
PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1;


In admincp.php, drop this in somewhere
// begin unconnectable peers section

if ($_GET['action'] == "listunconnectable") {
$res2 = SQL_Query_exec("SELECT userid, seeder, torrent, client FROM peers WHERE connectable='no' ORDER BY userid DESC") or sqlerr();

stdhead("Peers that are unconnectable");

begin_frame("Unconnectable");

print("<br/><a href=admincp.php?action=sendpmunconnectable>Send all not connectable users a PM</a>");
print("<br/><a href=admincp.php?action=viewlogsunconnectable>View the Log (Check this before PMing users)</a>");
print("<br/>Peers that are Not Connectable");
print("<br/>This is only users that are active on the torrents right now.");
print("<br/><font color=red>*</font> means the user is seeding.<p>");
$result = SQL_Query_exec("SELECT DISTINCT userid FROM peers WHERE connectable = 'no'");
$count = mysqli_num_rows($result);
print ("$count unique users that are not connectable ");
$result2 = SQL_Query_exec("SELECT DISTINCT torrent FROM peers WHERE connectable = 'no'");
$count2 = mysqli_num_rows($result2);
print ("on $count2  torrents.");
@mysqli_free_result($result);

if (mysqli_num_rows($res2) == 0) {
print("<p align=center><b>All Peers Are Connectable!</b></p>\n");
} else {

// Group torrents per user
$users = [];

while ($row = mysqli_fetch_assoc($res2)) {
$users[$row['userid']][] = $row;
}

print("<table border=1 cellspacing=0 cellpadding=5>");
print("<tr>
<td class=colhead>User</td>
<td class=colhead>Torrents</td>
<td class=colhead>Client(s)</td>
</tr>");

foreach ($users as $userid => $torrents) {

// Fetch username once per user
$u = SQL_Query_exec("SELECT username FROM users WHERE id = $userid");
$user = mysqli_fetch_assoc($u);

print("<tr>");

// Username
print("<td>
<a href='account-details.php?id=$userid'>{$user['username']}</a>
</td>");

// Torrent dropdown
print("<td>");
print("<select onchange=\"if(this.value) window.location=this.value\">");
print("<option value=''>Select torrent…</option>");

foreach ($torrents as $t) {
$label = $t['torrent'];
if ($t['seeder'] === 'yes') {
$label .= " *";
}

print("<option value='torrents-details.php?id={$t['torrent']}&dllist=1#seeders'>
$label
</option>");
}

print("</select>");
print("</td>");

// Client list (unique, clean)
$clients = array_unique(array_column($torrents, 'client'));
print("<td>" . implode("<br>", array_map('htmlspecialchars', $clients)) . "</td>");

print("</tr>");
}

print("</table>");


}
end_frame();
navmenu();
stdfoot();
}


if (isset($_GET["returnto"]) || isset($_SERVER["HTTP_REFERER"])) {
   $returnto = isset($_GET["returnto"]) ? $_GET["returnto"] : $_SERVER["HTTP_REFERER"];
   $returnto = htmlspecialchars($returnto, ENT_QUOTES, 'UTF-8');
}
?>
   <input type="hidden" name="returnto" value="<?php echo $returnto; ?>" />

   
<?php

if ($_GET['action'] == "sendpmunconnectable") {

if ($_SERVER["REQUEST_METHOD"] === "POST") {

$msg = trim($_POST['msg']);

if ($msg === '') {
show_error_msg("Error", "Please Type In Some Text.", 1);
}

// Send PM to all unconnectable users
$res = SQL_Query_exec("
SELECT DISTINCT userid
FROM peers
WHERE connectable = 'no'
") or sqlerr(__FILE__, __LINE__);

while ($row = mysqli_fetch_assoc($res)) {
SQL_Query_exec("
INSERT INTO messages (sender, receiver, added, msg, subject)
VALUES (
0,
{$row['userid']},
'" . get_date_time() . "',
" . sqlesc($msg) . ",
'Firewall / NAT Connectivity Issue'
)
") or sqlerr(__FILE__, __LINE__);
}

// Log the action
$dt = sqlesc(get_date_time());
SQL_Query_exec("
INSERT INTO notconnectablepmlog (user, date)
VALUES ({$CURUSER['id']}, $dt)
") or sqlerr(__FILE__, __LINE__);

write_log("A PM was sent to unconnectable users by ({$CURUSER['username']})");

// Redirect to log page
header("Location: admincp.php?action=viewlogsunconnectable");
exit;
}

stdhead("Peers that are unconnectable");
begin_frame("Send PM");

// Default message
$body = "The tracker detected that your client is firewalled or behind NAT, so it can’t accept incoming connections. This limits who can connect to you and may reduce speeds.\n\nTo fix this, port forward the same port range set in your torrent client on your router or firewall. Setup varies by router—see PortForward.com for guides.\n\nIf you need help, post in the forums or shoutbox and we’ll help you figure it out.";
?>

<table class="main" width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="embedded">
<div align="center">
<h1>Mass Message to All Non-Connectable Users</h1>

<form method="post" action="admincp.php?action=sendpmunconnectable">

<table cellspacing="0" cellpadding="5">
<tr>
<td>
Send Mass Message To All Users Currently Marked As Not Connectable
</td>
</tr>

<tr>
<td>
<textarea name="msg" cols="120" rows="15"><?php echo htmlspecialchars($body); ?></textarea>
</td>
</tr>

<tr>
<td align="center">
<input type="submit" value="Send PM" class="btn">
</td>
</tr>
</table>

</form>
</div>
</td>
</tr>
</table>

<?php
end_frame();
navmenu();
stdfoot();
}


if ($_GET['action'] == "viewlogsunconnectable") {

stdhead("Unconnectable Peers Mass PM Log");
begin_frame("Unconnectable PM Logs");

// Handle clearing logs
if (isset($_GET['clear']) && $_GET['clear'] === 'all') {
SQL_Query_exec("TRUNCATE TABLE notconnectablepmlog") or sqlerr();
write_log("Admin ({$CURUSER['username']}) cleared the Unconnectable PM log");
header("Location: admincp.php?action=viewlogsunconnectable");
exit;
}

if (isset($_GET['clear']) && $_GET['clear'] === 'old') {
SQL_Query_exec("DELETE FROM notconnectablepmlog WHERE date < NOW() - INTERVAL 30 DAY") or sqlerr();
write_log("Admin ({$CURUSER['username']}) pruned the Unconnectable PM log older than 30 days");
header("Location: admincp.php?action=viewlogsunconnectable");
exit;
}

$getlog = SQL_Query_exec("
SELECT user, date
FROM notconnectablepmlog
ORDER BY date DESC
LIMIT 100
");

print("Unconnectable Peers Mass PM Log");
print("<br/><br/><a href='admincp.php?action=sendpmunconnectable'><b>* Send all not connectable users a PM</b></a>");
print("<br/><a href='admincp.php?action=listunconnectable'><b>* List Unconnectable Users</b></a>");
print("<br/><br/>Please don't use the mass PM too often. We don't want to spam the users, just let them know they are unconnectable.<br/>Every week would be ok.<br/><br/>");

print("<a href='admincp.php?action=viewlogsunconnectable&clear=all' onclick='return confirm(\"Are you sure you want to clear ALL logs?\")'>Clear All Logs</a> | ");
print("<a href='admincp.php?action=viewlogsunconnectable&clear=old' onclick='return confirm(\"Delete logs older than 30 days?\")'>Prune Old Logs</a><br><br>");

// Group logs by admin
$admins = [];
while ($row = mysqli_fetch_assoc($getlog)) {
$admins[$row['user']][] = $row['date'];
}

print("<table border=1 cellspacing=0 cellpadding=5>");
print("<tr><td class=colhead>Admin</td><td class=colhead>PM Sends</td></tr>");

foreach ($admins as $userid => $dates) {
$r2 = SQL_Query_exec("SELECT username FROM users WHERE id=$userid") or sqlerr();
$a2 = mysqli_fetch_assoc($r2);

print("<tr>");
print("<td><a href='account-details.php?id=$userid'>{$a2['username']}</a></td>");
print("<td>");
print("<select onchange='if(this.value) window.location=this.value'>");
print("<option value=''>Show PM sent…</option>");

foreach ($dates as $date) {
// Get users who received the PM on this date
$users_sent_res = SQL_Query_exec("
SELECT receiver
FROM messages
WHERE sender = 0
 AND msg LIKE '%firewalled or behind NAT%'
 AND added = '" . $date . "'
");
$usernames = [];
while ($u = mysqli_fetch_assoc($users_sent_res)) {
$r3 = SQL_Query_exec("SELECT username FROM users WHERE id={$u['receiver']}") or sqlerr();
$a3 = mysqli_fetch_assoc($r3);
$usernames[] = $a3['username'];
}

// Truncate long user lists
$total = count($usernames);
if ($total > 5) {
$display_users = implode(", ", array_slice($usernames, 0, 5)) . " …and " . ($total - 5) . " more";
} else {
$display_users = implode(", ", $usernames);
}

$elapsed = get_elapsed_time(sql_timestamp_to_unix_timestamp($date));
print("<option value='#'>{$date} ({$elapsed} ago) – Users: {$display_users}</option>");
}

print("</select>");
print("</td>");
print("</tr>");
}

print("</table>");

end_frame();
navmenu();
stdfoot();
}
// end unconnectable peers section


then create a link for it up near the top in the nav section
   <td align="center"><a href="admincp.php?action=viewlogsunconnectable"><img src="images/admin/connectable.png" border="0" width="118" height="80" alt="" /><br /><?php echo T_("NOT_CONNECT"); ?><br /></a></td>


No extra files needed like the old one. All contained in the admincp.php
External UDP/HTTPS scrape — 2026-02-03 19:57:23 in v3 Support
Here are your functions file and torrents-details file and I inserted the code. Backup your files first as I have no way to test this, you will have to on your setup. The code in your files is extremely outdated so I cant make any promises. The code I posted above is for TTv3, but it may work, you will just have to try it
updated. Here ya go.
<?php
require_once("backend/functions.php");

dbconn();
loggedinonly();

$db = $GLOBALS["DBconnector"];

function catalog_h($v)
{
   return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function catalog_bind_stmt($stmt, $types, &$params)
{
   if (!$types || !$params) {
       return;
   }

   $bind = [];
   $bind[] = $types;

   foreach ($params as $k => $v) {
       $bind[] = &$params[$k];
   }

   call_user_func_array([$stmt, 'bind_param'], $bind);
}

function catalog_build_filter($search, $letter)
{
   $search = trim((string)$search);
   $letter = strtolower(trim((string)$letter));

   $where = "t.visible != 'no'";
   $params = [];
   $types = '';
   $q = '';

   if ($search !== '') {
       $where .= " AND t.name LIKE ?";
       $params[] = $search . '%';
       $types .= 's';
       $q = "search=" . urlencode($search);
   } else {
       if (strlen($letter) !== 1 || strpos("0123456789abcdefghijklmnopqrstuvwxyz", $letter) === false) {
           $letter = 'a';
       }

       $where .= " AND t.name LIKE ?";
       $params[] = $letter . '%';
       $types .= 's';
       $q = "letter=" . urlencode($letter);
   }

   return [$where, $params, $types, $q, $letter, $search];
}

function catalog_render_filters($active)
{
   echo "<div class='catalog-filter-groups'>";

   echo "<div class='catalog-filter-row catalog-filter-row-letters'>";
   foreach (range('a', 'z') as $c) {
       $u = strtoupper($c);

       if ($c === $active) {
           echo "<span class='catalog-filter-item active'>{$u}</span>";
       } else {
           echo "<a class='catalog-filter-item' href='?letter=" . catalog_h($c) . "'>{$u}</a>";
       }
   }
   echo "</div>";

   echo "<div class='catalog-filter-row catalog-filter-row-numbers'>";
   foreach (range(0, 9) as $n) {
       $n = (string)$n;

       if ($n === $active) {
           echo "<span class='catalog-filter-item active'>{$n}</span>";
       } else {
           echo "<a class='catalog-filter-item' href='?letter=" . catalog_h($n) . "'>{$n}</a>";
       }
   }
   echo "</div>";

   echo "</div>";
}

function catalog_pager($page, $pages, $q)
{
   if ($pages <= 1) {
       return;
   }

   echo "<div class='catalog-pager'>";

   if ($page > 1) {
       echo "<a class='catalog-page-link' href='?" . catalog_h($q) . "&page=" . ($page - 1) . "'><<</a>";
   }

   for ($i = max(1, $page - 3); $i <= min($pages, $page + 3); $i++) {
       if ($i == $page) {
           echo "<span class='catalog-page-link active'>{$i}</span>";
       } else {
           echo "<a class='catalog-page-link' href='?" . catalog_h($q) . "&page={$i}'>{$i}</a>";
       }
   }

   if ($page < $pages) {
       echo "<a class='catalog-page-link' href='?" . catalog_h($q) . "&page=" . ($page + 1) . "'>>></a>";
   }

   echo "</div>";
}

function catalog_img_html($row, $cfg)
{
   if (empty($row['image1'])) {
       return "<img src='images/no_poster.png' width='150' height='220' alt='No image'>";
   }

   $u = $cfg['SITEURL'] . "/uploads/images/" . rawurlencode($row['image1']);

   return "<img src='" . catalog_h($u) . "' width='150' height='220' alt='" . catalog_h($row['name']) . "'>";
}

$search = $_GET['search'] ?? '';
$letter = $_GET['letter'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$perpage = 4;

list($where, $params, $types, $q, $active, $search) = catalog_build_filter($search, $letter);

if ($CURUSER['view_xxx'] != 'yes') {
   $where .= " AND t.category NOT IN (40,7)";
}

stdhead("Catalog");
begin_frame("Catalog");

echo '<style>
.catalog-filter-groups{margin:10px 0 16px 0}
.catalog-filter-row{display:flex;flex-wrap:wrap;justify-content:center;gap:6px}
.catalog-filter-row-letters{margin-bottom:8px}
.catalog-filter-row-numbers{margin-top:2px}
.catalog-filter-item{padding:6px 10px;border:1px solid #444;background:#1f1f1f;color:#ccc;border-radius:6px;text-decoration:none;font-weight:bold}
.catalog-filter-item.active{background:#1fa34a;color:#fff;box-shadow:0 0 6px rgba(0,255,120,.5)}
.catalog-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;margin:15px}
.catalog-card{background:#1b1b1b;border:1px solid #333;border-radius:10px;overflow:hidden}
.catalog-card-header{padding:10px;background:#222;font-weight:bold}
.catalog-card-body{display:flex;gap:12px;padding:12px}
.catalog-desc{max-height:150px;overflow:auto;background:#111;padding:8px;border:1px solid #333;border-radius:6px;margin-top:8px}
.catalog-stat{padding:6px 10px;background:#111;border-radius:5px;border:1px solid #333;font-weight:bold}
.catalog-actions{margin-top:10px;display:flex;gap:8px;flex-wrap:wrap}
.catalog-btn{padding:6px 10px;background:#333;border-radius:6px;text-decoration:none;color:#fff;display:inline-block}
.catalog-btn.primary{background:#1e6bd6}
.catalog-pager{display:flex;justify-content:center;gap:6px;margin:10px;flex-wrap:wrap}
.catalog-page-link{padding:6px 10px;background:#1f1f1f;border-radius:6px;text-decoration:none;color:#ccc}
.catalog-page-link.active{background:#1e6bd6;color:#fff}
@media (max-width:700px){
.catalog-card-body{flex-direction:column}
}
</style>';

echo "<center>
<form method='get'>
<input type='text' name='search' value='" . catalog_h($search) . "' placeholder='Search'>
<input type='submit' value='Search'>
</form>
</center>";

catalog_render_filters($active);

$stmt = $db->prepare("SELECT COUNT(*) FROM torrents t WHERE $where");
if (!$stmt) {
   die("Prepare failed: " . catalog_h($db->error));
}

$countParams = $params;
catalog_bind_stmt($stmt, $types, $countParams);
$stmt->execute();
$stmt->bind_result($total);
$stmt->fetch();
$stmt->close();

$total = (int)$total;
$pages = max(1, (int)ceil($total / $perpage));
$page = min($page, $pages);
$offset = ($page - 1) * $perpage;

catalog_pager($page, $pages, $q);

$sql = "SELECT
t.id,
t.name,
t.size,
t.image1,
t.descr,
t.filename,
t.seeders,
t.leechers,
t.times_completed,
c.name AS cat_name,
c.parent_cat
FROM torrents t
LEFT JOIN categories c ON t.category = c.id
WHERE $where
ORDER BY t.name ASC
LIMIT ?, ?";

$mainParams = $params;
$mainParams[] = $offset;
$mainParams[] = $perpage;
$mainTypes = $types . "ii";

$stmt = $db->prepare($sql);
if (!$stmt) {
   die("Prepare failed: " . catalog_h($db->error));
}

catalog_bind_stmt($stmt, $mainTypes, $mainParams);
$stmt->execute();
$res = $stmt->get_result();

echo "<div class='catalog-grid'>";

while ($row = $res->fetch_assoc()) {
   $id = (int)$row['id'];
   $name = catalog_h($row['name']);
   $size = mksize((int)$row['size']);
   $downloads = (int)$row['times_completed'];
   $seeders = (int)$row['seeders'];
   $leechers = (int)$row['leechers'];

   echo "<div class='catalog-card'>";
   echo "<div class='catalog-card-header'>{$name}</div>";

   echo "<div class='catalog-card-body'>";
   echo "<div>" . catalog_img_html($row, $site_config) . "</div>";
   echo "<div style='flex:1'>";

   echo "<div><b>Category:</b> " . catalog_h($row['parent_cat']) . " > " . catalog_h($row['cat_name']) . "</div>";
   echo "<div><b>Size:</b> {$size}</div>";
   echo "<div><b>Downloads:</b> {$downloads}</div>";

   echo "<div class='catalog-desc'>" . format_comment($row['descr']) . "</div>";

   echo "<div style='display:flex;gap:8px;margin-top:8px;flex-wrap:wrap'>";
   echo "<div class='catalog-stat' style='color:#4cff88'>▲ {$seeders}</div>";
   echo "<div class='catalog-stat' style='color:#ff5c5c'>▼ {$leechers}</div>";
   echo "</div>";

   echo "<div class='catalog-actions'>";
   echo "<a class='catalog-btn primary' href='download.php?id={$id}&name=" . rawurlencode($row['filename']) . "'>Download</a>";
   echo "<a class='catalog-btn' href='torrents-details.php?id={$id}'>Details</a>";
   echo "</div>";

   echo "</div>";
   echo "</div>";
   echo "</div>";
}

echo "</div>";

$stmt->close();

catalog_pager($page, $pages, $q);

end_frame();
stdfoot();
?>
Error syntax — 2026-01-26 10:36:34 in v3 Support
your files look fine. just need to find out why that sql query is wrong
Error syntax — 2026-01-23 18:12:08 in v3 Support
last_action is the problem here. Also, TMDB shouldnt be a date or timestamp, so your query is wrong. You have malformed data being sent. Its putting the data for last action in the tmdb spot. Can you post your torrent upload page code? Does your external scrape in that same file look like this?
//EXTERNAL SCRAPE
if ($external == 'yes' && $site_config['UPLOADSCRAPE']) {
   $tracker = str_replace("/announce", "/scrape", $announce);    
   $stats = torrent_scrape_url($tracker, $infohash);
   
   // Sanitize and ensure non-negative values
   $seeders = max(0, (int)strip_tags($stats['seeds']));       // Force to 0 if negative
   $leechers = max(0, (int)strip_tags($stats['peers']));      // Force to 0 if negative
   $downloaded = max(0, (int)strip_tags($stats['downloaded'])); // Force to 0 if negative

   SQL_Query_exec("UPDATE torrents SET leechers='$leechers', seeders='$seeders', times_completed='$downloaded', last_action='".get_date_time()."', visible='yes' WHERE id='$id'");
}
//END SCRAPE
also have a look at this https://torrenttrader.uk/post/10731/last/#last
Error syntax — 2026-01-22 21:27:26 in v3 Support
seems like last_action is not getting any data, and the tmdb seems to be getting the data for last_action. I dont think tmdb should be a date right? I dont use tmdb, so Im just looking at your error. Possibly this
".sqlesc($tmdb)."
should be this
".sqlesc($_POST['tmdb'])."
Not sure, just a guess
External UDP/HTTPS scrape — 2026-01-21 07:30:09 in v3 Support
ok,  This seems to work. Should scrape udp and https while keeping all the same files with no external shit or extra files, cuz I dont like that. Test it and lets see. THIS IS COPY/PASTE AND APPLIES TO TTv3 unless you know what you are doing. This will work fine in whatever you have, but I cant tell you where to put it if you have custom code. in backend/functions, just replace the entire torrent_scrape_url
//////////// Begin revised torrent_scrape_url function ////////////

function torrent_scrape_url(string $scrape, string $hash): array
{
   $ret = [
       'seeds'      => 0,
       'peers'      => 0,
       'downloaded' => 0,
   ];

   // info_hash must be 40 hex chars
   if (!preg_match('/^[a-f0-9]{40}$/i', $hash)) {
       return $ret;
   }

   // Parse the input URL as-is (do NOT force http:// yet)
   $url = parse_url($scrape);

   // If no scheme and looks like host-only → default to http
   if (empty($url['scheme']) && !empty($url['host'])) {
       $scrape = 'http://' . $scrape;
       $url = parse_url($scrape); // re-parse
   }

   if (empty($url['host'])) {
       return $ret;
   }

   $scheme = strtolower($url['scheme'] ?? 'http');

   // ────────────────────────────────────────────────
   // UDP branch – handle BEFORE http/https
   // ────────────────────────────────────────────────
   if ($scheme === 'udp') {
       if (empty($url['port'])) {
           $url['port'] = 6969; // common default for udp trackers
       }

       $socket = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
       if (!$socket) {
           return $ret;
       }

       socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 4, 'usec' => 0]);
       socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => 4, 'usec' => 0]);

       // Connect request
       $conn_req = pack('N*', 0x417, 0x27101980, 0, mt_rand(1, 0x7fffffff));
       @socket_sendto($socket, $conn_req, 16, 0, $url['host'], $url['port']);

       $buf = '';
       $len = @socket_recvfrom($socket, $buf, 16, 0, $dummy1, $dummy2);
       if ($len !== 16) {
           @socket_close($socket);
           return $ret;
       }

       $conn_resp = unpack('Naction/Ntrans_id/Jconnection_id', $buf);
       if ($conn_resp['action'] !== 0) {
           @socket_close($socket);
           return $ret;
       }
       $connection_id = $conn_resp['connection_id'];

       // Scrape request
       $trans_id = mt_rand(1, 0x7fffffff);
       $scrape_req = pack('JNN', $connection_id, 2, $trans_id);
       $scrape_req .= pack('H*', $hash);

       @socket_sendto($socket, $scrape_req, strlen($scrape_req), 0, $url['host'], $url['port']);

       $buf = '';
       $len = @socket_recvfrom($socket, $buf, 8 + 12, 0, $dummy1, $dummy2);
       @socket_close($socket);

       if ($len < 20) {
           return $ret;
       }

       $scrape_resp = unpack('Naction/Ntrans_id', substr($buf, 0, 8));
       if ($scrape_resp['action'] !== 2 || $scrape_resp['trans_id'] !== $trans_id) {
           return $ret;
       }

       $stats = unpack('Ncomplete/Ndownloaded/Nincomplete', substr($buf, 8, 12));

       $ret['seeds']      = max(0, (int)($stats['complete']   ?? 0));
       $ret['peers']      = max(0, (int)($stats['incomplete'] ?? 0));
       $ret['downloaded'] = max(0, (int)($stats['downloaded'] ?? 0));

       return $ret;
   }

   // ────────────────────────────────────────────────
   // HTTP / HTTPS branch
   // ────────────────────────────────────────────────
   if (!in_array($scheme, ['http', 'https'], true)) {
       return $ret;
   }

   // Build clean scrape URL
   $base = $scheme . '://' . $url['host'];
   if (!empty($url['port']) && $url['port'] != ($scheme === 'https' ? 443 : 80)) {
       $base .= ':' . $url['port'];
   }
   $base .= $url['path'] ?? '/announce';

   $query_params = ['info_hash' => pack('H*', $hash)];
   $scrape_url = $base . '?' . http_build_query($query_params);

   // Fetch response
   if (function_exists('curl_init')) {
       $ch = curl_init($scrape_url);
       curl_setopt_array($ch, [
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_CONNECTTIMEOUT => 5,
           CURLOPT_TIMEOUT        => 10,
           CURLOPT_USERAGENT      => 'FastTracker Scraper/1.1',
           CURLOPT_SSL_VERIFYPEER => ($scheme === 'https'),
       ]);
       $response = curl_exec($ch);
       curl_close($ch);
   } else {
       ini_set('default_socket_timeout', 10);
       $response = @file_get_contents($scrape_url);
   }

   if (!$response) {
       return $ret;
   }

   // Decode tracker response
   $stats = BDecode($response);
   if (!is_array($stats) || empty($stats['files'])) {
       return $ret;
   }

   $binhash = pack('H*', $hash);
   if (!isset($stats['files'][$binhash])) {
       return $ret;
   }

   $file = $stats['files'][$binhash];
   $ret['seeds']      = max(0, (int)($file['complete']   ?? 0));
   $ret['peers']      = max(0, (int)($file['incomplete'] ?? 0));
   $ret['downloaded'] = max(0, (int)($file['downloaded'] ?? 0));

   return $ret;
}
/////////////// End revised torrent_scrape_url function ////////////

and in torrents-details. Replace from //download box to //end download box
 //download box
if ($row["external"] == 'yes') {
   if ($scrape == '1') {
       print("<td valign='top' align='right'>");

       // Buffering control
       @ini_set('output_buffering', 'Off');
       @ini_set('zlib.output_compression', 'Off');
       @ini_set('implicit_flush', true);
       ob_implicit_flush(true);
       while (ob_get_level() > 0) { ob_end_flush(); }
       flush();

       echo "<b id=\"scrapeStatus\">" . T_("LIVE_STATS") . ": Scraping trackers...</b><br />\n";

       // Progress log
       echo "<div id=\"progressLog\" style=\"max-height:300px; overflow-y:auto; border:1px solid #ccc; padding:10px; background:#f8f8f8; font-family:monospace; margin:12px 0; line-height:1.4;\">\n";

       flush();

       $seeders1    = 0;
       $leechers1   = 0;
       $downloaded1 = 0;
       $has_stats   = false;

       $count_res = SQL_Query_exec("SELECT COUNT(*) as total FROM announce WHERE torrent=$id");
       $count_row = mysqli_fetch_assoc($count_res);
       $total     = (int)$count_row['total'];
       $processed = 0;

       $tres = SQL_Query_exec("SELECT url FROM announce WHERE torrent=$id");
       while ($trow = mysqli_fetch_array($tres)) {
           $processed++;
           $ann = $trow["url"];

           echo "[$processed/$total] $ann ... ";
           flush();

           $tracker = explode("/", $ann);
           $path    = array_pop($tracker);
           $oldpath = $path;
           $path    = preg_replace("/^announce/", "scrape", $path);
           $scrape_url = implode("/", $tracker) . "/" . $path;

           if ($oldpath == $path) {
               echo "<span style=\"color:orange;\">skipped (no scrape support)</span><br />\n";
               flush();
               continue;
           }

           $stats = torrent_scrape_url($scrape_url, $row["info_hash"]);

           if ($stats['seeds'] > 0 || $stats['peers'] > 0 || $stats['downloaded'] > 0) {
               $seeders1    += $stats['seeds'];
               $leechers1   += $stats['peers'];
               $downloaded1 += $stats['downloaded'];
               $has_stats   = true;

               echo "<span style=\"color:green;\">OK</span> ";
               echo "(S: " . number_format($stats['seeds']) . " | L: " . number_format($stats['peers']) . " | C: " . number_format($stats['downloaded']) . ")<br />\n";

               $stmt = $GLOBALS["DBconnector"]->prepare(
                   "UPDATE announce SET online='yes', seeders=?, leechers=?, times_completed=? WHERE url=? AND torrent=?"
               );
               $stmt->bind_param("iiisi", $stats['seeds'], $stats['peers'], $stats['downloaded'], $ann, $id);
               $stmt->execute();
           } else {
               echo "<span style=\"color:red;\">no data / timeout</span><br />\n";

               $stmt = $GLOBALS["DBconnector"]->prepare(
                   "UPDATE announce SET online='no' WHERE url=? AND torrent=?"
               );
               $stmt->bind_param("si", $ann, $id);
               $stmt->execute();
           }

           flush();
           usleep(120000);  // slight delay to reduce server load
       }

       echo "</div>\n";

       echo "
       <script type=\"text/javascript\">
           document.getElementById('scrapeStatus').innerHTML = '" . T_("LIVE_STATS") . ": Completed';
           document.getElementById('scrapeStatus').style.color = '#006600';
       </script>\n";

       // Final stats
       if ($has_stats) {
           echo "<br /><b>Final aggregated stats:</b><br />\n";
           echo "Seeders: " . number_format($seeders1) . "<br />\n";
           echo "Leechers: " . number_format($leechers1) . "<br />\n";
           echo T_("COMPLETED") . ": " . number_format($downloaded1) . "<br />\n";

           $stmt = $GLOBALS["DBconnector"]->prepare(
               "UPDATE torrents SET leechers=?, seeders=?, times_completed=?, last_action=?, visible='yes' WHERE id=?"
           );
           $stmt->bind_param("iiisi", $leechers1, $seeders1, $downloaded1, $last_action = get_date_time(), $row['id']);
           $stmt->execute();
       } else {
           echo "<br /><font color='#ff0000'>All trackers failed or timed out<br />Please retry later</font><br />\n";
       }

       echo "<form action='torrents-details.php?id=$id&scrape=1' method='post' style=\"margin-top:15px;\">\n";
       echo "<input type=\"submit\" name=\"submit\" value=\"Update Stats Again\" />\n";
       echo "</form></td>\n";

       // auto-scroll script
       echo "
       <script type=\"text/javascript\">
       (function() {
           const log = document.getElementById('progressLog');
           if (!log) return;

           // Scroll to bottom function
           function scrollToBottom() {
               log.scrollTop = log.scrollHeight;
           }

           // Initial scroll (in case content already there)
           scrollToBottom();

           // MutationObserver – detects added lines and scrolls
           const observer = new MutationObserver(function(mutations) {
               scrollToBottom();
           });

           observer.observe(log, {
               childList: true,    // watch for added/removed nodes
               subtree: true,      // watch descendants too
               characterData: true // catch text changes
           });

           // Fallback polling (if MutationObserver not supported – very old browsers)
           const interval = setInterval(scrollToBottom, 800);

           // Stop polling once scraping is done (after page fully loads)
           window.addEventListener('load', function() {
               clearInterval(interval);
               scrollToBottom();
           });
       })();
       </script>\n";
   } else {
       if ($CURUSER["class"] > 4) {
           print("<td valign='top' align='right'>");
           print("<form action='torrents-details.php?id=$id&scrape=1' method='post'>");
           print("<input type=\"submit\" name=\"submit\" value=\"Update Stats\" />");
           print("</form></td>");
       }
   }
}

I attached a test torrent for you to try. I edited it and removed alot of the dead trackers, but I left enough for you to see how this works. The original had 85 trackers and most were dead. I cut it to 19, some are live and some are not which makes a good test
External UDP/HTTPS scrape — 2026-01-20 10:32:35 in v3 Support
see post below
External UDP/HTTPS scrape — 2026-01-20 01:08:19 in v3 Support
post removed. bad code. See post below
block — 2026-01-19 04:45:25 in v3 Support
if (!$CURUSER) {
   $site_config["LEFTNAV"]   = false;
   $site_config["MIDDLENAV"] = false;
   $site_config["RIGHTNAV"]  = false;
}
WebP image converter — 2026-01-17 14:51:31 in General Chat
This is fun. This works really well, so if you just need to convert images to webp, this works perfectly. I tested it a few times and had no issues. Backup everything as always. If you want this to update images, IT NEEDS TO BE IN THE IMAGES FOLDER THAT YOU WANT TO ALTER OR EDIT. for example mysite.burp/images/webpconverter.php. Make sure this file is in the folder you want the images converted, then run it, and all images are now webp....yaaayyyy
<?php

// Convert images in the current folder to WebP format
// WARNING: This will DELETE the original images after conversion. MAKE A BACKUP FIRST!
// Delete this file after use. Do not leave it on a public server.
// This uses the gd library, which must be installed with WebP support.
while (ob_get_level()) {
   ob_end_flush();
}
ob_implicit_flush(true);
set_time_limit(0);

$quality = 85;
$allowed = ['jpg', 'jpeg', 'png', 'bmp', 'gif'];

$confirmed = isset($_POST['confirm']) && $_POST['confirm'] === 'yes';

function is_animated_gif(string $file): bool
{
   if (!($fh = fopen($file, 'rb'))) {
       return false;
   }
   $frames = 0;
   while (!feof($fh) && $frames < 2) {
       $chunk = fread($fh, 1024);
       $frames += preg_match_all('#\x00\x21\xF9\x04#', $chunk);
   }
   fclose($fh);
   return $frames > 1;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebP Folder Converter</title>
<style>
body {
   font-family: system-ui, sans-serif;
   background: #111;
   color: #ddd;
   padding: 20px;
}
button {
   padding: 10px 16px;
   font-size: 16px;
   background: #c0392b;
   border: none;
   color: #fff;
   cursor: pointer;
}
button:hover {
   background: #e74c3c;
}
pre {
   background: #000;
   padding: 10px;
   overflow: auto;
   max-height: 60vh;
}
.warning { color: #f39c12; }
.success { color: #2ecc71; }

.spinner {
   display: inline-block;
   width: 12px;
   height: 12px;
   border: 2px solid #444;
   border-top-color: #2ecc71;
   border-radius: 50%;
   animation: spin 0.8s linear infinite;
   margin-right: 8px;
}

@keyframes spin {
   to { transform: rotate(360deg); }
}
</style>
</head>
<body>

<h2>WebP Converter (Current Folder)</h2>

<p class="warning">
⚠ This will permanently delete original images after conversion.<br>
Animated GIFs will lose animation.
</p>

<?php if (!$confirmed): ?>

<form method="post">
   <p>Folder: <strong><?= htmlspecialchars(__DIR__) ?></strong></p>
   <button type="submit" name="confirm" value="yes">
       Convert images to WebP
   </button>
</form>

<?php else: ?>

<p id="workingMsg"><span class="spinner"></span><strong>Working… do not close this page</strong></p>

<pre>
<?php
$files = scandir(__DIR__);
$count = 0;

foreach ($files as $file) {
   if (!is_file($file)) {
       continue;
   }

   $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
   if (!in_array($ext, $allowed, true)) {
       continue;
   }

   $count++;
   echo "Processing: $file\n";
   @ob_flush(); @flush();

   $webp = pathinfo($file, PATHINFO_FILENAME) . '.webp';

   if (file_exists($webp)) {
       echo "[SKIP] $file (webp exists)\n\n";
       @ob_flush(); @flush();
       continue;
   }

   if ($ext === 'gif' && is_animated_gif($file)) {
       echo "[SKIP] $file (animated GIF)\n\n";
       @ob_flush(); @flush();
       continue;
   }

   switch ($ext) {
       case 'jpg':
       case 'jpeg':
           $img = @imagecreatefromjpeg($file);
           break;
       case 'png':
           $img = @imagecreatefrompng($file);
           if ($img) {
               imagepalettetotruecolor($img);
               imagealphablending($img, true);
               imagesavealpha($img, true);
           }
           break;
       case 'bmp':
           $img = @imagecreatefrombmp($file);
           break;
       case 'gif':
           $img = @imagecreatefromgif($file);
           if ($img) {
               imagepalettetotruecolor($img);
           }
           break;
       default:
           $img = false;
   }

   if (!$img) {
       echo "[FAIL] $file (read error)\n\n";
       @ob_flush(); @flush();
       continue;
   }

   if (imagewebp($img, $webp, $quality)) {
       unlink($file);
       echo "[OK]   $file → $webp\n\n";
   } else {
       echo "[FAIL] $file (convert error)\n\n";
   }

   imagedestroy($img);
   @ob_flush(); @flush();
}

echo "Done. Files processed: $count\n";
?>
</pre>
<script>
document.addEventListener("DOMContentLoaded", function() {
   var working = document.getElementById('workingMsg');
   if (working) {
       working.innerHTML = '<strong>✅ CONVERSION COMPLETE. YOU CAN CLOSE THIS PAGE NOW</strong>';
   }
});
</script>

<p class="success">✅ Conversion complete</p>

<?php endif; ?>

</body>
</html>
Upload an avatar — 2026-01-07 19:51:22 in v3 Mods Completed
This seems to work for converting existing avatars to WebP. Just save it as avatarfix.php in your root and execute it. This will nullify any existing GIF images and only save the first frame as WebP
<?php
require_once __DIR__ . '/backend/functions.php';

dbconn();
loggedinonly();

if ($CURUSER['class'] < 8) {
   show_error_msg("Access denied", "Admins only.", 1);
}

$avatarDir = __DIR__ . '/' . trim($site_config['avatar_dir'], '/');
$avatarUrl = rtrim($site_config['SITEURL'], '/') . '/' . trim($site_config['avatar_dir'], '/');

$maxWidth  = 80;
$maxHeight = 80;
$quality   = (int)($site_config['avatar_webp_quality'] ?? 80);

$batchSize = 10; // avatars per load time

if (!is_dir($avatarDir) || !is_writable($avatarDir)) {
   show_error_msg("Server error", "Avatar directory not writable", 1);
}

$res = SQL_Query_exec("
   SELECT id, avatar
   FROM users
   WHERE avatar != ''
     AND avatar NOT LIKE '%.webp'
   LIMIT {$batchSize}
");

stdhead("Avatar Conversion");
begin_frame("Avatar Conversion");

if (mysqli_num_rows($res) === 0) {
   print("<p class='text-center'><b>All avatars have been converted</b></p>");
   print("<p class='text-center'>You can now safely delete this file.</p>");
   end_frame();
   stdfoot();
   exit;
}

print("<ul>");

while ($row = mysqli_fetch_assoc($res)) {

   $userId = (int)$row['id'];
   $oldUrl = $row['avatar'];
   $oldFile = basename($oldUrl);
   $oldPath = $avatarDir . '/' . $oldFile;

   if (!is_file($oldPath)) {
       print("<li>User {$userId}: file missing</li>");
       continue;
   }

   $info = getimagesize($oldPath);
   if ($info === false) {
       print("<li>User {$userId}: invalid image</li>");
       continue;
   }

switch ($info[2]) {
   case IMAGETYPE_JPEG:
       $src = imagecreatefromjpeg($oldPath);
       break;

   case IMAGETYPE_PNG:
       $src = imagecreatefrompng($oldPath);
       break;

   case IMAGETYPE_GIF:
       $src = imagecreatefromgif($oldPath);
       break;

   case IMAGETYPE_WEBP:
       print("<li>User {$userId}: already WebP</li>");
       continue 2;

   default:
       print("<li>User {$userId}: unsupported type</li>");
       continue 2;
}


   if (!$src) {
       print("<li>User {$userId}: failed to load image</li>");
       continue;
   }
   $srcW = imagesx($src);
   $srcH = imagesy($src);

   $scale = min($maxWidth / $srcW, $maxHeight / $srcH, 1);
   $newW  = (int)floor($srcW * $scale);
   $newH  = (int)floor($srcH * $scale);

   $dst = imagecreatetruecolor($newW, $newH);
   imagealphablending($dst, false);
   imagesavealpha($dst, true);

   imagecopyresampled(
       $dst, $src,
       0, 0, 0, 0,
       $newW, $newH,
       $srcW, $srcH
   );

   $newName = $userId . '.webp';
   $newPath = $avatarDir . '/' . $newName;

   if (!imagewebp($dst, $newPath, $quality)) {
       print("<li>User {$userId}: failed to save WebP</li>");
       imagedestroy($src);
       imagedestroy($dst);
       continue;
   }

   imagedestroy($src);
   imagedestroy($dst);

   SQL_Query_exec(
       "UPDATE users
        SET avatar = " . sqlesc($avatarUrl . '/' . $newName) . "
        WHERE id = {$userId}"
   );

   if ($oldFile !== $newName) {
       @unlink($oldPath);
   }

   print("<li>User {$userId}: converted</li>");
}

print("</ul>");

print("
   <p class='text-center'>
       <a href='avatarfix.php'><b>Continue next batch</b></a>
   </p>
");

end_frame();
stdfoot();
Upload an avatar — 2026-01-03 23:59:48 in v3 Mods Completed
You may need this in your login_block also
    function getUserAvatar($userAvatar, $siteUrl) {
       $avatar = htmlspecialchars($userAvatar);
       return $avatar ?: "$siteUrl/avatars/default_avatar.webp'";
   }
   $avatar = getUserAvatar($CURUSER["avatar"], $site_config["SITEURL"]);
Upload an avatar — 2026-01-03 23:31:16 in v3 Mods Completed
This is a continuation of this https://torrenttrader.uk/post/3317  You can upload an avatar to your sever directly rather than using a weblink to the image, which Is removed from this code. Images are converted to WebP using the GD library that your server already has, which is better than PNG or JPG. This code will not allow GIF, because thats just a bad idea anyway.
In account.php under edit_settings. Put this wherever you like.
/// AVATAR UPLOAD ///
if ($site_config['AVATARUPLOAD']) {

   $default_avatar = $site_config['SITEURL'] . '/avatars/default_avatar.webp';

   $avatar = $CURUSER['avatar'];
   if (empty($avatar)) {
       $avatar = $default_avatar;
   }

   $show_remove = ($avatar !== $default_avatar);

   $avatar = htmlspecialchars($avatar, ENT_QUOTES, 'UTF-8');

   $max_avatar_size = (int)$site_config['avatar_max_filesize'];

   if ($max_avatar_size >= GB) {
       $max_avatar_size_text = round($max_avatar_size / GB, 2) . ' GB';
   } elseif ($max_avatar_size >= MB) {
       $max_avatar_size_text = round($max_avatar_size / MB, 2) . ' MB';
   } else {
       $max_avatar_size_text = round($max_avatar_size / KB, 2) . ' KB';
   }

   print("
       <tr>
           <td align='right' class='table_col1'><b>" . T_('AVATAR') . ":</b></td>
           <td align='left' class='table_col1'>
               <table>
                   <tr>
                       <td>
                           <img src='{$avatar}' width='40' height='40' alt='Avatar'>
                       </td>
                       <td>
                           <a href='upavatar.php?action=upload'><b>" . T_('UP_AVATAR') . "</b></a>"
                           . ($show_remove
                               ? " &nbsp;|&nbsp; <a href='upavatar.php?action=remove'><b>Remove Avatar</b></a>"
                               : ""
                           ) . "
                           <br>
                           <small>
                               Images are converted to WebP · Max size: {$max_avatar_size_text}
                           </small>
                       </td>
                   </tr>
               </table>
           </td>
       </tr>
   ");
}
/// END UPLOAD AVATAR ///

Then create a file called upavatar.php and put it in the root folder of your site
<?php
require_once "backend/functions.php";

dbconn();
loggedinonly();

$action = $_GET['action'] ?? '';

if (!$site_config['AVATARUPLOAD']) {
   stdhead("Error");
   write_log("<b>DIRECT FILE ACCESS</b> - User <b>{$CURUSER['username']}</b> tried to upload avatar while disabled");
   show_error_msg("Error", "Avatar uploading is disabled by the site admin!", 1);
   stdfoot();
   exit;
}

$maxWidth  = 80;
$maxHeight = 80;
$maxSize   = (int)$site_config['avatar_max_filesize'];

$avatarDir = __DIR__ . '/' . trim($site_config['avatar_dir'], '/');
$avatarUrl = rtrim($site_config['SITEURL'], '/') . '/' . trim($site_config['avatar_dir'], '/');

if (!extension_loaded('gd')) {
   show_error_msg("Server error", "PHP GD extension is not installed", 1);
}

$gdInfo = gd_info();
if (empty($gdInfo['WebP Support'])) {
   show_error_msg("Server error", "GD WebP support is required for avatars", 1);
}


if ($action === 'post') {

   if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
       autolink ("upavatar.php?action=upload", "<b><font color='#ff0000'>No file selected...</font></b>");
   }

   if ($_FILES['avatar']['size'] > $maxSize) {
       show_error_msg(
           "Invalid file size",
           "Image must be less than " . mksize($maxSize),
           1
       );
   }

   if (!is_dir($avatarDir) || !is_writable($avatarDir)) {
       show_error_msg("Server error", "Avatar directory is not writable", 1);
   }

   $imageInfo = getimagesize($_FILES['avatar']['tmp_name']);
   if ($imageInfo === false) {
       write_log("<b>DIRECT FILE ACCESS</b> - User <b>{$CURUSER['username']}</b> uploaded non-image file");
       show_error_msg("Invalid file", "Uploaded file is not a valid image", 1);
   }

$allowedTypes = $site_config['avatar_allowed_types'] ?? [];

if (!isset($allowedTypes[$imageInfo[2]])) {
   autolink(
       "upavatar.php?action=upload",
       "<b><font color='#ff0000'>Invalid type. Allowed formats: " .
       implode(', ', $allowedTypes) .
       "</font></b>"
   );
}

   switch ($imageInfo[2]) {
       case IMAGETYPE_JPEG:
           $srcImage = imagecreatefromjpeg($_FILES['avatar']['tmp_name']);
           break;
       case IMAGETYPE_PNG:
           $srcImage = imagecreatefrompng($_FILES['avatar']['tmp_name']);
           break;
       case IMAGETYPE_WEBP:
           $srcImage = imagecreatefromwebp($_FILES['avatar']['tmp_name']);
           break;
       default:
           show_error_msg("Error", "Unsupported image format", 1);
   }

   if (!$srcImage) {
       show_error_msg("Error", "Failed to process image", 1);
   }

   $srcWidth  = $imageInfo[0];
   $srcHeight = $imageInfo[1];

   $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight, 1);
   $newW  = (int)floor($srcWidth * $scale);
   $newH  = (int)floor($srcHeight * $scale);

   $dstImage = imagecreatetruecolor($newW, $newH);

   /* Preserve transparency */
   imagealphablending($dstImage, false);
   imagesavealpha($dstImage, true);

   imagecopyresampled(
       $dstImage,
       $srcImage,
       0, 0, 0, 0,
       $newW, $newH,
       $srcWidth, $srcHeight
   );

   /* Save as WebP */
   $avatarName = (int)$CURUSER['id'] . '.webp';
   $avatarPath = $avatarDir . '/' . $avatarName;

   if (!imagewebp($dstImage, $avatarPath, 80)) {
       imagedestroy($srcImage);
       imagedestroy($dstImage);
       show_error_msg("Error", "Failed to save avatar image", 1);
   }

   imagedestroy($srcImage);
   imagedestroy($dstImage);

   $avatarFullUrl = $avatarUrl . '/' . $avatarName;
   SQL_Query_exec(
       "UPDATE users SET avatar = " . sqlesc($avatarFullUrl) . " WHERE id = " . (int)$CURUSER['id']
   );

   stdhead("Upload Avatar");
   begin_frame(T_("UP_AVATAR"));
   print("
       <br>
       <p class='text-center'>
           " . T_("AVATAR_OK") . "
           <a href='account.php?action=edit_settings&do=edit'><b>" . T_("ACCOUNT") . "</b></a>
       </p>
   ");
   end_frame();
   stdfoot();
   exit;
}


if ($action === 'upload') {

   stdhead("Upload Avatar");
   begin_frame(T_("UP_AVATAR"));

$allowedFormatsText = implode(', ', $site_config['avatar_allowed_types']);

print("
   <form method='post' action='?action=post' enctype='multipart/form-data'>
       <table class='table_col1' align='center' width='550' cellpadding='5'>
           <tr>
               <td class='table_col2' align='right'><b>" . T_("AVATAR_FILE") . ":</b></td>
               <td class='table_col1'><input type='file' name='avatar' size='60'></td>
           </tr>
           <tr>
               <td class='table_col2' align='right'><b>" . T_("DISCLAIMER") . ":</b></td>
               <td class='table_col1'>
                   " . T_("AVATAR_TXT") . " " . mksize($maxSize) . "<br>
                   <small>Allowed formats: {$allowedFormatsText}</small>
               </td>
           </tr>
           <tr>
               <td class='table_col1' colspan='2' align='center'>
                   <input type='submit' value='" . T_("UP_AVATAR") . "' class='btn'>
               </td>
           </tr>
       </table>
   </form>
");

   end_frame();
   stdfoot();
   exit;
}
if ($action === 'remove') {

   $default_avatar = rtrim($site_config['SITEURL'], '/') . '/avatars/default_avatar.webp';

   // Fetch current avatar
   $res = SQL_Query_exec(
       "SELECT avatar FROM users WHERE id = " . (int)$CURUSER['id']
   );

   $row = mysqli_fetch_assoc($res);
   $current_avatar = $row['avatar'] ?? '';

   // If empty or already default, nothing to remove
   if (empty($current_avatar) || $current_avatar === $default_avatar) {
       autolink(
           "account.php?action=edit_settings&do=edit",
           "<b>Nothing to remove.</b>"
       );
       exit;
   }

   // Convert URL to local filesystem path
   $avatar_dir = realpath(__DIR__ . '/' . trim($site_config['avatar_dir'], '/'));
   $avatar_path = parse_url($current_avatar, PHP_URL_PATH);

   if (!$avatar_path) {
       show_error_msg("Error", "Invalid avatar path", 1);
   }

   $full_path = realpath($_SERVER['DOCUMENT_ROOT'] . $avatar_path);

   // safety check to prevent directory traversal
   if (
       !$full_path ||
       !$avatar_dir ||
       strpos($full_path, $avatar_dir) !== 0 ||
       !is_file($full_path)
   ) {
       write_log("<b>SECURITY:</b> Avatar delete blocked for user {$CURUSER['username']}");
       show_error_msg("Error", "Invalid avatar file", 1);
   }

   // Delete avatar
   @unlink($full_path);

   // Reset avatar
   SQL_Query_exec(
       "UPDATE users SET avatar = " . sqlesc($default_avatar) . " WHERE id = " . (int)$CURUSER['id']
   );

   autolink(
       "account.php?action=edit_settings&do=edit",
       "<b>Avatar removed successfully.</b>"
   );
   exit;
}

stdhead("Error");
write_log("<b>DIRECT FILE ACCESS</b> - User <b>{$CURUSER['username']}</b> tried to access upavatar.php directly");
print("
<br>
<p class='text-center'><b>Direct access not allowed!</b></p>
<p class='text-center'>
   <a href='account.php?action=edit_settings&do=edit'><b>" . T_("ACCOUNT") . "</b></a>
</p>
<br>
");
stdfoot();

in backend/config add (you may have a few of these lines, so just replace it)
// Avatar Configuration (avatars are converted to WebP format in upavatar.php)
$site_config['AVATARUPLOAD'] = true;                          // Enable/disable avatar uploads
$site_config['avatar_dir'] = '/avatars';                      // Avatar storage directory (chmod 777)
$site_config['avatar_max_filesize'] = 3 * MB;                 // Maximum avatar file size
$site_config['avatar_webp_quality'] = 80;                     // WebP avatar quality (0-100)
$site_config['avatar_allowed_types'] = [                      // Permitted avatar image formats  
   IMAGETYPE_JPEG => 'JPG',                                  
   IMAGETYPE_PNG  => 'PNG',
   IMAGETYPE_WEBP => 'WebP',
];

You will also need this in your config. I use defines. Before the array starts $site_config = [];
// File Size Constants - DO NOT MODIFY
define('KB', 1024);
define('MB', 1024 * KB);
define('GB', 1024 * MB);

// Time Constants - DO NOT MODIFY
define('MINUTE', 60);
define('HOUR', 60 * MINUTE);
define('DAY', 24 * HOUR);
define('WEEK', 7 * DAY);

I attached a default_avatar.webp to replace the png that you probably have. Add this image to /avatars folder in the root as this code looks there for avatars, not the images folder
just change the database table to NULL. Easy
cool, thanks
password_hash is built into php. I wonder if using that would be better than creating a function
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 1
  • Members: 0
  • Guests online: 1
  • Comments: 3
  • Messages: 1,728