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;/* w  w  w .j a  v  a 2s  .  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 www  .  j ava2 s.co m
?>

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  ww .j a  v a 2s.  c  om
?>

Result

Related Topic