夜雨聆风学习资料网

ARTICLE · 1514404

零代码搭建私人记账系统!多用户独立账本+手机完美适配,上传即用

零代码搭建私人记账系统!多用户独立账本+手机完美适配,上传即用


大家好,今天给大家带来一款纯PHP单文件、无需数据库、多用户独立隔离的超轻量家庭记账本,直接复制代码就能用,小白也能轻松搭建属于自己的私密记账工具!

🔥 这款记账本到底强在哪?

- 纯单文件运行:一个  index.php  搞定全部,不用配环境、不用装数据库
- 多用户独立账本:每个人数据单独目录存储,互不干扰、隐私安全
- 手机完美适配:极简卡片UI,移动端流畅操作,随身随手记账
- 收支分类自定义:系统默认分类+自定义分类,自由管理
- 按月/按年统计:自动汇总收入支出,明细从高到低排序,一目了然
- 防误删验证:删除记录必须做算术验证,再也不怕手滑删错
- 轻量化不占地:代码干净无冗余,服务器/虚拟主机/甚至本地都能跑

 

📱 直接上完整源码(复制即用)

把下面代码全部复制,保存为  index.php ,上传到你的PHP空间/服务器,直接访问就能用!

php
 

<?php
session_start();
date_default_timezone_set("Asia/Shanghai");

$self       = basename(__FILE__);
$user_file  = __DIR__ . '/users.txt';

// ===================== 核心修改:每个用户独立目录 =====================
$base_data  = __DIR__ . '/user_data/';
$username   = $_SESSION['user']['username'] ?? '';
$user_dir   = $username ? $base_data . $username . '/' : '';

$record_file= $user_dir . 'records.txt';
$cate_file  = $user_dir . 'categories.txt';
// =====================================================================

$is_login   = isset($_SESSION['user']);
$mode       = $_GET['mode'] ?? 'login';
$type       = $_GET['type'] ?? 'month';
$month      = $_GET['month'] ?? date('Y-m');
$year       = $_GET['year'] ?? date('Y');
$cate_page  = $_GET['cate'] ?? 0;
$detail_tab = $_GET['detail'] ?? 'income';

// 系统默认分类
$default_cates = [
    'income'  => ['工资', '奖金', '兼职'],
    'expense' => ['买菜', '餐饮', '交通']
];

// ------------------------------
// 注册
// ------------------------------
if (isset($_POST['register'])) {
    $u = trim($_POST['username']);
    $p = trim($_POST['password']);
    if ($u && $p) {
        $exists = false;
        if (file_exists($user_file)) {
            foreach (file($user_file, FILE_IGNORE_NEW_LINES) as $line) {
                $arr = explode('|', $line);
                if ($arr[0] === $u) $exists = true;
            }
        }
        if (!$exists) {
            file_put_contents($user_file, "$u|$p\n", FILE_APPEND);
            echo "<script>alert('注册成功!请登录');location.href='$self';</script>";
            exit;
        } else {
            echo "<script>alert('用户名已存在');</script>";
        }
    }
}

// ------------------------------
// 登录
// ------------------------------
if (isset($_POST['login'])) {
    $u = trim($_POST['username']);
    $p = trim($_POST['password']);
    if (file_exists($user_file)) {
        foreach (file($user_file, FILE_IGNORE_NEW_LINES) as $line) {
            $arr = explode('|', $line);
            if ($arr[0] === $u && $arr[1] === $p) {
                $_SESSION['user'] = ['username' => $u];
                if (!is_dir($base_data)) mkdir($base_data, 0700, true);
                if (!is_dir($base_data . $u)) mkdir($base_data . $u, 0700, true);
                echo "<script>location.href='$self';</script>";
                exit;
            }
        }
    }
    echo "<script>alert('账号或密码错误');</script>";
}

// ------------------------------
// 退出
// ------------------------------
if (isset($_GET['logout'])) {
    session_destroy();
    echo "<script>location.href='$self';</script>";
    exit;
}

// ------------------------------
// 新增分类
// ------------------------------
if (isset($_POST['add_cate']) && $is_login) {
    $ctype = $_POST['cate_type'];
    $cname = trim($_POST['cate_name']);
    if ($ctype && $cname) {
        $line = $ctype . '|' . $cname . "\n";
        file_put_contents($cate_file, $line, FILE_APPEND);
        echo "<script>alert('添加成功');location.href='$self?cate=1';</script>";
        exit;
    }
}

