PHP 파일 작업: 디렉토리에서 파일을 얻고 상대 경로를 계산하는 방법

WBOY
풀어 주다: 2016-07-29 09:07:09
원래의
1164명이 탐색했습니다.

디렉터리의 파일 가져오기

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 파일 A에 액세스하는 파일 B의 상대 경로인 ../../lib/img/cache.php입니다.

getRelativePath 함수

<&#63;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; 
} 
&#63;> 

로그인 후 복사

데모

<&#63;php 
$path1 = '/home/web/lib/img/cache.php'; 
$path2 = '/home/web/api/img/show.php'; 
 
echo getRelativePath($path1, $path2); // ../../lib/img/cache.php 
&#63;> 
로그인 후 복사

위에서는 관련 내용을 포함하여 디렉토리에서 파일을 얻고 PHP 파일 작업의 상대 경로를 계산하는 방법을 소개했습니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!