2015-05-30 21 views
-2

有沒有辦法做到這一點?在同一頁面上包含ID的文件

包括文件:

<?php 
$_GET["id"]; 
case "fruits": include 'fruits.php'; 
?> 

fruits.php:

<?php 
$id = 'fruits'; 
echo 'hello fruits'; 
?> 

我想包括在所包含的文件中指定的ID文件。 感謝您的幫助。

+0

首先修復PHP中的拼寫錯誤和語法錯誤,比試圖研究'$ id'和'$ _GET ['id']'之間的區別。 – panther

+0

如果'$ _GET [「id」]'是「hello」,它應該包含'hello.php'或者什麼? – MortenMoulder

+0

完成。我不確定$ _GET是僅用於表單處理還是從單獨的文件中獲取任何值。 – tgifred

回答

0

你的代碼是非常不完整的,但這裏試圖解決你的問題。

<?php 
// Get the ID parameter and change it to a standard form 
// (Standard form is all lower case with no leading or trailing spaces) 
$FileId = strtolower(trim($_GET['id'])); 

// Check the File ID and load up the relevant file 
switch($FileId){ 
    case 'fruits': 
     require('fruits.php'); 
     break; 
    case 'something_else': 
     require('something_else.php'); 
     break; 
    /* ... your other test cases... */ 
    default: 
     // Unknown file requested 
     echo 'An error has occurred. An unknown file was requested.'; 
} 
?> 

另外,如果有可能的文件一個長長的清單,我想提出以下建議:

<?php 
// Get the ID parameter and change it to a standard form 
// (Standard form is all lower case with no leading or trailing spaces) 
$FileId = strtolower(trim($_GET['id'])); 

// Array of possible options: 
$FileOptions = array('fruits', 'something_else', 'file1', 'file2' /* ... etc... */); 

// Check if FileId is valid 
if(in_array($FileId, $FileOptions, true)){ 
    // FileId is a valid option 
    $FullFilename = $FileId . '.php'; 
    require($FullFilename); 
}else{ 
    // Invalid file option 
    echo 'An error has occurred. An unknown file was requested.'; 
} 
?> 

switch語句有很多的情況下能夠得到長期,他們可以降低可讀性。因此,第二種解決方案使用一個數組,並且in_array函數減少了代碼長度。這也使您可以輕鬆查看/管理允許哪些文件。

相關問題