在同一页面上按ID包含文件


include files by ID on same page

有办法做到这一点吗?

包括文件:

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

fruits.php:

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

我想通过被包含文件中指定的ID来包含文件。谢谢你的帮助。

你的代码很不完整,但这是一个解决你问题的尝试。

<?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.';
}
?>
有很多case的

Switch语句会变得很长,并且会降低可读性。因此,第二个解决方案使用数组和in_array函数来减少代码长度。这还允许您轻松地查看/管理哪些文件是允许的。