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

file_exists

(PHP 3, PHP 4, PHP 5)

file_exists -- Verifica si un archivo o directorio existe

Descripción

bool file_exists ( string nombre_archivo )

Devuelve TRUE si el archivo o directorio especificado por nombre_archivo existe; o FALSE de lo contrario.

En windows, use //nombre_computadora/recurso/nombre_archivo o \\nombre_computadora\recurso\nombre_archivo para revisar archivos en recursos compartidos de red.

Ejemplo 1. Probar si un archivo existe

<?php
$nombre_archivo
= '/ruta/hacia/foo.txt';

if (
file_exists($nombre_archivo)) {
   echo
"El archivo $nombre_archivo existe";
} else {
   echo
"El archivo $nombre_archivo no existe";
}
?>

Nota: Los resultados de esta función son guardados. Consultar clearstatcache() para más detalles.

Sugerencia: A partir de PHP 5.0.0, esta funcion tambien puede usarse con algunas URL como nombre de fichero. Consultar Apéndice M, para obtener una lista con soporte para la funcionalidad stat().

Aviso

Esta función devuelve FALSE para archivos inaccesibles debido a restricciones del modo seguro. Sin embargo estos archivo aun pueden ser incluidos si se encuentran en safe_mode_include_dir.

Vea también is_readable(), is_writable(), is_file() y file().



add a note add a note User Contributed Notes
file_exists
leibwaechter at web dot de
16-Aug-2006 02:32
Here is an easy function to check for remote files or an existing URL:
 
<?php
function url_exists($url)
{
 
$handle = @fopen($url, "r");
 if (
$handle === false)
  return
false;
 
fclose($handle);
 return
true;
}
?>
jana dot vasseru at gmail dot com
05-Aug-2006 06:38
if it happens to you that file_exists($file_name) returns true even if the file does not exist (and unlink gives warning 'permission denied' even if the file exists and is accessible) check if you don't have an extra space at the end of the filename - does wonders sometimes.
stefan at horn dot nl
11-Jul-2006 11:30
file_exists and safe_mode

file_exists under safe_mode works (I work with for php 4) doesn't work when owner of the dir where the file stands differs from the php-owner.

e.g. file_exists in this dir will give FALSE nevertheless the file exists

rights          owner  dir
drwxr-xr-x    apache  images

change the owner of the dir to the phpowner and file_exists works.

I spent too much time to discover. Hope it will spare a lot of your time.

Stefan
sirarthur at sirarthur dot info
10-May-2006 12:04
The following code will rename an uploaded image to a MD5 hash with a rand number added of its name and check wheter a file with same hash already exists or not:

