Skip to content

Instantly share code, notes, and snippets.

@biswarupadhikari
Created January 4, 2013 15:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biswarupadhikari/4453507 to your computer and use it in GitHub Desktop.
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

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

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

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