Переменной присвоить имя файла php

basename

При передаче строки с путём к файлу или каталогу, данная функция вернёт последний компонент имени из данного пути.

Замечание:

basename() наивно оперирует исключительно исходной строкой и не учитывает реальную файловую систему или компоненты пути типа » .. «.

basename() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() . Если path содержит символы, недопустимые для текущей локали, поведение basename() не определено.

Список параметров

На платформах Windows в качестве разделителей имён директорий используются оба слеша (прямой / и обратный \ ). В других операционных системах разделителем служит прямой слеш ( / ).

Если компонент имени заканчивается на suffix , то он также будет отброшен.

Возвращаемые значения

Возвращает базовое имя указанного пути path .

Примеры

Пример #1 Пример использования функции basename()

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 ( «/» );
?>

Результат выполнения данного примера:

1) sudoers 2) sudoers.d 3) passwd 4) etc 5) . 6)

Смотрите также

  • dirname() — Возвращает имя родительского каталога из указанного пути
  • pathinfo() — Возвращает информацию о пути к файлу

User Contributed Notes 31 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.

Example:
$file = «path/to/file.xml#xpointer(/Texture)» ;
echo basename ( $file , «.xml#xpointer(/Texture)» );
?>

Result in PHP4: file
Result in PHP5: Texture)

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

Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

$info = pathinfo ( $file );
$file_name = basename ( $file , ‘.’ . $info [ ‘extension’ ]);

echo $file_name ; // outputs ‘image’

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

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.

Читайте также:  Php получить исходный код

Then both the php basename() function, and also
the $_SERVER[QUERY_STRING] variables get confused.

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:

www dir: domain.com/temp/2005/january/t1.php

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

One line alternative for unicode filenames:

preg_replace ( ‘#.*?([^’ . DIRECTORY_SEPARATOR . ‘]*)’ . DIRECTORY_SEPARATOR . ‘*$#’ , ‘$1’ , $path );

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

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

Additional note to Anonymous’s mb_basename() solution: get rid of trailing slashes/backslashes!

Читайте также:  String format java with array

function mb_basename ( $path ) if ( preg_match ( ‘@^.*[\\\\/]([^\\\\/]+)([\\\\/]+)?$@s’ , $path , $matches )) return $matches [ 1 ];
> else if ( preg_match ( ‘@^([^\\\\/]+)([\\\\/]+)?$@s’ , $path , $matches )) return $matches [ 1 ];
>
return » ;
>

echo mb_basename ( «/etc//» ); # «etc»
?>

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

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

@softontherocks at gmail dot com
> If you want to get the extension of a file, I posted a function in
> http://softontherocks.blogspot.com/2013/07/obtener-la-extension-de-un-fichero-con.html
>
> The function is:
>
> function getExtension($file) > $pos = strrpos($file, ‘.’);
> return substr($file, $pos+1);
> >

This is much simpler:
$ext = strrchr( $filename, ‘.’ );

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.

to get the base url of my website

function url() $base_url = isset($_SERVER[‘HTTPS’]) && strtolower($_SERVER[‘HTTPS’]) !== ‘off’ ? ‘https’ : ‘http’;
$base_url .= ‘://’. $_SERVER[‘HTTP_HOST’];
$base_url .= str_replace(basename($_SERVER[‘SCRIPT_NAME’]), », $_SERVER[‘SCRIPT_NAME’]);
return $base_url;
>

@ 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

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

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:

$url = ‘http://example.com/url?with=query_string’ ;
basename ( $url ); // url?with=query_string
$url = $url . ‘&filename_for_basename=/desired_filename.ext’ ;
basename ( $url ); // desired_filename.ext
?>

Note: you can use the filename from the HTTP header (if present) to get the file with it’s original filename.

Читайте также:  Delete php my admin

Because of filename() gets «file.php?var=foo», i use explode in addition to basename like here:

$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

echo basename(‘somewhere.com/filename.php?id=2’, ‘.php’);
will output
filename.php?id=2

which is not the filename in case you expect!

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

My opinion is, remove the $suffix first, and then apply splitting the core basename ( PHP 4 ):

/*
* From stephane.fidanza@gmail.com:
*
* PHP 4: $suffix is removed first, and then the core basename is applied.
* PHP 5: $suffix is removed after applying the core basename.
*
* (c) Paulus Gandung Prakosa (rvn.plvhx@gmail.com)
*/
if ( !function_exists(‘php4_backward_compat_basename’) )
function php4_backward_compat_basename($path, $suffix = »)
if ( $suffix !== » ) $fixed_path = substr($path, 0, strlen($path) — strlen($suffix));
$fixed_basename = explode(‘/’, $fixed_path);
>

return ( isset($fixed_basename) ? array_pop($fixed_basename) : array_pop(explode(‘/’, $path)) );
>
>

array_pop ( explode ( ‘.’ , $fpath ));
?>

would be:

substr ( $fpath , strrpos ( $fpath , ‘.’ )); // returns the dot
?>

If you don’t want the dot, simply adds 1 to the position

substr ( $fpath , strrpos ( $fpath , ‘.’ ) + 1 ); // returns the ext only
?>

the best way to get the filename from url is here
// url : http://php.net/manual/add-note.php

defined ( ‘baseUrlFileName’ ) or define ( ‘baseUrlFileName’ ,
explode ( ‘.’ , explode ( ‘/’ , $_SERVER [ ‘PHP_SELF’ ])[ 3 ])[ 0 ]);

echo baseUrlFileName ; // result 1

Источник

Запись в файл, имя файла переменная

Подскажите как правильно подставить переменную в имя файла на создание и записи в файл. Нужно создать файл $Name.html
Делаю:

$fw = fopen("C:\Users\Public\Apache\htdocs\Charts\MyCharts\my_amCharts\Names\$Name.html", "w");
$Name1 = $Name.".html"; $fw = fopen("C:\Users\Public\Apache\htdocs\Charts\MyCharts\my_amCharts\Names\$Name1", "w");

И еще пару способов , ничего не получается, файлы не создаются.
Создаются если явно прописать, без переменной:

$fw = fopen("C:\Users\Public\Apache\htdocs\Charts\MyCharts\my_amCharts\Names\Name.html", "w");

Переменная как имя select-a
Добрый день Товарищи! Подскажите как получить значение select если они создаются динамически и имя.

Запись в файл, имя файла
Столкнулся с такой проблемой, как сделать, чтобы программа автоматично давала имя самому текстовому.

Запись в файл путь и имя файла
Имеется такой код string path = @"E:\MyTest.txt"; if (!File.Exists(path)) .

Создание файла имя которого — переменная
Как мне известно чтобы создать файл функцией 3Сh, нужно в регистр DX записать переменную такого.

переменную попробуйте в <> взять т.е. .html

Добавлено через 15 минут
ps надо заэкранировать слэши

fopen("C:\\Users\\Public\\Apache\\htdocs\\Charts\\MyCharts\\my_amCharts\\Names\\$Name.html", "w");
 $t = 'w'; $this_value = 'ff'; $t = '$this_value.html'; echo $t; ?>

Источник

Оцените статью