2017年2月6日 星期一

把 URL 中的路徑當成參數

今日在開發一個項目上需要盡量把網址縮短。最好的做法是扮成 RESTful 方式。即是把本來網址後面的參數變成路徑的一部份。我用 .htaccess 的 RewriteRule 來處理。
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?value=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ index.php?type=$1&code=$2 [L]
簡單寫了一個 PHP 程式去顯示讀進來的數值:
<?php
//----------------------------------------------------------------------------------------
//  Rewrite Rules DEMO
//----------------------------------------------------------------------------------------
//  Platform: Linux + Apache + PHP
//  Written by Pacess HO
//  Copyright 2017 Pacess Studio.  All rights reserved.
//----------------------------------------------------------------------------------------

header("Access-Control-Allow-Origin: https://home.pacess.com");
header("Access-Control-Allow-Methods: POST");
 
header("Content-type: text/plain");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Tue, 10 Mar 1987 00:00:00 GMT");
 
date_default_timezone_set("Asia/Hong_Kong");
mb_internal_encoding("UTF-8");
ini_set("memory_limit", "-1");
set_time_limit(0);

//========================================================================================
//  Main Program
$_interfaceType = php_sapi_name();

//  apache2handler = Browser
//  cli = Terminal
if ($_interfaceType == "cli")  {
   echo("Please run this program with browser...");
   exit(0);
}

$requestDump = print_r($_REQUEST, TRUE);
echo($requestDump);

?>

沒有留言: