Skip to content

Instantly share code, notes, and snippets.

@biswarupadhikari
Created January 4, 2013 15:34
Show Gist options
  • Select an option

  • Save biswarupadhikari/4453507 to your computer and use it in GitHub Desktop.

Select an option

Save biswarupadhikari/4453507 to your computer and use it in GitHub Desktop.
is_subdir php function. How to check is sub directory is php
<?php
function is_subdir($parent,$sub){
$parent=rtrim($parent,'/');
$sub=rtrim($sub,'/');
$parent=explode('/',$parent);
$sub=explode('/',$sub);
for($i=0;$i<count($parent);$i++){
if($parent[$i]!=$sub[$i]){
return false;
}
}
return true;
}
?>
/**
Use Of The Function
**/
$parent="/home/adidac/fsdfsfsdDesktopsadasd";
$sub="/home/adidac/fsdfsfsdDesktopsadasd/asda/sd/asd/asd/asd/as/d";
if(is_subdir($parent,$sub)){
echo "Yes Sub Dir";
}else{
echo "Not Sub Dir";
}
@eco747
Copy link
Copy Markdown

eco747 commented Jan 7, 2014

care, this function check only common part of both directories.
ie. if parent is a\b\c\d\e and sub is a\b\c\d\e........ you will get a small problem

this function do not check backslashes.

@fatihgvn
Copy link
Copy Markdown

function is_subdir($parent,$sub){
  $parent=rtrim($parent,'/');
  $sub=rtrim($sub,'/');
  $parent=explode('/',$parent);
  $sub=explode('/',$sub);
  if(count($sub) >= count($parent)){
    for($i=0;$i<count($parent);$i++){
      if($parent[$i]!=$sub[$i]){
        return false;
      }
    }
    return true;
  }
  return false;
}

Thank you for the function. It worked for me. I modified it a bit.

@yCodeTech
Copy link
Copy Markdown

yCodeTech commented Sep 12, 2023

Doesn't work if the sub directory is the parent directory.

$parent = "/home/adidac/fsdfsfsdDesktopsadasd";
$sub = "/home/adidac/fsdfsfsdDesktopsadasd";

It would still return true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment