PHP - Retrieving a Filename from a Path

Introduction

To separate a filename from its directory path, use basename() function.

It takes a complete file path and returning just the filename.

For example, the following code assigns index.html to $filename :

Demo

<?php
$filename = basename("/home/php/folder/docs/index.html" );
echo $filename;/*from www  . j a  v  a2s.c  o  m*/
?>

Result

You can specify a directory path instead, in which case the rightmost directory name is returned.

Here's an example that assigns the value docs to $dir :

Demo

<?php

$dir = basename("/home/php/folder/docs");
echo $dir;//from  w ww .j a  va 2  s .c om
?>

Result

basename() returns the last whole string after the rightmost slash.

To strip extension or suffix, use it as a second argument to basename().

The following example assigns "myfile" to $filename :

Demo

<?php

$filename = basename("/home/james/docs/myfile.doc" ,".doc" );
echo $filename;//w  w  w .j  a  v a2s  .  c o  m
?>

Result

Related Topic