MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

basename

(PHP 3, PHP 4, PHP 5)

basename --  Devuelve la parte del path correspondiente al nombre del archivo

Descripción

string basename ( string path [, string sufijo] )

Dada una cadena que contiene el path de un archivo, esta función devuelve el nombre base del archivo. Si el nombre del archivo termina con sufijo, este también será cortado del nombre del archivo.

En Windows, tanto la barra (/) como la barra inversa (\) pueden usarse como caracter separador en el path. En otros entornos, se usa la barra directa (/).

Ejemplo 1. Ejemplo de basename()

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

Nota: El parámetro sufijo fue agregado en PHP 4.1.0.

Ver también: dirname().



add a note add a note User Contributed Notes
basename
lazy lester
17-Feb-2006 04:19
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.

For instance if the path is like this:
http://www.ex.com/getdat.php?dep=n/a&title=boss

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

In such a case, use:

<php
$path_with_query="http://www.ex.com/getdat.php?dep=n/a&title=boss";
$path=explode("?",$path_with_query);
$filename=basename($path[0]);
$query=$path[1];
?>
support at rebootconcepts dot com
17-Feb-2006 11:55
works on windows and linux, faster/easier than amitabh's...

<?php
$basename
= preg_replace( '/^.+[\\\\\\/]/', '', $filename );

// Optional; change any non letter, hyphen, or period to an underscore.
$sterile_filename = preg_replace( "/[^\w\.-]+/", "_", $basename );
?>
poniestail at gmail dot com
04-Jan-2006 04:18
examples from "icewind" and "basname" seem highly overdone... not to mention example from "basename" is exactly the same as one from "icewind"...

possibly a more logical approach?
<?
  
//possible URL = http://domain.com/path/to/file.php?var=foo
  
$filename = substr( $_SERVER["SCRIPT_NAME"], 1 ); //substr( ) used for optional removal of initial "/"
  
$query = $_SERVER["QUERY_STRING"];
?>

to see the entire $_SERVER variable try this:
<?
  
echo "<pre>
     "
.print_r( $_SERVER, true )."
     </pre>
   "
;
?>
15-Nov-2005 04:57
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.
icewind
02-Nov-2005 12:44
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").
www.turigeza.com
24-Oct-2005 12:47
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!
crash at subsection dot org dot uk
22-Sep-2005 12:38
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
tomboshoven at gmail dot com
05-Sep-2005 06:53
basename() also works with urls, eg:

basename('http://www.google.com/intl/en/images/logo.gif');

will return 'logo.gif'.
b_r_i_a__n at locallinux dot com
22-Aug-2005 05:47
I was looking for a way to get only the filename whether or not I had received the full path to it from the user.  I came up with a much simpler (and probably more robust) method by using the power of basename in reverse:

$infile = "/usr/bin/php";
$filename = stristr ($infile,basename ($infile));

This even works on those _wacky_ filenames like "/usr/lib/libnetsnmp.so.5.0.9" which are not factored when exploding the full path and taking out only the last segment after "."
pvollma at pcvsoftware dot net
14-Jul-2005 09:28
Note that in my example below, I used the stripslashes function on the target string first because I was dealing with the POST array $_FILES. When creating this array, PHP will add slashes to any slashes it finds in the string, so these must be stripped out first before processing the file path. Then again, the only reason I can think of that basename() would fail is when dealing with Windows paths on a *nix server -- and the file upload via POST is the only situation I can think of that would require this. Obviously, if you are not dealing with these additional slashes, invoking stripslashes() first would remove the very separators you need extract the file name from the full path.
amitabh at NOSPAM dot saysnetsoft dot com
14-Jul-2005 01:55
The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
<?php
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);
       }
}
?>
pvollma at pcvsoftware dot net
13-Jul-2005 11:43
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):

<?php
$filen
= stripslashes($_FILES['userfile']['name']);
$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.
KOmaSHOOTER at gmx dot de
30-Jan-2005 06:18
if you want the name of the parent directory
<?php
$_parenDir_path
= join(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1),"/").'/'; // returns the full path to the parent dir
$_parenDir basename ($_parenDir_path,"/"); // returns only the name of the parent dir
// or
$_parenDir2 = array_pop(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1)); // returns also only the name of the parent dir
echo('$_parenDir_path  = '.$_parenDir_path.'<br>');
echo(
'$_parenDir  = '.$_parenDir.'<br>');
echo(
'$_parenDir2  = '.$_parenDir2.'<br>');
?>
KOmaSHOOTER at gmx dot de
29-Jan-2005 04:24
If you want the current path where youre file is and not the full path then use this :)

