記錄 2015 年初開發留言板專案時常用的 PHP 時間處理函數、ThinkPHP 跳轉/重定向方法、唯一 ID 生成技巧,供同類專案快速參考。
| 函數 | 用途 | 範例 |
|---|---|---|
time() | 取得當前 Unix 時間戳(秒) | 1709280000 |
microtime(true) | 取得含微秒的時間戳(浮點數) | 1709280000.1234 |
date('Y-m-d H:i:s', $timestamp) | 格式化時間戳為可讀字串 | 2024-02-29 15:30:00 |
strtotime('2024-02-29 15:30:00') | 解析英文日期字串為時間戳 | 1709280000 |
常用組合:
<?php
// 當前格式化時間
$now = date('Y-m-d H:i:s');
// 指定日期轉時間戳
$ts = strtotime('2024-12-31 23:59:59');
// 相對時間計算
$tomorrow = strtotime('+1 day');
$lastWeek = strtotime('-1 week');
?>
<?php
// 無參數:13 字元(微秒時間戳基礎)
echo uniqid(); // 如:65e8f3a2b1c4d
// 有參數:23 字元(前綴 + 更高精度)
echo uniqid('msg_'); // 如:msg_65e8f3a2b1c4d7.89012345
echo uniqid('', true); // 開啟 more_entropy,如:65e8f3a2b1c4d7.890123
?>
應用場景: 留言 ID、訂單號前綴、暫存檔名、Session 防重複提交 Token。注意: uniqid() 不具加密安全性,敏感場景請用 random_bytes() 或 openssl_random_pseudo_bytes()。
| 方法 | 預設跳轉地址 | 預設等待時間 | 適用場景 |
|---|---|---|---|
success($msg, $url, $wait) | $_SERVER['HTTP_REFERER'](上一頁) | 1 秒 | 操作成功提示 |
error($msg, $url, $wait) | javascript:history.back(-1) | 3 秒 | 操作失敗/驗證錯誤 |
<?php
// 控制器中使用
$this->success('留言發布成功', U('Message/index'), 2);
$this->error('內容不能為空', '', 3); // 返回上一頁
?>
僅需重定向至指定 URL(非模組/控制器/方法),不顯示等待頁面:
<?php
// 參數:URL、延遲秒數、提示訊息
$this->redirect('https://example.com/thanks', 0, '正在跳轉...');
// 配合 U 函數生成內部 URL
$this->redirect(U('User/profile'), 2, '跳轉至個人中心');
?>
差異點: success/error 會顯示 ThinkPHP 內建等待模板;redirect 直接送出 HTTP 302 Location 標頭,瀏覽器立即跳轉。
<?php
class MessageController extends Controller {
public function add() {
if (!IS_POST) {
$this->error('非法請求');
}
$content = I('post.content', '', 'trim');
if (empty($content)) {
$this->error('留言內容不能為空');
}
$data = [
'content' => $content,
'uid' => session('user.id'),
'uname' => session('user.name'),
'ip' => get_client_ip(),
'create_time' => time(),
'uuid' => uniqid('msg_', true), // 唯一標識
];
if (M('Message')->add($data)) {
$this->success('發布成功', U('index'), 1);
} else {
$this->error('發布失敗,請重試');
}
}
}
?>
time() + date() 存儲,strtotime() 解析輸入。uniqid('prefix_', true) 簡單實用,高併發建議加隨機後綴或改用 UUID。success/error,純導向用 redirect。