整理 PHP 面試高頻三大核心筆試題,含標準答案、代碼實現、邊界情況處理與擴展思考,助你面試從容應對。
需求:給定兩個絕對路徑 $a、$b,計算 $b 相對於 $a 的相對路徑。
示例:
$a = '/a/b/c/d/e.php'
$b = '/a/b/12/34/c.php'
結果:../../12/34/
<?php
function getRelativePath($from, $to) {
// 規範化:去除尾部斜槓、分割為陣列
$fromParts = array_filter(explode('/', rtrim($from, '/')));
$toParts = array_filter(explode('/', rtrim($to, '/')));
// 找出共同前綴長度
$commonLen = 0;
$minLen = min(count($fromParts), count($toParts));
for ($i = 0; $i < $minLen; $i++) {
if ($fromParts[$i] === $toParts[$i]) $commonLen++;
else break;
}
// 構建相對路徑:向上級目錄 + 目標剩餘路徑
$upLevels = count($fromParts) - $commonLen;
$relative = str_repeat('../', $upLevels);
$relative .= implode('/', array_slice($toParts, $commonLen));
// 如果目標是檔案,保留檔案名;如果是目錄,補尾部斜槓
if (substr($to, -1) !== '/') {
// 已包含檔案名
} else {
$relative .= '/';
}
return $relative;
}
// 測試
$a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/c.php';
echo getRelativePath($a, $b); // 輸出:../../12/34/c.php
?>
.、..、多重斜槓、符號連結realpath() 規範化後再計算Symfony\Component\Filesystem\Filesystem::getRelativePath()SELECT * FROM table LIMIT offset, pageSize
offset = (currentPage - 1) * pageSize
| 問題 | 標準答案 | 進階優化 |
|---|---|---|
| 大偏移量性能下降 | LIMIT 1000000, 20 需掃描 100 萬行 | 延遲關聯:SELECT * FROM t INNER JOIN (SELECT id FROM t LIMIT 1000000, 20) tmp USING(id) |
| 總數統計慢 | COUNT(*) 全表掃描 | 資訊表估算、緩存總數、近似計數 |
| 游標分頁 | OFFSET 基礎 | WHERE id > last_id ORDER BY id LIMIT 20 無偏移量掃描 |
| 並發一致性 | 數據插入/刪除導致頁面漂移 | 快照隔離、版本號、游標標識 |
<?php
$method = $_SERVER['REQUEST_METHOD']; // 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'...
if ($method === 'POST') {
// 處理 POST
}
?>
$request->method() / $request->isMethod('post')$request->getMethod()Request::instance()->method()function isPost() { return $_SERVER['REQUEST_METHOD'] === 'POST'; }$_POST 非空 ≠ POST 請求(PUT/DELETE 也可能填充)method="post" + _method=put 模擬 PUT 需框架中介軟體支援REQUEST_METHOD 不存在這三題覆蓋字串處理、SQL 優化、HTTP 協議三大後端核心能力,吃透即過關。