# PHP_檔案相關

- #### 判斷資料夾是否存在，建立資料夾

```PHP
if ( !file_exists( $dir ) || !is_dir( $dir) ) {   mkdir($dir); }
```

- #### 遞回查詢資料夾內檔案

```PHP

function listdirs($dirf, $mark=1) {

    // LOB_MARK	若檔案為資料夾，在回傳檔案路徑的最後面加上斜線"\"
    // GLOB_NOSORT	保持檔案路徑在原資料夾的出現順序(不重新排序)
    // GLOB_NOCHECK	若找不到匹配的檔案路徑，回傳匹配的條件字串
    // GLOB_NOESCAPE	不要將反斜線視為跳脫字元
    // GLOB_BRACE	將 {a,b,c} 視為搜尋 'a', 'b', 或 'c'
    // GLOB_ONLYDIR	只列出資料夾路徑
    // GLOB_ERR	發生讀取錯誤時停止動作(像是無法讀取的資料夾)，預設是「忽略錯誤」
    $alldirs = array();
    if ($mark==1)
    {
        $alldirs = null;
    }
    $dirs = glob($dirf . '/*', GLOB_NOSORT);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dirf) listdirs($dirf, 0);
    return $alldirs;
}
$dirf="/tmp";
$result_data = listdirs($dirf, $mark=1);
echo print_r($result_data,true);
```

執行系統命令

```PHP
  function osCommand( $CMD="" )
  {
    $ret="";
    
    if( $CMD=="" )
      return $ret;
      
    if( ($fp = popen($CMD,"r")) )
    {
      $ret="";
      while( !feof( $fp ) )
        $ret .= fgets( $fp )."\n";
      fclose( $fp );
    }
    
    return $ret;
  }
if(!is_dir($log_folder)){
	mkdir($log_folder);
	osCommand( "chown webmaster.webmaster $log_folder");
}
```