Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: remove filename from path

Tags:

php

Say I have an path: images/alphabet/abc/23345.jpg

How do I remove the file at the end from the path? So I end up with: images/aphabet/abc/

like image 433
George Reith Avatar asked Jul 21 '11 21:07

George Reith


People also ask

How to remove file name from path in PHP?

Removing the file path from a filename in PHP is be easy! The basename() function will remove the file's path from your string and leave only the filename. So, for example, it means that if your file path string is: '/home/anto.

How to remove directory path in PHP?

PHP rmdir() Function The rmdir() function removes an empty directory.

What is __ FILE __ in PHP?

__FILE__ is simply the name of the current file. realpath(dirname(__FILE__)) gets the name of the directory that the file is in -- in essence, the directory that the app is installed in. And @ is PHP's extremely silly way of suppressing errors.


2 Answers

You want dirname()

like image 174
Byron Whitlock Avatar answered Oct 07 '22 01:10

Byron Whitlock


dirname() only gives you the parent folder's name, so dirname() will fail where pathinfo() will not.

For that, you should use pathinfo():

$dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME); 

The PATHINFO_DIRNAME tells pathinfo to directly return the dirname.

See some examples:

  • For path images/alphabet/abc/23345.jpg, both works:

    <?php  $dirname = dirname('images/alphabet/abc/23345.jpg');  // $dirname === 'images/alphabet/abc/'  $dirname = pathinfo('images/alphabet/abc/23345.jpg', PATHINFO_DIRNAME);  // $dirname === 'images/alphabet/abc/' 
  • For path images/alphabet/abc/, where dirname fails:

    <?php  $dirname = dirname('images/alphabet/abc/');  // $dirname === 'images/alphabet/'  $dirname = pathinfo('images/alphabet/abc/', PATHINFO_DIRNAME);  // $dirname === 'images/alphabet/abc/' 
like image 29
Machado Avatar answered Oct 07 '22 03:10

Machado