PHP文件操作之获取目录下文件与计算相对路径的
网络编程 2021-07-05 09:09www.168986.cn编程入门
这篇文章主要介绍了PHP文件操作技巧之获取目录下文件与计算相对路径的方法,其中获取目录下文件方面分为包含子目录和不包含子目录两种情况,需要的朋友可以参考下
获取目录下文件
1、获取目录下文件,不包括子目录
//获取某目录下所有文件、目录名(不包括子目录下文件、目录名) $handler = opendir($dir); while (($filename = readdir($handler)) !== false) {//务必使用!==,防止目录下出现类似文件名“0”等情况 if ($filename != "." && $filename != "..") { $files[] = $filename ; } } } closedir($handler); //打印所有文件名 foreach ($filens as $value) { echo $value."<br />"; }
2、获取目录下所有文件,包括子目录
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
<?php /** 计算path1 相对于 path2 的路径,即在path2引用paht1的相对路径 * @param String $path1 * @param String $path2 * @return String */ 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; } } // 将path2的/ 转为 ../,path1获取后面的部分,然后合拼 $tmp = array_merge(array_fill(0, count($arr2)-$depth-1, '..'), array_slice($arr1, $depth)); $relativePath = implode('/', $tmp); return $relativePath; } ?>
demo
<?php $path1 = '/home/web/lib/img/cache.php'; $path2 = '/home/web/api/img/show.php'; echo getRelativePath($path1, $path2); // ../../lib/img/cache.php ?>
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程