<?php
$file
= $HTTP_POST_FILES['file'];
$image=new Image($imgfld,$file);
if(
$image->FType != null){
if (
$image->FType=="image/gif") {
$ext = ".gif";
}else{
$ext = ".jpg";
}
 
$nfile = md5($image->Name . rand());
while(
file_exists($imgfld . $nfile . $ext) == true){
 
$nfile = md5($image->Name . rand());
}
 
$image->ResizedWidth = $imggrx;
 
$image->ResizedHeight = $imggry;
 
$image->Resample($nfile);
?>

It uses an image class found at phpclasses.org
pilotdoofy at gmail dot com
22-Apr-2006 01:35
I wrote a very simple function that allows you to search a folder for a file name with a regular expression. It can handle both PREG and EREG regexps and can accept different case sensitivities for EREG regexps.

function regExpFile($regExp, $dir, $regType='P', $case='') {
# Two parameters accepted by $regType are E for ereg* functions
# and P for preg* functions
$func = ( $regType == 'P' ) ? 'preg_match' : 'ereg' . $case;

# Note, technically anything other than P will use ereg* functions;
# however, you can specify whether to use ereg or eregi by
# declaring $case as "i" to use eregi rather than ereg

$open = opendir($dir);
while( ($file = readdir($open)) !== false ) {
if ( $func($regExp, $file) ) {
return true;
}
} // End while
return false;
} // End function

Basically if you supply anything but "P" for $regType it will assume you're using EREG regexps. The case should only be blank or "i".
hiro at arkusa dot com
07-Feb-2006 01:23
As of php 5.0.4, many (if not all) php file manipulation functions fail if a file's size is no smaller than 2GB (i.e. 2^31) on the x86 platforms. Even file_exists() fails (always returns FALSE). This puzzled me when I was writing a video file manipulation application.

A simple alternative is like:

function file_exists_2gb($filename) {
   system("test -f $filename", $rval);
   return ($rval == 0);
}
07-Jan-2006 01:08
I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try 'flower.jpg' and it exists, then it tries 'flower[1].jpg' and if that one exists it tries 'flower[2].jpg' and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.

<?php
function imageExists($image,$dir) {

  
$i=1; $probeer=$image;

   while(
file_exists($dir.$probeer)) {
      
$punt=strrpos($image,".");
       if(
substr($image,($punt-3),1)!==("[") && substr($image,($punt-1),1)!==("]")) {
          
$probeer=substr($image,0,$punt)."[".$i."]".
          
substr($image,($punt),strlen($image)-$punt);
       } else {
          
$probeer=substr($image,0,($punt-3))."[".$i."]".
          
substr($image,($punt),strlen($image)-$punt);
       }
      
$i++;
   }
   return
$probeer;
}
?>
Fabrizio (staff at bibivu dot com)
21-Dec-2005 06:11
here a function to check if a certain URL exist:
<?php
  
function url_exists($url) {
      
$a_url = parse_url($url);
       if (!isset(
$a_url['port'])) $a_url['port'] = 80;
      
$errno = 0;
      
$errstr = '';
      
$timeout = 30;
       if(isset(
$a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
          
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
           if (!
$fid) return false;
          
$page = isset($a_url['path'])  ?$a_url['path']:'';
          
$page .= isset($a_url['query'])?'?'.$a_url['query']:'';
          
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
          
$head = fread($fid, 4096);
          
fclose($fid);
           return
preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
       } else {
           return
false;
       }
   }
?>

in my CMS, I am using it with those lines:
<?php
      
if(!isset($this->f_exist[$image]['exist']))
           if(
strtolower(substr($fimage,0,4)) == 'http' || strtolower(substr($fimage,0,4)) == 'www.'){
               if(
strtolower(substr($image,0,4)) == 'www.'){
                  
$fimage = 'http://'.$fimage;
                  
$image = 'http://'.$image;
               }
              
$this->f_exist[$image]['exist'] = $this->url_exists($fimage); //for now
          
} else {
              
$this->f_exist[$image]['exist'] = ($fimage!='' && file_exists($fimage) && is_file($fimage) && is_readable($fimage) && filesize($fimage)>0);
           }
       }
?>
flobee
13-Dec-2005 04:24
file_exists overwrites the last access (atime) !
try:
if (@fclose(@fopen( $file, "r"))) {
                     // true;
                 } else {
                     // false;
                 }
to check if important for you
ihoss dot com at gmail dot com
19-Oct-2005 07:37
The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
  $img
= "images/".$_FILES['bilde']['name'];
 
$t=0;
  while(
file_exists($img)){
  
$img = "images/".$_FILES['bilde']['name'];
  
$img=substr($img,0,strpos($img,"."))."_$t".strstr($img,".");
  
$t++;
  }
 
move_uploaded_file($_FILES['bilde']['tmp_name'], $img);
?>
phenbach at phenbach dot com
19-Sep-2005 03:37
I recently had an issue with PLESK and copying file to other directories with the move_uploaded file function.

This would work on every linux server except plesk servers. I could figure it out and have yet to find out.  I had to create a work a round and decided to use the exec() function.

As noted above the file_exist() function must need to wait for some time and I found the looking function a waste of resouces and didn't work for me anyway. So this is what I came up with.

function cp($source,$destination){

$cmd="cp -u ".$source ." ".$destination; //create the command string to copy with the update option
exec($cmd); //exec command
$cmd_test="ls -la ".$destination; //list file
exec($cmd_test,$out);
//If the file is present it $out[0] key will contain the file info.
//if it is not present it will be null
if (isset($out[0])){
     return true;
}else{
     return false;
}
   }
davidc at php dot net
13-Sep-2005 01:05
Also while using the file_exists file, please make sure you do not start using stuff like,

<?php

if(file_exists($_GET['file'] . '.php')) {
   include(
$_GET['file'] . '.php';
}

?>

you could use something like this..

<?php
   $inrep
= "./";
  
$extfichier = ".php";
  
$page = $inrep.basename(strval($_REQUEST["page"]),$extfichier).extfichier;
   if(
file_exist($page)) {
       include(
$page);
   }
?>

or even hardcode it.

  So since pretty much all commercial server(s) have url_fopen on.. you can imagine that file_exists($_GET['file']. '.php')
is rather .. unsecure :)

-David Coallier
tma at 2p dot cz
24-Aug-2005 01:47
If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately.  Iy seems that a short timeout may be required.

<?
   $file
= 'file.tmp';
   if (
$h = popen("start \"bla\" touch $file", "r")) {
    
pclose($h);
  
// now I would like know if a file was created
   // note: usleep not supported
    
$start = gettimeofday(); 
     while (!
file_exists(trim($file, " '\""))) {
      
$stop = gettimeofday();
       if (
1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break;  // wait a moment
    
}

     if (
file_exists($file))  // now should be reliable
?>
09-Aug-2005 07:20
That is true feshi. But, if you have your server configured correctly, those access logs will only be accessible by an admin or the root account. The webuser account that runs the php script will be unable to start reading from that file. That's the easiest fix.
feshi
04-Aug-2005 03:34
this code looks inocent

<?php
$filename
=$_REQUEST["var"];
$filename .= ".data";
file_exist($filename){
  include(
$filename);
}
?>

but if you pass something like script.php?var=test%00asbs
it should really can do bad things like including accesslog files if you replace "test" with something like "../logs/accesslog"
joe dot knall at gmx dot net
15-Mar-2005 03:59
concerning file_exists and safe_mode:
if safe_mode=ON and $file (in safe_mode_include_dir) is not owned by the user who executes file_exists($file), file_exists returns FALSE but still $file can be included;
I could handle this by setting safe_mode_gid=On and appropriate group-ownership
07-Mar-2005 02:00
Nathaniel, you should read the manual carefuly next time prior to posting anything here, as all you indicated is the fact you missed the idea of the include_path. To remind - include_path is for some functions only, mainly intended for include and require to simpify include/require operations (kinda way the #include works). It is NOT for any filesystem function, which would be damn annoying than helpful, which is quite understandable and obvious.
andrewNOSPAMPLEASE at abcd dot NOSPAMERSca
11-Feb-2005 05:29
file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.
Nathaniel
08-Feb-2005 09:08
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.

It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.

Thus:

<?PHP
// .htaccess php_value include_path '/home/user/public_html/';

// includes lies in /home/user/public_html/includes/

//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
     include(
'includes/config.php');
}

//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
   include(
'includes/config.php');
}
?>

Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
ceo at l-i-e dot com
02-Dec-2004 03:44
Prior to 4.3.2, and 4.3.3 with open_basedir, this function generated an error/warning message when the file/directory in question did not exist.
aidan at php dot net
10-Apr-2004 09:46
If you'd like to check if a file exists anywhere your include path, have a look at this function:

http://aidan.dotgeek.org/lib/?file=function.file_exists_incpath.php
alex at raynor nospam dot ru
05-Apr-2004 08:16
If you use open_basedir in php.ini and use file_exists for file outside open_basedir path, you will not be warned at log and file_exists returns false even if file really exists.
11-Feb-2004 06:32
On nix systems file_exists will report a link that doesn't point to a valid file as non-existant, ie: the link itself exists but the file it points to does not.  Using is_link will report true whether the link points to a valid file or not.

Citas célebres

Nadie es peor que uno mismo para conocer lo peor de sí mismo.

Thomas Fuller
Clérigo y escritor inglés
(1609-1661)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_029.jpg
Contenidos Web

Chiste de... Médicos
El huevo rojo

Un tío va al medico y dice:

- Doctor, que yo tengo un problema, que cuando hago el amor con mi mujer se me pone un huevo rojo.

- Pero eso es increíble, ¡eso lo tengo que ver!
Total que el tío va con su mujer empiezan a darle delante del médico y efectivamente un huevo se le pone rojo fosforito.

- ¿Es usted camionero?

- Sí, ¿cómo lo sabe?

- Entonces es la reserva.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_063.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_0295.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

Warning: array_rand(): First argument has to be an array in /var/www/html/contenidos/efemerides.php on line 14
Sucedió el...

31 de agosto de

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