45 lines
2.0 KiB
PHP
45 lines
2.0 KiB
PHP
<?php
|
||
// 头像输出:?u=<user_id>。没上传过就现场画一个首字母色块 SVG,
|
||
// 好处是 HTML 里永远只出现 avatar.php?u=N,不暴露 uploads/ 下的真实文件名。
|
||
require_once __DIR__ . '/includes/auth.php';
|
||
|
||
$uid = (int)($_GET['u'] ?? 0);
|
||
$row = null;
|
||
if ($uid > 0) {
|
||
$stmt = $conn->prepare("SELECT user_id, nick_name, display_name, avatar FROM photo_users WHERE user_id = ? AND active = 1");
|
||
$stmt->bind_param("i", $uid);
|
||
$stmt->execute();
|
||
$row = $stmt->get_result()->fetch_assoc();
|
||
$stmt->close();
|
||
}
|
||
|
||
if ($row && !empty($row['avatar'])) {
|
||
$uploads_dir = realpath(__DIR__ . '/uploads');
|
||
$full = realpath(__DIR__ . '/' . $row['avatar']);
|
||
if ($full && $uploads_dir && strpos($full, $uploads_dir) === 0 && is_file($full)) {
|
||
header('Content-Type: image/png');
|
||
header('Cache-Control: public, max-age=86400');
|
||
header('Content-Length: ' . filesize($full));
|
||
readfile($full);
|
||
exit;
|
||
}
|
||
}
|
||
|
||
$name = $row && trim((string)$row['display_name']) !== '' ? $row['display_name'] : (string)($row['nick_name'] ?? '');
|
||
$ch = $name !== '' ? mb_substr($name, 0, 1, 'UTF-8') : '?';
|
||
$hues = [258, 330, 200, 160, 28, 12, 285, 190];
|
||
$hue = $hues[$uid % count($hues)];
|
||
$ch = htmlspecialchars($ch, ENT_QUOTES | ENT_XML1, 'UTF-8');
|
||
|
||
header('Content-Type: image/svg+xml');
|
||
header('Cache-Control: public, max-age=86400');
|
||
echo '<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">'
|
||
. '<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">'
|
||
. '<stop offset="0" stop-color="hsl(' . $hue . ',70%,58%)"/>'
|
||
. '<stop offset="1" stop-color="hsl(' . (($hue + 40) % 360) . ',70%,62%)"/>'
|
||
. '</linearGradient></defs>'
|
||
. '<rect width="128" height="128" fill="url(#g)"/>'
|
||
. '<text x="64" y="64" fill="#fff" font-size="58" font-weight="700" text-anchor="middle" '
|
||
. 'dominant-baseline="central" font-family="PingFang SC, Microsoft YaHei, sans-serif">' . $ch . '</text>'
|
||
. '</svg>';
|