2015-05-30 20 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函数减少了代码长度。这也使您可以轻松查看/管理允许哪些文件。

相关问题