Skip to content

Remove Filename From Path using PHP

You can easily get the only path from the given full path(Path with filename) using PHP’s built-in functions like dirname() and pathinfo().

Let’s assume your path is D:/projects/Demo/storage/app/agency/files/6/62414f6a7a123-HIPAAPrivacy.pdf and you want to get D:/projects/Demo/storage/app/agency/files/6/. You can remove the filename with the below two PHP examples.

Example with pathinfo()

<?php
	$file = "D:/projects/Demo/storage/app/agency/files/6/62414f6a7a123-HIPAAPrivacy.pdf";
  $dirname = pathinfo($file, PATHINFO_DIRNAME);
  echo $dirname; // output: D:/projects/Demo/storage/app/agency/files/6

//without PATHINFO_DIRNAME option
//  $dirname = pathinfo($file);
//  print_r($dirname);
// output will be 
/* Array
(
    [dirname] => D:/projects/Demo/storage/app/agency/files/6
    [basename] => 62414f6a7a123-HIPAAPrivacy.pdf
    [extension] => pdf
    [filename] => 62414f6a7a123-HIPAAPrivacy
) */
?>

Example with dirname()

If you are going to pass a path with a filename always, then this method is suitable, without a filename in the end it will fail, you will not get the expected result, since it gives you the parent folder’s name.

<?php
	$file = "D:/projects/Demo/storage/app/agency/files/6/62414f6a7a123-HIPAAPrivacy.pdf";
  $dirname = dirname($file);
  echo $dirname; // output: D:/projects/Demo/storage/app/agency/files/6
?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments