获取目录下文件
1、获取目录下文件,不包括子目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $handler = opendir($dir);
while (($filename = readdir($handler)) !== false) {
if ($filename != "." && $filename != "..") {
$files[] = $filename ;
}
}
}
closedir($handler);
foreach ($filens as $value) {
echo $value."<br />";
}
|
2、获取目录下所有文件,包括子目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | function get_allfiles($path,&$files) {
if(is_dir($path)){
$dp = dir($path);
while ($file = $dp ->read()){
if($file !="." && $file !=".."){
get_allfiles($path."/".$file, $files);
}
}
$dp ->close();
}
if(is_file($path)){
$files[] = $path;
}
}
function get_filenamesbydir($dir){
$files = array();
get_allfiles($dir,$files);
return $files;
}
$filenames = get_filenamesbydir("static/image/");
foreach ($filenames as $value) {
echo $value."<br />";
}
|
计算两个文件之间的相对路径方法
php 计算两个文件之间的相对路径方法
例如:
文件A 的路径是 /home/web/lib/img/cache.php
文件B的路径是 /home/web/api/img/show.php
那么,文件A相对于文件B的路径是 ../../lib/img/cache.php,即文件B 访问 文件A的相对路径。
function getRelativePath
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <?php
function getRelativePath($path1, $path2){
$arr1 = explode('/', $path1);
$arr2 = explode('/', $path2);
$intersection = array_intersect_assoc($arr1, $arr2);
$depth = 0;
for($i=0,$len=count($intersection); $i<$len; $i++){
if(!isset($intersection[$i])){
$depth = $i;
break;
}
}
$tmp = array_merge(array_fill(0, count($arr2)-$depth-1, '..'), array_slice($arr1, $depth));
$relativePath = implode('/', $tmp);
return $relativePath;
}
?>
|
demo
1 2 3 4 5 6 | <?php
$path1 = '/home/web/lib/img/cache.php';
$path2 = '/home/web/api/img/show.php';
echo getRelativePath($path1, $path2);
?>
|