短链服务是站长工具里很常用的功能。这里给出一个 PHP + SQLite 的单文件实现,不依赖任何第三方扩展(SQLite3 通常在 PHP 里默认启用),支持自动生成短码和自定义短码,做完直接能用。
完整代码(shorturl.php)
<?php
declare(strict_types=1);
$dbFile = __DIR__ . '/shorturl.db';
$baseUrl = 'https://你的域名/';
$pdo = new PDO('sqlite:' . $dbFile);
$pdo->exec('CREATE TABLE IF NOT EXISTS links (
code TEXT PRIMARY KEY,
url TEXT NOT NULL,
created_at INTEGER NOT NULL
)');
// 路由判断
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = trim($path, '/');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 生成短链: POST { "url": "https://...", "code": "可选" }
$input = json_decode(file_get_contents('php://input'), true);
$url = filter_var($input['url'] ?? '', FILTER_VALIDATE_URL);
if (!$url) { json(['code' => 1, 'message' => 'url 无效'], 400); }
$code = isset($input['code']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', $input['code']) : '';
if ($code === '') {
$code = base62(bin2hex(random_bytes(6)));
}
$stmt = $pdo->prepare('SELECT 1 FROM links WHERE code = ?');
$stmt->execute([$code]);
if ($stmt->fetchColumn()) { json(['code' => 2, 'message' => '短码已存在'], 409); }
$pdo->prepare('INSERT INTO links (code, url, created_at) VALUES (?, ?, ?)')
->execute([$code, $url, time()]);
json(['code' => 0, 'short' => $baseUrl . $code]);
}
if ($path !== '') {
// 跳转: 访问短码
$stmt = $pdo->prepare('SELECT url FROM links WHERE code = ?');
$stmt->execute([$path]);
$url = $stmt->fetchColumn();
if ($url) {
header('Location: ' . $url, true, 302);
exit;
}
http_response_code(404);
echo '短链不存在';
exit;
}
json(['code' => 0, 'message' => '短链服务运行中', 'usage' => 'POST {url, code?} => 生成,GET /code => 跳转']);
function base62(string $hex): string {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$num = hexdec($hex);
if ($num === 0) return '0';
$out = '';
while ($num > 0) {
$out = $chars[$num % 62] . $out;
$num = intdiv($num, 62);
}
return $out;
}
function json(array $data, int $status = 200): never {
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
使用说明
文件放任意 PHP 站点目录即可运行。生成短链用 POST 传 JSON,自动生成短码约 8~11 位;想用自己的短码传 code 字段。访问 https://域名/短码 即 302 跳转。SQLite 数据自动落库到同级 shorturl.db,备份时拷走这个文件即可。