2012-03-11 104 views
1

它可以通過.htaccess發送查詢到另一個文件? 有點解釋:QUERY_STRING在PHP中處理

的index.php處理所有的網頁是這樣的:

switch($page) { 
    case 'index': 
     require_once START . '/includes/pages/index.php'; 
    break; 

    case 'another': 
     require_once START . '/includes/pages/another.php'; 
    break; 
     and so on... 

在.htaccess:

RewriteRule ^index$ index.php?page=index [L] 
RewriteRule ^another$ index.php?page=another [L] 

鏈接(例如本地主機/ 84ss7d41):

RewriteRule ^(.*)$ index.php?QUERY_STRING=$1 [L] 

所以在/includes/pages/index.php

if ($_GET['QUERY_STRING']) { 
$_SERVER['QUERY_STRING'] = $_GET['QUERY_STRING']; 
$query_string = check_input($_SERVER['QUERY_STRING']); 
    //checking/validating processing further... 

如何使這樣一個本地主機/ 84ss7d41以相同的方式工作環節和現在一樣,但沒有的index.php?我想單獨我的「項目」,如果事情會發生(文件誤刪除)檢查/驗證的數據將工作一樣,沒有主腳本,它是這樣的:

if (main project file index.php/ || /includes/pages/index.php doesn't exist) { 
    check/validate data with reserve.php 
} 
+0

如果您想稍後避免麻煩,請勿覆蓋'$ _SERVER'陣列的成員。你試圖達到的目標應該是可能的,但你必須更清楚你想要達到的目標。 – hakre 2012-03-11 16:23:07

+0

你能澄清你的問題嗎?你想創建像'localhost/84ss7d41'這樣的鏈接,或者你想在index.php不存在的時候重定向用戶?你想要什麼? – MahanGM 2012-03-11 19:02:45

+0

@MahanGM正好,只要index.php不存在 – ZeroSuf3r 2012-03-12 11:30:41

回答

1
RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_URI} !=/index.php 
RewriteRule ^(.*) /index.php [L] 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*) /reserve.php [L] 

這種重定向是做所有的請求不匹配現有文件(例如圖像)到index.php,然後您可以使用$_SERVER["REQUEST_URI"]來決定如何操作。這是前端控制器模式的實現http://en.wikipedia.org/wiki/Front_Controller_pattern

此外,如果index.php不能通過apache的發現,則該請求將被轉發到reserve.php

雖然,構建在這種冗餘的不一定是「右'要做的事情(如果reserve.php也會丟失呢?)。對index.php執行適當的訪問控制可能是更好的方法。

+0

這顯然會導致一個「index.php」,但在這裏稱爲「controller.php」? – steveoh 2012-03-15 23:17:43

+1

@steveoh確實。我覺得我錯過了點... – 2012-03-15 23:25:46

+0

事實上,這是我不是在這裏開始的問題。爲什麼要殺死主腳本?除此之外:我喜歡前端控制器模式:) – steveoh 2012-03-15 23:29:02