<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));   
// retuns the name of current used directory
?>

Example:

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

<?php
echo('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');   
// returns: /temp/2005/january
?>

<?php
echo('file = '.basename ($PHP_SELF,".php"));   
// returns: t1
?>

if you combine these two you get this
<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));   
// returns: january
?>

And for the full path use this
<?php
echo(' PHP_SELF <br>'.$_SERVER['PHP_SELF'].'<br><br>');
// returns: /temp/2005/january/t1.php   
?>
antrik at users dot sf dot net
15-Nov-2004 10:40
When using basename() on a path to a directory ('/bar/foo/'), the last path component ('foo') is returned, instead of the empty string one would expect. (Both PHP 4.1.2 and 4.3.8 on GNU/Linux.) No idea whether this is considered a bug or a feature -- I found it extremely annoying. Had to work around using: <?php $file=substr($path, -1)=='/'?'':basename($path) ?> Watch out!
osanim at cidlisuis dot org
17-Apr-2004 11:12
If you want know the real directory of the include file, you have to writte:

<?php
dirname
(__FILE__)
?>
KOmaSHOOTER at gmx dot de
28-Nov-2003 02:33
Exmaple for exploding ;) the filename to an array

<?php
echo(basename ($PHP_SELF)."<br>");  // returnes filename.php
$file = basename ($PHP_SELF);
$file = explode(".",$file);
print_r($file);    // returnes Array ( [0] => filename [1] => php )
echo("<br>");
$filename = basename(strval($file[0]),$file[1]);
echo(
$filename."<br>");  // returnes  filename
echo(basename ($PHP_SELF,".php")."<br>");  // returnes  filename
echo("<br>");
echo(
"<br>");
//show_source(basename ($PHP_SELF,".php").".php")
show_source($file[0].".".$file[1])
?>
giovanni at giacobbi dot net
08-Nov-2003 07:52
No comments here seems to take care about UNIX system files, which typically start with a dot, but they are not "extensions-only".
The following function should work with every file path. If not, please let me know at my email address.

<?php

function remove_ext($str) {
 
$noext = preg_replace('/(.+)\..*$/', '$1', $str);
  print
"input: $str\n";
  print
"output: $noext\n\n";
}

remove_ext("/home/joh.nny/test.php");
remove_ext("home/johnny/test.php");
remove_ext("weirdfile.");
remove_ext(".hiddenfile");
remove_ext("../johnny.conf");
daijoubu_NOSP at M_videotron dot ca
15-Oct-2003 10:22
An faster alternative to:

<?php
array_pop
(explode('.', $fpath));
?>

would be:

<?php
substr
($fpath, strrpos($fpath, '.')); // returns the dot
?>

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

<?php
substr
($fpath, strrpos($fpath, '.') + 1); // returns the ext only
?>
travis dot kroh at ndsu dot nodak dot edu
19-May-2003 02:12
<?php
$foo
="/path/to/file.ext";
echo
$foo."<br />";
$bar=$foo;
echo
basename($bar,".ext")."<br />";
echo
$foo."<br />";
echo
$bar."<br />";
?>

Will display:
/path/to/file.ext
file
/path/to/file
/path/to/file

Which is probably not expected behavior, as
it returns one thing, changes the variable
to produce something else, and also modifies
BOTH variables in memory.

To avoid this, use:
basename(strval($bar),".ext")
Richard at Lyders dot Net
01-Apr-2003 01:53
you can also make use of the basename() function's second parameter:

<?PHP
$fpath
= "/blah/file.name.has.lots.of.dots.ext";
$fext  = array_pop(explode('.', $fpath));
$fname = basename($fpath, '.'.$fext);

print
"fpath: $fpath\n<br>";
print
"fext: $fext\n<br>";
print
"fname: $fname\n<br>";
?>

Citas célebres

¿Alguno de los presentes tiene poderes de telekinsia? Que levante mi mano.

Emo Philips
Cómico estadounidense
(n. 1956)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_040.jpg
Contenidos Web

Chiste de... Médicos
Mitomanía

En la consulta del psicólogo:

- Dígame, en su familia ¿hay casos de mitomanía?

- Pues sí, doctor: mi marido se cree el cabeza de familia.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_036.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0227.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid fallera mayor campus party alcacer feria valencia fernando alonso loterias dinero inversiones violencia de genero makro empresas cartera soledad tolerancia metro valencia gobierno de españa violencia de genero UIMP navidad