// ------------------------------
// 删除分类
// ------------------------------
if (isset($_GET['del_cate']) && $is_login) {
    $del_type = $_GET['del_type'];
    $del_name = trim($_GET['del_cate']);

    if (in_array($del_name, $default_cates[$del_type] ?? [])) {
        echo "<script>alert('系统默认分类不可删除!');location.href='$self?cate=1';</script>";
        exit;
    }

    $used = false;
    if (file_exists($record_file)) {
        foreach (file($record_file) as $line) {
            $a = explode('|', trim($line));
            if (count($a) >= 6 && $a[0] == $username && $a[1] == $del_type && $a[2] == $del_name) {
                $used = true;
                break;
            }
        }
    }

    if ($used) {
        echo "<script>alert('该分类已被使用,请先删除相关记账记录!');location.href='$self?cate=1';</script>";
        exit;
    }

    $all = file($cate_file, FILE_IGNORE_NEW_LINES);
    $new  = [];
    foreach ($all as $line) {
        $a = explode('|', trim($line));
        if (!(count($a) == 2 && $a[0] == $del_type && $a[1] == $del_name)) {
            $new[] = $line;
        }
    }
    file_put_contents($cate_file, implode("\n", $new) . "\n");
    echo "<script>alert('删除成功');location.href='$self?cate=1';</script>";
    exit;
}

// ------------------------------
// 删除单条记录
// ------------------------------
if (isset($_GET['del_record']) && $is_login) {
    $ans   = $_GET['ans'] ?? '';
    $exp   = $_GET['exp'] ?? '';
   
    $calc = @eval("return $exp;");
    if ($calc === false || $calc != $ans) {
        echo "<script>alert('验证错误,无法删除!');location.href='$self';</script>";
        exit;
    }

    $del_line = base64_decode($_GET['del_record']);
    $lines = file($record_file, FILE_IGNORE_NEW_LINES);
    $new_lines = [];
    foreach ($lines as $line) {
        if (trim($line) !== trim($del_line)) {
            $new_lines[] = $line;
        }
    }
    file_put_contents($record_file, implode("\n", $new_lines) . "\n");
    echo "<script>alert('删除成功');location.href='$self';</script>";
    exit;
}

// ------------------------------
// 读取分类
// ------------------------------
$cates = $default_cates;
$user_cates = ['income' => [], 'expense' => []];

if (file_exists($cate_file)) {
    foreach (file($cate_file, FILE_IGNORE_NEW_LINES) as $line) {
        $a = explode('|', trim($line));
        if (count($a) == 2) {
            $t = $a[0]; $n = $a[1];
            $user_cates[$t][] = $n;
        }
    }
}

foreach (['income', 'expense'] as $t) {
    $cates[$t] = array_unique(array_merge($cates[$t], $user_cates[$t]));
}

// ------------------------------
// 添加记录
// ------------------------------
if (isset($_POST['add']) && $is_login) {
    $t     = $_POST['type'];
    $cate  = $_POST['cate'];
    $money = (float)$_POST['money'];
    $note  = trim($_POST['note']);
    $time  = date('Y-m-d H:i:s');
    $line  = implode('|', [$username, $t, $cate, $money, $note, $time]) . "\n";
    file_put_contents($record_file, $line, FILE_APPEND);
    echo "<script>location.href='$self';</script>";
    exit;
}

// ------------------------------
// 读取记录
// ------------------------------
$records = [];
if (file_exists($record_file)) {
    foreach (file($record_file, FILE_IGNORE_NEW_LINES) as $line) {
        $arr = explode('|', trim($line));
        if (count($arr) < 6) continue;
        [$u, $t, $c, $m, $n, $dt] = $arr;
        if ($u !== $username) continue;
        $records[] = [
            'raw'    => $line,
            'user'   => $u,
            'type'   => $t,
            'cate'   => $c,
            'money'  => (float)$m,
            'note'   => $n,
            'time'   => $dt
        ];
    }
}

// ------------------------------
// 筛选月/年
// ------------------------------
$show = [];
foreach ($records as $r) {
    if ($type === 'month') {
        if (substr($r['time'], 0, 7) === $month) $show[] = $r;
    } else {
        if (substr($r['time'], 0, 4) === $year) $show[] = $r;
    }
}

