简体   繁体   English

使用PHP获取目录中单个文件的名称

[英]get name of single file in a directory using php

Although I can find plenty of examples of listing all of the files in a directory 虽然我可以找到很多列出目录中所有文件的示例

$dir = '../upload/'.$id.'/ask_temp';

But I need to get the name of a single file so I can store it in a variable to use elsewhere. 但是我需要获取单个文件的名称,以便将其存储在变量中以在其他地方使用。

There is and only ever will be one file in there. 那里只有一个文件。

In regards to ComFreek's answer, make sure to filter out any directory. 关于ComFreek的答案,请确保过滤掉任何目录。 (. and ..) (。和..)

I'm assuming you're using at least PHP 5.3 我假设您至少使用PHP 5.3

$files = array_filter(scandir($dir), function($val) use($dir)
{
    return is_file($dir.'/'.$val);
});

$myFile = $files[0];

Another way is to this, this is probably easier. 另一种方法是,这可能更容易。 (first 2 are always '.' and '..') (前两个始终为“。”和“ ..”)

$files = scandir($dir);
$myFile = $files[2];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM