Comment puis-je obtenir un nom de fichier à partir d'un chemin complet avec PHP?

par exemple, comment obtenir Output.map

de

F:Program FilesSSH Communications SecuritySSH Secure ShellOutput.map

avec PHP?

175
demandé sur Peter Mortensen 2009-09-13 20:49:08

14 réponses

vous recherchez basename .

l'exemple du manuel PHP:

<?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"
?>
357
répondu Mark Rushakoff 2017-12-28 19:45:52

j'ai fait cela en utilisant la fonction PATHINFO qui crée un tableau avec les parties du chemin à utiliser! Par exemple, vous pouvez faire ceci:

<?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);
?>

Ce sera de retour:

/usr/admin/config
test.xml
xml
test

L'utilisation de cette fonction est disponible depuis PHP 5.2.0!

alors vous pouvez manipuler toutes les pièces dont vous avez besoin. Par exemple, pour utiliser le chemin complet, vous pouvez faire ceci:

$fullPath = $xmlFile['dirname'] . '/' . $xmlSchema['basename'];
54
répondu Metafaniel 2018-01-08 13:32:28

la fonction basename devrait vous donner ce que vous voulez:

donne une chaîne contenant un chemin vers un fichier, cette fonction retourne le nom de base du fichier.

par exemple, citant la page du manuel:

<?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"
?>

ou, dans votre cas:

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

, Vous obtiendrez:

string(10) "Output.map"
10
répondu Pascal MARTIN 2018-01-08 13:28:31

Avec SplFileInfo :

SplFileInfo la classe SplFileInfo offre un objet de haut niveau orienté interface avec l'information pour un fichier individuel.

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 "

7
répondu 7-isnotbad 2018-01-08 13:51:09

il y a plusieurs façons d'obtenir le nom et l'extension du fichier. Vous pouvez utiliser la suivante, qui est facile à utiliser.

$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
7
répondu Khadka Pushpendra 2018-01-08 13:56:17
$filename = basename($path);
6
répondu p4bl0 2009-09-13 16:51:23

basename () a un bug lors du traitement des caractères asiatiques comme le Chinois.

j'utilise ceci:

function get_basename($filename)
{
    return preg_replace('/^.+[\\\/]/', '', $filename);
}
6
répondu Sun Junwen 2018-01-08 13:30:32

essayez ceci:

echo basename($_SERVER["SCRIPT_FILENAME"], '.php') 
5
répondu atwebceo 2013-11-28 00:38:29

vous pouvez utiliser la fonction basename () .

3
répondu Vertigo 2018-01-08 13:28:47

pour ce faire dans les quelques lignes que je suggère d'utiliser la constante intégrée DIRECTORY_SEPARATOR avec explode(delimiter, string) pour séparer le chemin en parties et ensuite simplement enlever le dernier élément dans le tableau fourni.

exemple:

$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'
2
répondu Douglas Tober 2015-08-17 16:40:07

pour obtenir le nom exact du fichier de L'URI, j'utiliserais cette méthode:

<?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, '?'));
?>
1
répondu chandoo 2018-01-08 13:30:03

Basename ne fonctionne pas pour moi. J'ai obtenu le nom de fichier à partir d'un formulaire (fichier). Dans Google Chrome (Mac OS X v10.7 (Lion)) la variable file devient:

c:\fakepath\file.txt

quand j'utilise:

basename($_GET['file'])

il retourne:

c:\fakepath\file.txt

donc dans ce cas la réponse de Sun Junwen fonctionne mieux.

sur Firefox la variable du fichier n'inclut pas ce fakepath.

1
répondu ricardo 2018-01-08 13:50:11
<?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>
0
répondu antelove 2017-09-23 15:10:15

c'est simple. Par exemple:

<?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);
?>

la sortie sera:

Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)
0
répondu Kathir 2018-01-08 13:52:41