$total_in = $total_out = 0;
foreach ($show as $r) {
    if ($r['type'] === 'income') $total_in += $r['money'];
    if ($r['type'] === 'expense') $total_out += $r['money'];
}

$in_list = array_filter($show, fn($v) => $v['type'] === 'income');
usort($in_list, fn($a, $b) => $b['money'] <=> $a['money']);

$out_list = array_filter($show, fn($v) => $v['type'] === 'expense');
usort($out_list, fn($a, $b) => $b['money'] <=> $a['money']);
?>

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>私人多用户记账本</title>
<style>
*{box-sizing:border-box;font-family:system-ui}
html,body{margin:0;padding:10px;background:#f7f8fa}
.card{background:#fff;border-radius:16px;padding:20px;margin-bottom:10px;box-shadow:0 2px 10px #00000008}
.title{font-size:18px;font-weight:600;margin-bottom:16px}
input,select{width:100%;padding:12px 14px;margin:8px 0;border:1px solid #e5e7eb;border-radius:12px;font-size:15px}
button{width:100%;padding:13px;border:none;border-radius:12px;background:#007aff;color:#fff;font-size:16px;margin-top:8px}
.btn-danger{background:#fa4040}
.btn-cate{background:#667eea;color:#fff;margin-top:0}
.toggle{text-align:center;margin-top:14px;font-size:14px;color:#666}
.toggle a{color:#007aff}
.tab{display:flex;gap:8px;margin-bottom:10px}
.tab a{flex:1;text-align:center;padding:10px;border-radius:10px;background:#f1f5ff;text-decoration:none;color:#333}
.tab a.active{background:#007aff;color:#fff}
.stats{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.stats .item{background:#f1f5ff;padding:14px;border-radius:12px;text-align:center;cursor:pointer}
.stats .item.active{background:#e0ebff}
.income{color:#07c160}
.expense{color:#fa4040}
.item-box{
    padding:12px 0;
    border-bottom:1px solid #f2f2f2;
    display:flex;
    justify-content:space-between;
    align-items:center;
}
.money{font-weight:bold}
.time{font-size:12px;color:#999}
.cate-item{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f2f2f2}
.del{color:#fa4040;font-size:14px}
.default-tag{font-size:12px;color:#999;margin-left:6px}
.detail-scroll{
    max-height: 220px;
    overflow-y: auto;
    padding-right: 5px;
}
.detail-scroll::-webkit-scrollbar{
    width: 4px;
}
.detail-scroll::-webkit-scrollbar-thumb{
    background: #ddd;
    border-radius: 2px;
}
#verifyMask{
    position:fixed;top:0;left:0;width:100%;height:100%;
    background:rgba(0,0,0,0.5);display:none;
    justify-content:center;align-items:center;z-index:9999
}
.verifyBox{background:#fff;border-radius:14px;padding:24px;width:90%;max-width:320px}
.verifyTitle{font-size:16px;font-weight:500;margin-bottom:16px;text-align:center}
.verifyLine{display:flex;align-items:center;gap:8px;margin-bottom:20px}
.verifyExp{font-size:16px}
.verifyInput{flex:1;border:1px solid #ddd;border-radius:8px;padding:10px 12px;font-size:16px}
.verifyBtns{display:flex;gap:10px}
.verifyBtn{flex:1;border:none;border-radius:8px;padding:12px;font-size:15px}
.btnCancel{background:#f1f1f1;color:#333}
.btnOk{background:#007aff;color:#fff}
</style>

<script>
function changeType() {
    let t = document.getElementById('type').value;
    document.querySelectorAll('.cate-option').forEach(o=>o.style.display = o.dataset.type==t?'block':'none');
    document.getElementById('cate').selectedIndex=0;
}
let currentRaw='',currentExp='';
function getRandomExp(){
    let a=Math.floor(Math.random()*9)+1,b=Math.floor(Math.random()*9)+1;return a+"+"+b;
}
function delCheck(raw){
    currentRaw=raw;currentExp=getRandomExp();
    document.getElementById('verifyExp').textContent=currentExp;
    document.getElementById('verifyMask').style.display='flex';
    document.getElementById('verifyInput').focus();
    return false;
}
function doDelete(){
    let ans=document.getElementById('verifyInput').value.trim();
    if(!ans)return;
    location.href=`?del_record=${currentRaw}&exp=${encodeURIComponent(currentExp)}&ans=${ans}`;
}
function closeMask(){document.getElementById('verifyMask').style.display='none'}
</script>

<div id="verifyMask">
    <div class="verifyBox">
        <div class="verifyTitle">删除验证</div>
        <div class="verifyLine">
            <span class="verifyExp" id="verifyExp"></span><span>=</span>
            <input type="number" class="verifyInput" id="verifyInput" placeholder="输入结果">
        </div>
        <div class="verifyBtns">
            <button class="verifyBtn btnCancel" onclick="closeMask()">取消</button>
            <button class="verifyBtn btnOk" onclick="doDelete()">确定删除</button>
        </div>
    </div>
</div>

<?php if(!$is_login): ?>
<div class="card">
    <?php if($mode == 'login'): ?>
        <div class="title" style="text-align:center">登录</div>
        <form method="post">
            <input name="username" placeholder="用户名" required>
            <input name="password" type="password" placeholder="密码" required>
            <button name="login">登录</button>
        </form>
        <div class="toggle">还没账号?<a href="?mode=register">去注册</a></div>
    <?php else: ?>
        <div class="title" style="text-align:center">注册</div>
        <form method="post">
            <input name="username" placeholder="用户名" required>
            <input name="password" type="password" placeholder="密码" required>
            <button name="register">注册</button>
        </form>
        <div class="toggle">已有账号?<a href="?mode=login">返回登录</a></div>
    <?php endif; ?>
</div>

<?php else: ?>

<div class="card">
    <div style="display:flex;justify-content:space-between">
        <div>欢迎:<?= $username ?></div>
        <a href="?logout=1" style="color:#fa4040">退出</a>
    </div>
</div>

<div class="card">
    <div class="tab">
        <a href="?type=month" class="<?= $type=='month'?'active':'' ?>">本月</a>
        <a href="?type=year" class="<?= $type=='year'?'active':'' ?>">本年</a>
    </div>
   
    <form method="get" id="filterForm">
        <input type="hidden" name="type" value="<?= $type ?>">
        <input type="hidden" name="detail" value="<?= $detail_tab ?>">
        <?php if($type=='month'): ?>
            <input type="month" name="month" value="<?= $month ?>" onchange="document.getElementById('filterForm').submit()">
        <?php else: ?>
            <select name="year" onchange="document.getElementById('filterForm').submit()">
                <?php for($y=2020;$y<=2030;$y++): ?>
                    <option value="<?= $y ?>" <?= $y==$year?'selected':'' ?>><?= $y ?>年</option>
                <?php endfor; ?>
            </select>
        <?php endif; ?>
    </form>
</div>

<div class="card">
    <div class="title"><?= $type=='month' ? $month : $year.'年' ?> 收支统计</div>
    <div class="stats">
        <a href="?type=<?= $type ?>&month=<?= $month ?>&year=<?= $year ?>&detail=income"
           class="item <?= $detail_tab == 'income' ? 'active' : '' ?>" style="text-decoration:none">
            总收入<br><b class="income">¥<?= $total_in ?></b>
        </a>
        <a href="?type=<?= $type ?>&month=<?= $month ?>&year=<?= $year ?>&detail=expense"
           class="item <?= $detail_tab == 'expense' ? 'active' : '' ?>" style="text-decoration:none">
            总支出<br><b class="expense">¥<?= $total_out ?></b>
        </a>
    </div>

    <div class="detail-scroll" style="margin-top:15px">
        <?php if($detail_tab == 'income'): ?>
            <div class="title income" style="font-size:16px;margin-bottom:10px">📥 收入明细</div>
            <?php if(empty($in_list)): ?>
                <div style="color:#999;padding:10px">暂无收入记录</div>
            <?php endif; ?>
            <?php foreach($in_list as $item): ?>
                <div class="item-box">
                    <div>
                        <div><?= $item['cate'] ?></div>
                        <div class="money income">+¥<?= $item['money'] ?></div>
                        <div class="time"><?= $item['time'] ?> <?= $item['note'] ?></div>
                    </div>
                    <a href="#" onclick="return delCheck('<?= base64_encode($item['raw']) ?>')" class="del">删除</a>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="title expense" style="font-size:16px;margin-bottom:10px">📤 支出明细</div>
            <?php if(empty($out_list)): ?>
                <div style="color:#999;padding:10px">暂无支出记录</div>
            <?php endif; ?>
            <?php foreach($out_list as $item): ?>
                <div class="item-box">
                    <div>
                        <div><?= $item['cate'] ?></div>
                        <div class="money expense">-¥<?= $item['money'] ?></div>
                        <div class="time"><?= $item['time'] ?> <?= $item['note'] ?></div>
                    </div>
                    <a href="#" onclick="return delCheck('<?= base64_encode($item['raw']) ?>')" class="del">删除</a>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<?php if(!$cate_page): ?>
<div class="card">
    <div class="title">快速记账</div>
    <a href="?cate=1" style="display:block;width:100%;text-align:center;background:#667eea;color:#fff;padding:12px;border-radius:12px;text-decoration:none;margin-bottom:10px">
        分类设置
    </a>
    <form method="post">
        <select name="type" id="type" onchange="changeType()" required>
            <option value="income">收入</option>
            <option value="expense">支出</option>
        </select>
        <select name="cate" id="cate" required>
            <?php foreach(['income','expense'] as $ct): ?>
                <?php foreach($cates[$ct] as $c): ?>
                    <option class="cate-option" data-type="<?= $ct ?>" value="<?= $c ?>"><?= $c ?></option>
                <?php endforeach; ?>
            <?php endforeach; ?>
        </select>
        <input name="money" type="number" step="0.01" placeholder="金额" required>
        <input name="note" placeholder="备注(选填)">
        <button name="add">保存记录</button>
    </form>
</div>

<?php else: ?>
<div class="card">
    <div class="title">分类设置</div>
    <a href="<?=$self?>" style="color:#007aff;text-decoration:none">← 返回记账</a>
   
    <div style="margin:16px 0">
        <form method="post" style="display:flex;gap:8px">
            <select name="cate_type" style="flex:2">
                <option value="income">收入</option>
                <option value="expense">支出</option>
            </select>
            <input name="cate_name" placeholder="输入分类名" style="flex:3" required>
            <button name="add_cate" style="flex:1">添加</button>
        </form>
    </div>

    <div style="margin-bottom:16px">
        <div style="font-size:14px;color:#666;margin-bottom:6px">收入分类</div>
        <?php foreach($cates['income'] as $c): ?>
            <div class="cate-item">
                <span>
                    <?= $c ?>
                    <?php if(in_array($c, $default_cates['income'])): ?>
                        <span class="default-tag">(默认)</span>
                    <?php endif; ?>
                </span>
                <?php if(!in_array($c, $default_cates['income'])): ?>
                    <a href="?del_type=income&del_cate=<?= urlencode($c) ?>&cate=1" class="del" onclick="return confirm('确定删除?')">删除</a>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <div>
        <div style="font-size:14px;color:#666;margin-bottom:6px">支出分类</div>
        <?php foreach($cates['expense'] as $c): ?>
            <div class="cate-item">
                <span>
                    <?= $c ?>
                    <?php if(in_array($c, $default_cates['expense'])): ?>
                        <span class="default-tag">(默认)</span>
                    <?php endif; ?>
                </span>
                <?php if(!in_array($c, $default_cates['expense'])): ?>
                    <a href="?del_type=expense&del_cate=<?= urlencode($c) ?>&cate=1" class="del" onclick="return confirm('确定删除?')">删除</a>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>
 

 

🚀 部署使用教程(30秒上手)

1. 新建文本文档,把上面代码完整粘贴进去
2. 另存为  index.php ,编码选择 UTF-8
3. 上传到支持PHP的服务器/虚拟主机
4. 直接访问网址,注册→登录,立刻开始记账

✅ 为什么推荐你用它?

市面上的记账APP要么广告多、要么收费、要么隐私不安全。
这款私人部署、数据自己掌控、多用户隔离、界面清爽无广告,真正属于你自己的记账工具!

不管是个人自用、家庭共用、还是小团队记账,全都完美hold住!
代码干净、无后门、无授权、无采集,安全放心,长期稳定使用。

 

💬 最后说两句

这么好用的零代码私人记账本,还不赶紧收藏搭建一个?
不用数据库、不用复杂配置,复制即用,真正做到随手记账、清晰管钱!

需要其他实用工具、源码教程,欢迎关注我,后续持续分享干货~

回首页,搜索你想要的文档

在首页搜索框输入关键词,快速定位资料

文库首页搜索指引 立即搜索

相关学习资料