Tuesday, May 14, 2013

Get File Name Without File Extension in PHP

Definition and Usage - basename()
The basename() function returns the filename from a path.

pathRequired. Specifies the path to check
suffixOptional. Specifies a file extension. If the filename has this file extension, the file extension will not show

$path = "/testweb/home.php";

//Show filename with file extension
echo basename($path) ."<br/>";

//Show filename without file extension
echo basename($path,".php");
The output of the code above will be:

You have to know the extension to remove it in advance though.

You can use pathinfo() and basename() together if you don't know the extension of the file.

First get the extension using pathinfo(), and use the basename function, like this:

$path = "/testweb/home.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);

$file = basename($path, ".".$ext); // $file is set to "home"
Definition and Usage - pathinfo()

pathinfo() returns information about path: either an associative array or a string, depending on options.


1. If the path has more than one an extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one.
2. If the path does not have an extension, no extension element will be returned.

Ref: http://www.w3schools.com/php/func_filesystem_basename.asp and http://de.php.net/manual/en/function.pathinfo.php

1 comment:

  1. Thanks for the sharing this blog is very intersting. It's very informarmative and very knowladgeable blog.
    Genesis Technologies is one of the best IT company in Indore. We have developed a product accounting software development which is completely best in it's environment.