初始化版本
This commit is contained in:
56
api/head.php
Normal file
56
api/head.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
// 头像代理:转发 https://api.iyuns.com/api/head 并返回 { url }
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
$endpoint = 'https://api.iyuns.com/api/head';
|
||||
|
||||
function fetch_json($url) {
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_CONNECTTIMEOUT => 8,
|
||||
CURLOPT_TIMEOUT => 12,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_USERAGENT => 'DiscussionProxy/1.0',
|
||||
]);
|
||||
$body = curl_exec($ch);
|
||||
$err = curl_error($ch);
|
||||
curl_close($ch);
|
||||
if ($err) { return null; }
|
||||
$json = json_decode($body, true);
|
||||
return is_array($json) ? $json : null;
|
||||
}
|
||||
|
||||
$resp = fetch_json($endpoint);
|
||||
$url = '';
|
||||
if ($resp && ($resp['code'] ?? 0) == 200) {
|
||||
$url = preg_replace('/[`\s]/', '', (string)($resp['data'] ?? ''));
|
||||
}
|
||||
if (!$url) {
|
||||
// 远程失败时,回退到本地随机头像(遍历 avatars 下所有日期目录)
|
||||
$root = __DIR__ . '/../avatars';
|
||||
$candidates = [];
|
||||
if (is_dir($root)) {
|
||||
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root));
|
||||
foreach ($rii as $file) {
|
||||
if ($file->isFile()) {
|
||||
$ext = strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
|
||||
if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
|
||||
$rel = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $file->getPathname()));
|
||||
$candidates[] = $rel;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!empty($candidates)) {
|
||||
shuffle($candidates);
|
||||
$url = $candidates[0];
|
||||
}
|
||||
}
|
||||
// 如果本地也没有,则后备一个 Unsplash 头像
|
||||
if (!$url) {
|
||||
$url = 'https://images.unsplash.com/photo-1547425260-76bcadfb4f9b?w=200&h=200&fit=crop';
|
||||
}
|
||||
}
|
||||
|
||||
echo json_encode(['url' => $url], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
Reference in New Issue
Block a user