Php имя файла без расширения
Если у меня есть файл с именем my.zip , эта функция возвращает .zip .
Я хочу сделать обратное, я хочу, чтобы функция возвращала my без расширения.
Файл представляет собой просто строку в переменной.
17 Answers 17
No need for all that. Check out pathinfo(), it gives you all the components of your path.
Example from the manual:
Output of the code:
And alternatively you can get only certain parts like:
Why was this downvoted? The answer is absolutely correct. pathinfo operates on strings, so it doesn't matter if the file is actually on the server or not.
It's unfortunate that they misnamed "basename", since it returns the full filename with extension, not the base name.
This is very useful, especially when you don't need to know the file extension in order to extract it.
As an alternative to pathinfo() , you can use
Example from PHP manual
You have to know the extension to remove it in advance though.
However, since your question suggests you have the need for getting the extension and the basename, I'd vote Pekka's answer as the most useful one, because it will give you any info you'd want about the path and file with one single native function.
what if i do not know about file extension .. let say if path is dynamic anytype of file extension can come in it !! then what ??
@user889030 then you have a different scenario than the OP and don't use basename , but pathinfo as shown elsewere on the page.
Whoever decided that filename doesn't have an extension while basename does must have some sadistic tendencies.
Another approach is by using regular expressions.
This removes from the last period . up until the end of the string.
Much better than using explode, and only catches the last period section in case you used periods in file names
@caiosm1005, The attack surface immediately increases because It's hard to reason against the internals of a regex engine. For example, in the code above, it wouldn't be odd if there's some input $fileName which could cause the engine to run in exponential (or worse) time. And assuming we have finished dissecting the internals of this specific regex engine and have theoretically proven it to be robust against every possible value $fileName could be, the code is still not arbitrarily portable to another platform that has another implementation of the regex engine.
If the extension is not known, use this solution
Please provide a like to the php man page for pathinfo . This is going to help OP make the ShowFileExtension method better and will provide extra reading for anyone trying to find this answer. Also a bit of a description would not go astray.
There is no need to write lots of code. Even it can be done just by one line of code. See here
Below is the one line code that returns the filename only and removes extension name:
This was already mentioned in the accepted answer. This answer adds nothing new to the page at the time that it was posted.
Almost all the above solution have the shown getting filename from variable $path
Below snippet will get the current executed file name without extension
Explanation
$_SERVER['SCRIPT_NAME'] contains the path of the current script.
@Gordon basename will work fine if you know the extension, if you dont you can use explode:
Please direct comments to me with the comment function below my answer. The most appropriate function for this is pathinfo , which is why I gave basename as an alternative only. There is no need to reinvent pathinfo with regex or explode .
@fire, Your update makes no sense. end(explode(".", $file)); gives you the extension, not the filename.
Если у меня есть файл с именем my.zip , эта функция вернется .zip .
Я хочу сделать обратное, я хочу, чтобы функция возвращалась my без расширения.
Файл - это просто строка в переменной.
Во всем этом нет нужды. Проверьте pathinfo () , он дает вам все компоненты вашего пути.
Пример из мануала:
В качестве альтернативы вы можете получить только определенные части, такие как:
Почему это было отклонено? Ответ абсолютно правильный. pathinfo работает со строками, поэтому не имеет значения, действительно ли файл находится на сервере или нет.
К сожалению, они неправильно назвали «базовое имя», поскольку оно возвращает полное имя файла с расширением, а не базовое имя.
@Oscar - это наиболее широко понимаемое значение этого термина basename . Никаких неправильных названий.
В качестве альтернативы pathinfo() вы можете использовать
Пример из руководства по PHP
Вы должны знать расширение, чтобы удалить его заранее.
Однако, поскольку ваш вопрос предполагает, что вам нужно получить расширение и базовое имя, я бы проголосовал за ответ Пекки как наиболее полезный, потому что он предоставит вам любую информацию, которую вы хотите о пути и файле с одним единственным родным функция.
что, если я не знаю о расширении файла . скажем, если путь является динамическим, в него может входить любой тип расширения файла !! и что ??
@ user889030, то у вас есть сценарий, отличный от OP, и вы не используете его basename , но pathinfo как показано на странице.
Другой подход - использование регулярных выражений.
Это удаляет от последнего периода . до конца строки.
Намного лучше, чем использование разнесения, и захватывает только последний раздел периода, если вы использовали точки в именах файлов.
Спасибо, и приведенные выше комментарии подтвердили это. Отсутствие необходимости знать расширение делает это более полезным.
@ caiosm1005, поверхность атаки сразу же увеличивается, потому что трудно рассуждать против внутренней части движка регулярных выражений. Например, в приведенном выше коде было бы не странно, если бы был какой-то ввод, $fileName который мог бы заставить двигатель работать в экспоненциальном (или, что еще хуже) времени. И если предположить, что мы закончили анализ внутренних компонентов этого конкретного механизма регулярных выражений и теоретически доказали его устойчивость к любым возможным значениям $fileName , код по-прежнему не может произвольно переноситься на другую платформу, которая имеет другую реализацию механизма регулярных выражений.
Примеры
echo "1) " . basename ( "/etc/sudoers.d" , ".d" ). PHP_EOL ;
echo "2) " . basename ( "/etc/sudoers.d" ). PHP_EOL ;
echo "3) " . basename ( "/etc/passwd" ). PHP_EOL ;
echo "4) " . basename ( "/etc/" ). PHP_EOL ;
echo "5) " . basename ( "." ). PHP_EOL ;
echo "6) " . basename ( "/" );
?>?php
Результат выполнения данного примера:
Список параметров
На платформах Windows в качестве разделителей имён директорий используются оба слеша (прямой / и обратный \ ). В других операционных системах разделителем служит прямой слеш ( / ).
Если компонент имени заканчивается на suffix , то он также будет отброшен.
Примеры
$path_parts = pathinfo ( '/www/htdocs/inc/lib.inc.php' );
?phpecho $path_parts [ 'dirname' ], "\n" ;
echo $path_parts [ 'basename' ], "\n" ;
echo $path_parts [ 'extension' ], "\n" ;
echo $path_parts [ 'filename' ], "\n" ;
?>
Результат выполнения данного примера:
$path_parts = pathinfo ( '/path/emptyextension.' );
var_dump ( $path_parts [ 'extension' ]);
$path_parts = pathinfo ( '/path/noextension' );
var_dump ( $path_parts [ 'extension' ]);
?>
Результатом выполнения данного примера будет что-то подобное:
Результатом выполнения данного примера будет что-то подобное:
Возвращаемые значения
Возвращает базовое имя указанного пути path .
Смотрите также
- dirname() - Возвращает имя родительского каталога из указанного пути
- pathinfo() - Возвращает информацию о пути к файлу
ОТВЕТЫ
Ответ 1
Не нужно этого. Проверьте pathinfo(), он предоставит вам все компоненты вашего пути.
Пример из руководства:
И, альтернативно, вы можете получить только определенные части, например:
Ответ 2
В качестве альтернативы pathinfo() вы можете использовать
Пример из руководства PHP
Вы должны знать расширение, чтобы удалить его заранее, хотя.
Однако, поскольку ваш вопрос подсказывает, что вам нужно получить расширение и базовое имя, я бы голосовал Pekka answer как самый полезный, потому что он будет предоставить вам любую информацию, которую вы хотите о пути и файле, с одной единственной встроенной функцией.
Ответ 3
Ответ 4
Другой подход заключается в использовании регулярных выражений.
Это удаляет из последнего периода . до конца строки.
Ответ 5
Если расширение неизвестно, используйте это решение
Ответ 6
@Bordon basename будет работать нормально, если вы знаете расширение, если вы не можете использовать explode:
Ответ 7
Почти все вышеупомянутое решение имеет показанное получение имени файла из переменной $path
Ниже фрагмента будет получить текущее имя исполняемого файла без расширения
Объяснение
$_ SERVER ['SCRIPT_NAME'] содержит путь к текущему script.
Ответ 8
Там нет необходимости писать много кода. Даже это может быть сделано только одной строкой кода. Смотрите здесь
Ниже приведен однострочный код, который возвращает только имя файла и удаляет расширение:
Ответ 9
@fire, если имя файла использует точки, вы можете получить неправильный вывод. Я бы использовал метод @Gordon, но также получил расширение, поэтому функция basename работает со всеми расширениями, например:
Ответ 10
в моем случае, я использую ниже. Меня не волнует, каково его расширение.: D я думаю, это поможет вам
Ответ 11
Вы можете написать это
Они возвращают текущий элемент массива, если он не используется ранее.
Ответ 12
Ответ 13
Имя файла без расширения файла, если вы не знаете этого расширения:
$basename = substr($filename, 0, strrpos($filename, "."));
Ответ 14
Если вы не знаете, какое расширение у вас есть, вы можете попробовать следующее:
Работа со всеми возможностями:
Ответ 15
Ваш ответ ниже идеального решения скрыть до расширения файла в php.
Ответ 16
Это возвращает только имя файла без расширения в 1 строке:
Ответ 17
Существующие решения не работают, когда есть несколько частей для расширения. Функция ниже работает для нескольких частей, полного пути или просто имени файла aa:
При передаче строки с путём к файлу или каталогу, данная функция вернёт последний компонент имени из данного пути.
Замечание:
basename() наивно оперирует исключительно исходной строкой и не учитывает реальную файловую систему или компоненты пути типа " .. ".
basename() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() . Если path содержит символы, недопустимые для текущей локали, поведение basename() не определено.
User Contributed Notes 30 notes
It's a shame, that for a 20 years of development we don't have mb_basename() yet!
// works both in windows and unix
function mb_basename($path) if (preg_match('@^.*[\\\\/]([^\\\\/]+)$@s', $path, $matches)) return $matches[1];
> else if (preg_match('@^([^\\\\/]+)$@s', $path, $matches)) return $matches[1];
>
return '';
>
Support of the $suffix parameter has changed between PHP4 and PHP5:
in PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.
There is only one variant that works in my case for my Russian UTF-8 letters:
function mb_basename ( $file )
<
return end ( explode ( '/' , $file ));
>
>
It is intented for UNIX servers
It might be useful to have a version of the function basename working with arrays too.
function a_basename ( $file , $exts )
<
$onlyfilename = end ( explode ( "/" , $file ) );
if( is_string ( $exts ) )
<
if ( strpos ( $onlyfilename , $exts , 0 ) !== false )
$onlyfilename = str_replace ( $exts , "" , $onlyfilename );
>
else if ( is_array ( $exts ) )
<
// works with PHP version foreach( $exts as $KEY => $ext )
<
$onlyfilename = str_replace ( $ext , "" , $onlyfilename );
>
>
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.
// your file
$file = 'image.jpg' ;
$info = pathinfo ( $file );
$file_name = basename ( $file , '.' . $info [ 'extension' ]);
echo $file_name ; // outputs 'image'
If your path has a query string appended, and if the query string contains a "/" character, then the suggestions for extracting the filename offered below don't work.
Then both the php basename() function, and also
the $_SERVER[QUERY_STRING] variables get confused.
In such a case, use:
There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):
$newfile = basename ( $filen );
if ( strpos ( $newfile , '\\' ) !== false ) <
$tmp = preg_split ( "[\\\]" , $newfile );
$newfile = $tmp [ count ( $tmp ) - 1 ];
>
?>
$newfile will now contain only the file name and extension, even if the POSTed file name included a full Windows path.
Exmaple for exploding ;) the filename to an array
echo( basename ( $PHP_SELF ). "
" ); // returnes filename.php
$file = basename ( $PHP_SELF );
$file = explode ( "." , $file );
print_r ( $file ); // returnes Array ( [0] => filename [1] => php )
echo( "
" );
$filename = basename ( strval ( $file [ 0 ]), $file [ 1 ]);
echo( $filename . "
" ); // returnes filename
echo( basename ( $PHP_SELF , ".php" ). "
" ); // returnes filename
echo( "
" );
echo( "
" );
//show_source(basename ($PHP_SELF,".php").".php")
show_source ( $file [ 0 ]. "." . $file [ 1 ])
?>
Additional note to Anonymous's mb_basename() solution: get rid of trailing slashes/backslashes!
function mb_basename ( $path ) if ( preg_match ( '@^.*[\\\\/]([^\\\\/]+)([\\\\/]+)?$@s' , $path , $matches )) return $matches [ 1 ];
> else if ( preg_match ( '@^([^\\\\/]+)([\\\\/]+)?$@s' , $path , $matches )) return $matches [ 1 ];
>
return '' ;
>
If you want the current path where youre file is and not the full path then use this :)
echo( 'dir = ' . basename ( dirname ( $_SERVER [ 'PHP_SELF' ]), "/" ));
// retuns the name of current used directory
?>
Example:
echo( 'dirname
' . dirname ( $_SERVER [ 'PHP_SELF' ]). '
' );
// returns: /temp/2005/january
?>
echo( 'file = ' . basename ( $PHP_SELF , ".php" ));
// returns: t1
?>
if you combine these two you get this
echo( 'dir = ' . basename ( dirname ( $_SERVER [ 'PHP_SELF' ]), "/" ));
// returns: january
?>
And for the full path use this
echo( ' PHP_SELF
' . $_SERVER [ 'PHP_SELF' ]. '
' );
// returns: /temp/2005/january/t1.php
?>
There is a problem reading non-Latin characters in the file name if the locale is not configured correctly.
For example: instead of the name «ФЫВА-1234.doc», is displayed «-1234.doc».
Solution: rawurldecode(basename($full_name)).
A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))
since basename always treats a path as a path to a file, e.g.
/var/www/site/foo/ indicates /var/www/site as the path to file
foo
@ lcvalentine at gmail dot com
>This is much simpler:
>$ext = strrchr( $filename, '.' );
Even though yours is shorter, you can also do:
$ext = end(explode(".", basename($file
The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
function GetFileName ( $file_name )
$newfile = basename ( $file_name );
if ( strpos ( $newfile , '\\' ) !== false )
$tmp = preg_split ( "[\\\]" , $newfile );
$newfile = $tmp [ count ( $tmp ) - 1 ];
return( $newfile );
>
else
return( $file_name );
>
>
?>
This is much simpler:
$ext = strrchr( $filename, '.' );
to get the base url of my website
On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:
//assume the real filename is mytest.JPG:
$name_i_have = "mytest.jpg" ;
$realfilename = basename ( realpath ( $name_i_have ));
?>
basename itself does not check the filesystem for the given file, it does, so it seems, only string-manipulation.
With realpath() you can "extend" this functionality.
once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:
function splitFilename ( $filename )
<
$pos = strrpos ( $filename , '.' );
if ( $pos === false )
< // dot is not found in the filename
return array( $filename , '' ); // no extension
>
else
<
$basename = substr ( $filename , 0 , $pos );
$extension = substr ( $filename , $pos + 1 );
return array( $basename , $extension );
>
>
?>
I got a blank output from this code
suggested earlier by a friend here.
So anybody who wants to get the current directory path can use another technique that I use as
//suppose you're using this in pageitself.php page
I hope it helps.
As already pointed out above, if a query string contains a '/' character, basename will not handle it well. But it can come really handy when you want to pass a url with query string to a funtion that copies/downloads the file using basename as local filename, by attaching an extra query to the end of the url:
$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$file = $file[0];
$query = $file[1];
Now $file only contains "file.php" and $query contains the query-string (in this case "var=foo").
Basename without query string:
$filename = array_shift ( explode ( '?' , basename ( $url_path )));
?>
simple but not said in the above examples
which is not the filename in case you expect!
My opinion is, remove the $suffix first, and then apply splitting the core basename ( PHP 4 ):
return ( isset($fixed_basename) ? array_pop($fixed_basename) : array_pop(explode('/', $path)) );
>
>
icewinds exmaple wouldn't work, the query part would contain the second char of the filename, not the query part of the url.
$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$query = $file[1];
$file = $file[0];
?>
That works better.
defined ( 'baseUrlFileName' ) or define ( 'baseUrlFileName' ,
explode ( '.' , explode ( '/' , $_SERVER [ 'PHP_SELF' ])[ 3 ])[ 0 ]);
pathinfo() возвращает информацию о path в виде ассоциативного массива или строки, в зависимости от flags .
Замечание:
Подробнее о получении информации о текущем пути, можно почитать в разделе Предопределённые зарезервированные переменные.
Замечание:
pathinfo() оперирует входной строкой и не знает фактическую файловую систему или компоненты пути, такие как " .. ".
pathinfo() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() .
Возвращаемые значения
Если параметр flags не передан, то возвращаемый ассоциативный массив ( array ) будет содержать следующие элементы: dirname , basename , extension (если есть) и filename .
Замечание:
Если path содержит больше одного расширения, то PATHINFO_EXTENSION возвращает только последний и PATHINFO_FILENAME удаляет только последнее расширение. (смотрите пример ниже).
Замечание:
Если path не содержит расширения, то не будет возвращён элемент extension (смотрите ниже второй пример).
Замечание:
Если basename параметра path начинается с точки, то все последующие символы интерпретируются как расширение файла ( extension ) и имя файла filename будет пустым (смотрите третий пример).
Если указан параметр flags , будет возвращена строка ( string ), содержащая указанный элемент.
Список параметров
Если указан, то задаёт, какой из элементов пути будет возвращён: PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION и PATHINFO_FILENAME .
Если flags не указан, то возвращаются все доступные элементы.
User Contributed Notes 37 notes
Simple example of pathinfo and array destructuring in PHP 7:
[ 'basename' => $basename , 'dirname' => $dirname ] = pathinfo ( '/www/htdocs/inc/lib.inc.php' );
var_dump ( $basename , $dirname );
// result:
// string(11) "lib.inc.php"
// string(15) "/www/htdocs/inc"
?>
pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.
Reality:
var_dump(pathinfo('中国人2016.xls'));
exit();
array(4) < 'dirname' =>string(1) "." 'basename' => string(8) "2016.xls" 'extension' => string(3) "xls" 'filename' => string(4) "2016" >
Expect(Solve):
setlocale(LC_ALL, 'zh_CN.UTF-8');
var_dump(pathinfo('中国人2016.xls'));
exit();
array(4) < 'dirname' =>string(1) "." 'basename' => string(17) "中国人2016.xls" 'extension' => string(3) "xls" 'filename' => string(13) "中国人2016" >
unexpected, but longtime (all versions?) consistent, behaviour with trailing slash (Linux):
with Linux I am used, to add a trailing slash,
or just to keep that of the command line completion by [TAB],
to avoid mistyping a path on cp or mv with a same filename instead of a directory
using CLI '$ php -a' the result is in the next line
(but can also be done by script, webserver, etc.)
php > var_dump ( pathinfo ( '/home/USER/www.2021-05/' ));
array( 4 ) [ "dirname" ]=> string ( 10 ) "/home/USER"
[ "basename" ]=> string ( 11 ) "www.2021-05"
[ "extension" ]=> string ( 7 ) "2021-05"
[ "filename" ]=> string ( 3 ) "www"
>
Use this function in place of pathinfo to make it work with UTF-8 encoded file names too
function mb_pathinfo ( $filepath ) preg_match ( '%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im' , $filepath , $m );
if( $m [ 1 ]) $ret [ 'dirname' ]= $m [ 1 ];
if( $m [ 2 ]) $ret [ 'basename' ]= $m [ 2 ];
if( $m [ 5 ]) $ret [ 'extension' ]= $m [ 5 ];
if( $m [ 3 ]) $ret [ 'filename' ]= $m [ 3 ];
return $ret ;
>
?>
Note that this function seems to just perform string operations, and will work even on a non-existent path, e.g.
print_r ( pathinfo ( '/no/where/file.txt' ));
?>
which will output:
Array
(
[dirname] => /no/where
[basename] => file.txt
[extension] => txt
[filename] => file
)
If a file has more than one 'file extension' (seperated by periods), the last one will be returned.
For example:
$pathinfo = pathinfo ( '/dir/test.tar.gz' );
echo 'Extension: ' . $pathinfo [ 'extension' ];
?>
will produce:
Extension: gz
Checked with version 5.5.12:
It works fine with filenames with utf-8 characters, pathinfo will strip them away:
print_r ( pathinfo ( "/mnt/files/飛兒樂團光茫.mp3" ));
?>
.. will display:
Array
(
[dirname] => /mnt/files
[basename] => 飛兒樂團光茫.mp3
[extension] => mp3
[filename] => 飛兒樂團光茫
)
Here is a simple function that gets the extension of a file. Simply using PATHINFO_EXTENSION will yield incorrect results if the path contains a query string with dots in the parameter names (for eg. &x.1=2&y.1=5), so this function eliminates the query string first and subsequently runs PATHINFO_EXTENSION on the clean path/url.
function extension ( $path ) <
$qpos = strpos ( $path , "?" );
if ( $qpos !== false ) $path = substr ( $path , 0 , $qpos );
$extension = pathinfo ( $path , PATHINFO_EXTENSION );
//pathinfo function example
//passing single argument
echo "
" ;" ;
print_r ( pathinfo ( "/home/ramki/ramki.pdf" ));
echo "
//passing two agruments
$path =array( PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION , PATHINFO_FILENAME );
foreach ( $path as $value )
echo "
" . pathinfo ( "/home/ramki/ramki.pdf" , $value ). "" ;
?>
//output
/*
Array
(
[dirname] => /home/ramki
[basename] => ramki.pdf
[extension] => pdf
[filename] => ramki
)
/home/ramki
ramki.pdf
ramki
*/
if you call pathinfo with a filename in url-style (example.php?with=parameter), make sure you remove the given parameters before, otherwise they will be returned as part of the extension.
Note that in PHP 4 (if you're stuck using it), pathinfo only provides dirname, basename, and extension, but not filename. This function will not split a file's stem and extension for you.
If you have filename with utf-8 characters, pathinfo will strip them away:
Array
(
[dirname] => /mnt/files
[basename] => .mp3
[extension] => mp3
[filename] =>
)
If you want only the file extension, use this:
$extension = substr ( strrchr ( $filename , "." ), 1 );
?>
This is many times faster than using pathinfo() and getting the value from array.
at example from "qutechie at gmail dot com" you can only replace function 'strpos' with 'strrpos'. (strrpos — Find position of last occurrence of a char in a string)
It's simple. For example:
function filePath ( $filePath )
$fileParts = pathinfo ( $filePath );
if(!isset( $fileParts [ 'filename' ]))
$filePath = filePath ( '/www/htdocs/index.html' );
print_r ( $filePath );
?>
Output will be:
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
any type of url parse_url can handle this will get the extension of
pathinfo(parse_url('URL GOES HERE',PHP_URL_PATH),PATHINFO_EXTENSION)
pathinfo will return null if 0 or null is specified for the option argument.
So you'll need to define it's value manually if the option field is omitted, to provide the default functionality.
public function getFileInfo ( $source = null , $option = null ) if(! $option ) //1 + 2 + 4
$option = PATHINFO_DIRNAME + PATHINFO_BASENAME + PATHINFO_EXTENSION ;
if( defined ( 'PATHINFO_FILENAME' ))
$option += PATHINFO_FILENAME ; //8
>
return pathinfo ( $source , $option );
>
$obj -> getFileInfo ( "/test/file/someFile.txt" );
?>
A little compat for < 5.2
function pathinfo_filename ( $file ) < //file.name.ext, returns file.name
if ( defined ( 'PATHINFO_FILENAME' )) return pathinfo ( $file , PATHINFO_FILENAME );
if ( strstr ( $file , '.' )) return substr ( $file , 0 , strrpos ( $file , '.' ));
>
Here's a neat wee function to grab the relative path to root (especially useful if you're using mock-directories to pass variables into scripts with mod_rewrite). The function simply iterates through every occurence of "/" within the REQUEST_URI environment variable, appending "../" to the output for every instance:
function path_to_root ( $path )
$pathinfo = pathinfo ( $path );
$deep = substr_count ( $pathinfo [ dirname ], "/" );
It's worth nothing that pathinfo returns foo/index.php for the directory when dealing with URLs like foo/index.php/bar
When you need to get the file extension to upload a file with a
// $_FILES['archivo'] receives the file (named 'archivo'), ['name'] gets the file name.
//['tmp_name] gets the temporal name of the file (not the real name), which will be used later
//Here is the magic of pathinfo to get the file extension
$extension = pathinfo($nombre, PATHINFO_EXTENSION);
$nombre_final = $nombre. ".". $extension;
// $ruta is where you want to save the file
$ruta = "subidos/".$nombre_final;
move_uploaded_file($nombre_temporal, $ruta);
Sometimes, it's interessant to get the basename without extension.
So, I appended a new entry 'basenameWE' (Basename Without Extension) to the returned array.
// pathinfo improved
function pathinfo_im ( $path )
$tab = pathinfo ( $path );
$tab [ "basenameWE" ] = substr ( $tab [ "basename" ], 0
, strlen ( $tab [ "basename" ]) - ( strlen ( $tab [ "extension" ]) + 1 ) );
echo "
\n" ;\n" ;
print_r ( pathinfo_im ( $my_path ) );
echo "
Array
(
[dirname] => /var/www/html
[basename] => example.html
[extension] => html
[basenameWE] => example
)
Note: dirname will be "." (meaning current directory) if the path is just a file name. (PHP 5.4.34)
var_dump ( pathinfo ( 'file.ext' , PATHINFO_DIRNAME ) ); // string(1) "."
?>
A warning: this function varies depending on the platform it is being run on. For example, pathinfo('C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe') will return a different result when run through a winOS PHP platform (local development) vs. a server's UNIX-based OS. A bit like the Locale settings, but unexpected.
echo $dirname; // "storage/"
echo $basename; // "example.pdf"
echo $extension; // "pdf"
echo $filename; // "example"
Note that pathinfo($somePath, PATHINFO_EXTENSION) will return '' (empty string) for both of these paths:
That's good, but then note that pathinfo($somePath, PATHINFO_FILENAME) won't end in the dot for 'another_strange_file_ending_in_dot.' - you'll need pathinfo($somePath, PATHINFO_BASENAME) to get the original filename ending in a dot.
Hope this helps!
// your code goes here
echo phpversion ();
print_r ( pathinfo ( "/resources/img/stock/wxb001/美景.jpg" ));
输出:
5.6.4 - 2
Array
(
[ dirname ] => / resources / img / stock / wxb001
[ basename ] => 美景 . png
[ extension ] => png
[ filename ] => 美景
)
但是在php5.3.3版本中
// your code goes here
echo phpversion ();
print_r ( pathinfo ( "/resources/img/stock/wxb001/美景.jpg" ));
输出:
5.3.3
Array
(
[ dirname ] => /var/ www / www . shima . jp . net / resources / img / stock / wxb001
[ basename ] => . png
[ extension ] => png
[ filename ] =>
)
This function is not perfect, but you can use it to convert a relative path to a URL.
Please email me if you can make any improvements.
function mapURL ( $relPath ) $filePathName = realpath ( $relPath );
$filePath = realpath ( dirname ( $relPath ));
$basePath = realpath ( $_SERVER [ 'DOCUMENT_ROOT' ]);
// can not create URL for directory lower than DOCUMENT_ROOT
if ( strlen ( $basePath ) > strlen ( $filePath )) return '' ;
>
pathinfo() which can be used with UTF filenames.
function pathinfo_utf ( $path )
<
if ( strpos ( $path , '/' ) !== false ) $basename = end ( explode ( '/' , $path ));
elseif ( strpos ( $path , '\\' ) !== false ) $basename = end ( explode ( '\\' , $path ));
else return false ;
if (empty( $basename )) return false ;
$dirname = substr ( $path , 0 , strlen ( $path ) - strlen ( $basename ) - 1 );
if ( strpos ( $basename , '.' ) !== false )
<
$extension = end ( explode ( '.' , $path ));
$filename = substr ( $basename , 0 , strlen ( $basename ) - strlen ( $extension ) - 1 );
>
else
<
$extension = '' ;
$filename = $basename ;
>
return array
(
'dirname' => $dirname ,
'basename' => $basename ,
'extension' => $extension ,
'filename' => $filename
);
>
?>
Further to my previous post.
This affects servers that run PHP as a cgi module
If you have your own server:
You can use the AcceptPathInfo directive to force the core handler to accept requests with PATH_INFO and thereby restore the ability to use PATH_INFO in server-side includes.
about the path, there are one thing you should note :
On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/). (this explain is from basename() function part https://www.php.net/manual/en/function.basename.php)
example:
$path = "http://www.test.com/a\b\c\filename.pdf" ;
echo pathinfo ( $pdfUrl , PATHINFO_BASENAME ); //get basename
//output
//on window: result is filename.pdf
//on Linux: result is a\b\c\filename.pdf (that is may not your expect)
//so in order to get same result in different system. i will do below first.
$path = str_replace ( $path , '\\' , '/' ); //convert '\' to '/'
?>
For a good example of how platform independent this function is have a look at the different return values that Lostindream and I experienced. Mine is above and Lostindream's is below:
Array
(
[dirname] => /www/psychicblast/images/1
[basename] => my three girlfriends.jpg
[extension] => jpg
)
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
z
If I have a file named my.zip , this function returns .zip .
I want to do the reverse, I want the function to return my without the extension.
The file is just a string in a variable.
Смотрите также
- dirname() - Возвращает имя родительского каталога из указанного пути
- basename() - Возвращает последний компонент имени из указанного пути
- parse_url() - Разбирает URL и возвращает его компоненты
- realpath() - Возвращает канонизированный абсолютный путь к файлу
Читайте также: