PHP 下載完成後,使用 php -S localhost:8000 就可以建立一個伺服器,完全不需要阿帕契伺服器。This article is about creating server routing from scratch without Apache server with php. 基礎路由(routing) 在 php 本身提供的伺服器中,在哪個資料夾中執行 php -S localhost:8000,localhost:8000 這個網址就會找到哪個資料夾裡面的 index.php 或是 index.html 檔案,然後提供到前端頁面上。 如果輸入的網址沒有給任何的副檔名,伺服器也會抓 index.php 或是 index.html 檔案,然後提供到前端頁面上。 但是如有給提供附檔名,例如 http://localhost:8000/about.php,這邊的網址有 .php,伺服器就會找資料夾中是否有 about.php 這個檔案,然後提供到前端去。 自訂路由 我們可以運用 php 原生伺服器不提供附檔名網址就會導向提供 index.php 或是 index.html 這個特性來撰寫路由。 我們用 $_SERVER[REQUEST_URI] 這個內建全域變數來做。 當網址是 http://localhost:8000/about 時,$_SERVER[REQUEST_URI] 就是 /about。 接下來我們可以運用 switch case 或是 if statements 來建立路由。當然,也需要建立幾個頁面,舉例來說,home.php 跟 about.php。 最後,只要在用 require 或是 include 來提供頁面。 程式碼範例 <h1>This is my header</h1> <a href="/">Home</a> <a href="/about">About</a> <hr> <?php switch($_SERVER["REQUEST_URI"]){ case...