274

For example, how do I get Output.map

from

F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map

with PHP?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
omg
  • 136,412
  • 142
  • 288
  • 348

14 Answers14

521

You're looking for basename.

The example from the PHP manual:

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 34
    basename() has a bug when processes Asian characters like Chinese. – Sun Junwen Mar 16 '13 at 10:30
  • 2
    Thanks Sun, you just saved me hours of bug killing since my app will be used overseas. – SilentSteel Mar 03 '14 at 21:52
  • 15
    I would suggest `pathinfo` over `basename` as Metafaniel posted below. `pathinfo()` will give you an array with the parts of the path. Or for the case here, you can just specifically ask for the filename. So `pathinfo('/var/www/html/index.php', PATHINFO_FILENAME)` should return `'index.php'` [PHP Pathinfo documentation](http://php.net/manual/en/function.pathinfo.php) – OnethingSimple Apr 19 '15 at 13:54
  • 10
    @OnethingSimple Check the docs again... counter intuitive though it is, you'll want `PATHINFO_BASENAME` to get the full `index.php`. `PATHINFO_FILENAME` will give you `index`. – levigroker Apr 12 '16 at 22:59
  • 1
    in any case, for a unicode compatible method, `mb_substr($filepath,mb_strrpos($filepath,'/',0,'UTF-16LE'),NULL,'UTF-16LE')` - just replace UTF-16LE with whatever characterset your filesystem uses (NTFS and ExFAT uses UTF16) – hanshenrik Sep 23 '17 at 15:20
  • Caution basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. – hakki Mar 10 '20 at 14:50
86

I've done this using the function PATHINFO which creates an array with the parts of the path for you to use! For example, you can do this:

<?php
    $xmlFile = pathinfo('/usr/admin/config/test.xml');

    function filePathParts($arg1) {
        echo $arg1['dirname'], "\n";
        echo $arg1['basename'], "\n";
        echo $arg1['extension'], "\n";
        echo $arg1['filename'], "\n";
    }

    filePathParts($xmlFile);
?>

This will return:

/usr/admin/config
test.xml
xml
test

The use of this function has been available since PHP 5.2.0!

Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:

$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];
Jeff Baker
  • 1,492
  • 1
  • 12
  • 15
Metafaniel
  • 29,318
  • 8
  • 40
  • 67
  • I had to change `\n` into `
    ` to get the formatted output you're describing?
    – Frank Conijn - Support Ukraine Aug 12 '21 at 09:23
  • 1
    @FrankConijn Because of your question, I can see you're using a web browser with my code snippet. In that case: yes, you have to replace `\n` with `
    `. My code is meant to be run using the command line, thus the line breaks with `\n` work. Greetings.
    – Metafaniel Aug 12 '21 at 22:10
19

There are several ways to get the file name and extension. You can use the following one which is easy to use.

$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
15

With SplFileInfo:

SplFileInfo The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

Ref: http://php.net/manual/en/splfileinfo.getfilename.php

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

o/p: string(7) "foo.txt"

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
internals-in
  • 4,798
  • 2
  • 21
  • 38
14

The basename function should give you what you want:

Given a string containing a path to a file, this function will return the base name of the file.

For instance, quoting the manual's page:

<?php
    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
?>

Or, in your case:

$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));

You'll get:

string(10) "Output.map"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
12

Try this:

echo basename($_SERVER["SCRIPT_FILENAME"], '.php') 
atwebceo
  • 293
  • 1
  • 4
  • 11
9

basename() has a bug when processing Asian characters like Chinese.

I use this:

function get_basename($filename)
{
    return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sun Junwen
  • 1,068
  • 10
  • 20
  • I don't think its a bug, in the [docs](https://www.php.net/manual/en/function.basename.php) its mentioned: `Caution basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. `. But I also prefere to use preg_replace, because the directory separator differ between operating systems. On Ubuntu `\\` is not a directoy separator and basename will have no effect on it. – Adam Jun 07 '20 at 08:35
8
$filename = basename($path);
p4bl0
  • 3,846
  • 1
  • 22
  • 21
5

You can use the basename() function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vertigo
  • 2,714
  • 1
  • 22
  • 24
4

To do this in the fewest lines I would suggest using the built-in DIRECTORY_SEPARATOR constant along with explode(delimiter, string) to separate the path into parts and then simply pluck off the last element in the provided array.

Example:

$path = 'F:\Program Files\SSH Communications Security\SSH SecureShell\Output.map'

//Get filename from path
$pathArr = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($pathArr);

echo $filename;
>> 'Output.map'
Douglas Tober
  • 300
  • 4
  • 15
3

To get the exact file name from the URI, I would use this method:

<?php
    $file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;

    //basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.

    echo $basename = substr($file1, 0, strpos($file1, '?'));
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chandoo
  • 1,276
  • 2
  • 21
  • 32
2

It's simple. For example:

<?php
    function filePath($filePath)
    {
        $fileParts = pathinfo($filePath);

        if (!isset($fileParts['filename']))
        {
            $fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
        }
        return $fileParts;
    }

    $filePath = filePath('/www/htdocs/index.html');
    print_r($filePath);
?>

The output will be:

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kathir
  • 1,212
  • 15
  • 25
1
$image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);
Chandni Soni
  • 377
  • 4
  • 16
  • Please describe what did you change and why, to help others identify the problem and understand this answer – FZs Apr 04 '19 at 18:30
0
<?php

  $windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";

  /* str_replace(find, replace, string, count) */
  $unix    = str_replace("\\", "/", $windows);

  print_r(pathinfo($unix, PATHINFO_BASENAME));

?> 

body, html, iframe { 
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
<iframe src="https://ideone.com/Rfxd0P"></iframe>
antelove
  • 3,216
  • 26
  • 20