2012-07-23 19:18
浏览 82


I'm trying to create a drop down menu that points to a directory and populates a drop down menu with the names of certain files in that directory using PHP.

Here's what I'm working with:


$path = "pages/"; //change this if the script is in a different dir that the files you want
$show = array( '.php', '.html' ); //Type of files to show

$select = "<select name=\"content\" id=\"content\">";

$dh = @opendir( $path );

while( false !== ( $file = readdir( $dh ) ) ){
        if(in_array( $ext, $show )){       
            $select .= "<option value='$path/$file'>$file</option>

$select .= "</select>";
closedir( $dh );

echo "$select";

This bit of code is giving me an errors, and I'm not even really attached to it if there's a better way of trying to accomplish what I'm trying to do.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试创建一个指向目录的下拉菜单,并使用名称填充下拉菜单 使用PHP在该目录中的某些文件。


  $ path =“pages /”;  //如果脚本位于您想要的文件的另一个目录中,则更改此项
 $ show = array('。php','。html');  //要显示的文件类型
 $ select =“&lt; select name = \”content \“id = \”content \“&gt;”; 
 $ dh = @opendir($ path);  
而(假!==($ file = readdir($ dh))){
 $ ext = substr($ file,-4,4); 
 if(in_array($ ext,$ show))  {
 $ select。=“&lt; option value ='$ path / $ file'&gt; $ file&lt; / option&gt; 
 $ select。=“&lt; / 选择&gt;“; 
closedir($ dh); 
echo”$ select“; 

这段代码给了我一个错误,如果有更好的方法来尝试完成我的工作,我甚至都不会真正依赖它 试图做。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dst8922 2012-07-23 19:25

    It would be easier to use glob() because it can handle wildcards.

    // match all files that have either .html or .php extension
    $file_matcher = realpath(dirname(__FILE__)) . '/../pages/*.{php,html}';
    foreach( glob($file_matcher, GLOB_BRACE) as $file ) {
      $file_name = basename($file);
      $select .= "<option value='$file'>$file_name</option>
    点赞 评论
  • douchiwan1503 2012-07-23 19:25

    You need a full path reference (i.e. /var/www/pages/) instead of just "pages".

    Also you might consider using DirectoryIterator object for easily getting to directroy information (if you are using PHP 5).

    点赞 评论
  • dongwei8440 2012-07-23 19:25

    I don't know, which errors you get. But I think it won't work with the $show array because you're comparing the last 4 chars of the file with the contents of the array. Instead of $ext=substr($file,-4,4); you could write $ext=substr($file, strrpos( $file, ".")); which gives you the string from the position of the last occurance of ".".

    Also I suggest for test reason that you omit the @ opening the directory because I think that the path cannot be found.

    点赞 评论

相关推荐 更多相似问题