Php не видит файл
On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.
Return Values
Returns true if the file or directory specified by filename exists; false otherwise.
Note:
This function will return false for symlinks pointing to non-existing files.
Note:
The check is done using the real UID/GID instead of the effective one.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
User Contributed Notes 31 notes
Note: The results of this function are cached. See clearstatcache() for more details.
That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;)
I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two. file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.
Note that realpath() will return false if the file doesn't exist. So if you're going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath() instead of calling file_exists() first
In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers. You can still use get_headers if you don't have the option of using CURL..
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:
You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on "Open a session as" Create a new user that has enough permissions and also be sure that target share has the proper permissions.
Hope this save some hours of research to anyone.
file_exists() does NOT search the php include_path for your file, so don't use it before trying to include or require.
@$result = include $filename;
Yes, include does return false when the file can't be found, but it does also generate a warning. That's why you need the @. Don't try to get around the warning issue by using file_exists(). That will leave you scratching your head until you figure out or stumble across the fact that file_exists() DOESN'T SEARCH THE PHP INCLUDE_PATH.
returns always "missing", even for an existing URL.
I found that in the same situation the file() function can read the remote file, so I changed my routine in
This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.
function url_exists ( $url ) $url = str_replace ( "http://" , "" , $url );
if ( strstr ( $url , "/" )) $url = explode ( "/" , $url , 2 );
$url [ 1 ] = "/" . $url [ 1 ];
> else $url = array( $url , "/" );
>
$fh = fsockopen ( $url [ 0 ], 80 );
if ( $fh ) fputs ( $fh , "GET " . $url [ 1 ]. " HTTP/1.1\nHost:" . $url [ 0 ]. "\n\n" );
if ( fread ( $fh , 22 ) == "HTTP/1.1 404 Not Found" ) < return FALSE ; >
else
If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree. PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).
This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.
When using file_exists, seems you cannot do:
foreach ( $possibles as $poss )
<
if ( file_exists ( SITE_RANGE_IMAGE_PATH . $this -> range_id . '/ ' . $poss . '.jpg' ) )
<
// exists
>
else
<
// not found
>
>
?>
so you must do:
foreach ( $possibles as $poss )
<
$img = SITE_RANGE_IMAGE_PATH . $this -> range_id . '/ ' . $poss . '.jpg'
if ( file_exists ( $img ) )
<
// exists
>
else
<
// not found
>
>
?>
Then things will work fine.
This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3
Not sure if it is down to the concatenation or the fact theres a constant in there, i'm about to run away and test just that.
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.
function imageExists ( $image , $dir )
$i = 1 ; $probeer = $image ;
I was having problems with the file_exists when using urls, so I made this function:
function file_exists_2 ( $filePath )
return ( $ch = curl_init ( $filePath )) ? @ curl_close ( $ch ) || true : false ;
>
?>
Cheers!
this code here is in case you want to check if a file exists in another server:
function fileExists ( $path ) return (@ fopen ( $path , "r" )== true );
>
?>
unfortunately the file_exists can't reach remote servers, so I used the fopen function.
Here is a simpler version of url_exists:
Note on openspecies entry (excellent btw, thanks!).
If your server cannot resolve its own DNS, use the following:
$f = preg_replace('/www\.yourserver\.(net|com)/', getenv('SERVER_ADDR'), $f);
Just before the $h = @get_headers($f); line.
Replace the extensions (net|com|. ) in the regexp expression as appropriate.
Wordpress always prepends the full URL to any file it stores in its database so, as noted elsewhere, file_exists() can't find the file since it uses the 'document root', not the URL. An easy way out of this is to use:
file_exists (str_replace (home_url(), $_SERVER['DOCUMENT_ROOT'], $file) )
to check if file $file exists. Note: As from PHP8, 'DOCUMENT_ROOT' must be enclosed within SQUARE BRACKETS, not braces as suggested by ferodano at gmail dot com
I made a bit of code that sees whether a file served via RTSP is there or not:
function rtsp_exists ( $url )
$server = parse_url ( $url , PHP_URL_HOST );
$port = "554" ;
$hdrs = "DESCRIBE " . $url . " RTSP/1.0" . "\r\n\r\n" ;
//Open connection (15s timeout)
$sh = fsockopen ( $server , $port , $err , $err_otp , 15 );
//Check connections
if(! $sh ) return false ;
//Send headers
fputs ( $sh , $hdrs );
//Receive data (1KB)
$rtds = fgets ( $sh , 1024 );
//Close socket
fclose ( $sh );
return strpos ( $rtds , "200 OK" ) > 0 ;
>
?>
NB: This function expects the full server-related pathname to work.
For example, if you run a PHP routine from within, for example, the root folder of your website and and ask:
You will get FALSE even if that file does exist off root.
You need to add
Older php (v4.x) do not work with get_headers() function. So I made this one and working.
function url_exists ( $url ) // Version 4.x supported
$handle = curl_init ( $url );
if ( false === $handle )
return false ;
>
curl_setopt ( $handle , CURLOPT_HEADER , false );
curl_setopt ( $handle , CURLOPT_FAILONERROR , true ); // this works
curl_setopt ( $handle , CURLOPT_NOBODY , true );
curl_setopt ( $handle , CURLOPT_RETURNTRANSFER , false );
$connectable = curl_exec ( $handle );
curl_close ( $handle );
return $connectable ;
>
?>
You could use document root to be on the safer side because the function does not take relative paths:
if( file_exists ( $_SERVER < 'DOCUMENT_ROOT' >. "/my_images/abc.jpg" )) <
.
>
?>
Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.
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.
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.
// .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.
file_exists() will return FALSE for broken links
$ ln -s does_not_exist my_link
$ ls -l
lrwxr-xr-x 1 user group 14 May 13 17:28 my_link -> does_not_exist
$ php -r "var_dump(file_exists('my_link'));"
bool(false)
The code can be used to t a filename that can be used to create a new filename.
function generateRandomString ( $length = 8 )
<
$string = "" ;
//character that can be used
$possible = "0123456789bcdfghjkmnpqrstvwxyz" ;
for( $i = 0 ; $i < $length ; $i ++)
<
$char = substr ( $possible , rand ( 0 , strlen ( $possible )- 1 ), 1 );
if (! strstr ( $string , $char ))
<
$string .= $char ;
>
>
function randomFile ( $folder = '' , $extension = '' )
<
$folder = trim ( $folder );
$folder = ( $folder == '' ) ? './' : $folder ;
//check if directory exist
if (! is_dir ( $folder ))
//generate a filepath
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;
//check if that filepath already exist, if it exist if generates again
//till if gets one that doesn't exist
while( file_exists ( $filepath ))
<
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;
>
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.
$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 );
?>
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):
function __autoload ( $name )
<
$path = explode ( ":" , ini_get ( 'include_path' )); //get all the possible paths to the file (preloaded with the file structure of the project)
foreach( $path as $tryThis )
<
//try each possible iteration of the file name and use the first one that comes up
// name.class.php first
$exists = file_exists ( $tryThis . '/' . $name . '.class.php' );
if ( $exists )
<
include_once( $name . '.class.php' );
return;
>
//ok that didn't work, try the other way around
$exists = file_exists ( $tryThis . '/' . 'class.' . $name . '.php' );
if ( $exists )
<
include_once( 'class.' . $name . '.php' );
return;
>
//neither did that. let's try as an inc.php
$exists = file_exists ( $tryThis . '/' . $name . '.inc.php' );
if ( $exists )
<
include_once( $name . '.inc.php' );
return;
>
>
// can't find it.
die( "Class $name could not be found!" );
>
?>
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
?>
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.
The following function is a good solution:
function file_exists_safe ( $file ) if (! $fd = fopen ( $file , 'xb' )) return true ; // the file already exists
>
fclose ( $fd ); // the file is now created, we don't need the file handler
return false ;
>
?>
The function will create a file if non-existent, following calls will fail because the file exists (in effect being a lock).
IMPORTANT: The file will remain on the disk if it was successfully created and you must clean up after you, f.ex. remove it or overwrite it. This step is purposely omitted from the function as to let scripts do calculations all the while being sure the file won't be "seized" by another process.
function create_and_lock ( $file ) if (! $fd = fopen ( $file , 'xb' )) return false ;
>
if (! flock ( $fd , LOCK_EX | LOCK_NB )) < // may fail for other reasons, LOCK_NB will prevent blocking
fclose ( $fd );
unlink ( $file ); // clean up
return false ;
>
return $fd ;
>
Return Values
Returns true if the file or directory specified by filename exists; false otherwise.
Note:
This function will return false for symlinks pointing to non-existing files.
Note:
The check is done using the real UID/GID instead of the effective one.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Примеры
if ( file_exists ( $filename )) echo "Файл $filename существует" ;
> else echo "Файл $filename не существует" ;
>
?>
Решение
Мне показалось, что существует проблема с объявлением $uploadedFile с помощью basename($_FILES['file_name']['name']."test") ~ это приведет к тому, что файл не будет иметь расширения при сохранении.
isAllowedFile можно немного упростить с помощью pathinfo чтобы получить расширение файла, а не сложное использование substr
Структура каталога на вашем веб-сервере неизвестна, но если вы предполагаете, что корневой каталог документа c:/wwwroot/html/public тогда вы обычно загружаете файлы за пределами этого в непубличный каталог, такой как c:/wwwroot/html/uploads ~ с учетом этого использованный каталог будет c:/wwwroot/html/uploads/
Загрузить форму
example.php
Я попробовал выше демо — я пропустил $ от uploadedFile но когда это было исправлено, все работало нормально — обратите внимание, я использовал путь, соответствующий моему компьютеру c:/temp/fileuploads/
При попытке перейти в каталог загрузки учтите следующее:
Это находит корень сервера и перемещается вверх на один уровень, оттуда (если вы храните файлы вне корня) вы можете затем использовать getcwd() сформировать часть целевого пути
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Examples
if ( file_exists ( $filename )) echo "The file $filename exists" ;
> else echo "The file $filename does not exist" ;
>
?>
User Contributed Notes 31 notes
Note: The results of this function are cached. See clearstatcache() for more details.
That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;)
I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two. file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.
Note that realpath() will return false if the file doesn't exist. So if you're going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath() instead of calling file_exists() first
In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers. You can still use get_headers if you don't have the option of using CURL..
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:
You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on "Open a session as" Create a new user that has enough permissions and also be sure that target share has the proper permissions.
Hope this save some hours of research to anyone.
file_exists() does NOT search the php include_path for your file, so don't use it before trying to include or require.
@$result = include $filename;
Yes, include does return false when the file can't be found, but it does also generate a warning. That's why you need the @. Don't try to get around the warning issue by using file_exists(). That will leave you scratching your head until you figure out or stumble across the fact that file_exists() DOESN'T SEARCH THE PHP INCLUDE_PATH.
returns always "missing", even for an existing URL.
I found that in the same situation the file() function can read the remote file, so I changed my routine in
This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.
function url_exists ( $url ) $url = str_replace ( "http://" , "" , $url );
if ( strstr ( $url , "/" )) $url = explode ( "/" , $url , 2 );
$url [ 1 ] = "/" . $url [ 1 ];
> else $url = array( $url , "/" );
>
$fh = fsockopen ( $url [ 0 ], 80 );
if ( $fh ) fputs ( $fh , "GET " . $url [ 1 ]. " HTTP/1.1\nHost:" . $url [ 0 ]. "\n\n" );
if ( fread ( $fh , 22 ) == "HTTP/1.1 404 Not Found" ) < return FALSE ; >
else
If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree. PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).
This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.
When using file_exists, seems you cannot do:
foreach ( $possibles as $poss )
<
if ( file_exists ( SITE_RANGE_IMAGE_PATH . $this -> range_id . '/ ' . $poss . '.jpg' ) )
<
// exists
>
else
<
// not found
>
>
?>
so you must do:
foreach ( $possibles as $poss )
<
$img = SITE_RANGE_IMAGE_PATH . $this -> range_id . '/ ' . $poss . '.jpg'
if ( file_exists ( $img ) )
<
// exists
>
else
<
// not found
>
>
?>
Then things will work fine.
This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3
Not sure if it is down to the concatenation or the fact theres a constant in there, i'm about to run away and test just that.
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.
function imageExists ( $image , $dir )
$i = 1 ; $probeer = $image ;
I was having problems with the file_exists when using urls, so I made this function:
function file_exists_2 ( $filePath )
return ( $ch = curl_init ( $filePath )) ? @ curl_close ( $ch ) || true : false ;
>
?>
Cheers!
this code here is in case you want to check if a file exists in another server:
function fileExists ( $path ) return (@ fopen ( $path , "r" )== true );
>
?>
unfortunately the file_exists can't reach remote servers, so I used the fopen function.
Here is a simpler version of url_exists:
Note on openspecies entry (excellent btw, thanks!).
If your server cannot resolve its own DNS, use the following:
$f = preg_replace('/www\.yourserver\.(net|com)/', getenv('SERVER_ADDR'), $f);
Just before the $h = @get_headers($f); line.
Replace the extensions (net|com|. ) in the regexp expression as appropriate.
Wordpress always prepends the full URL to any file it stores in its database so, as noted elsewhere, file_exists() can't find the file since it uses the 'document root', not the URL. An easy way out of this is to use:
file_exists (str_replace (home_url(), $_SERVER['DOCUMENT_ROOT'], $file) )
to check if file $file exists. Note: As from PHP8, 'DOCUMENT_ROOT' must be enclosed within SQUARE BRACKETS, not braces as suggested by ferodano at gmail dot com
I made a bit of code that sees whether a file served via RTSP is there or not:
function rtsp_exists ( $url )
$server = parse_url ( $url , PHP_URL_HOST );
$port = "554" ;
$hdrs = "DESCRIBE " . $url . " RTSP/1.0" . "\r\n\r\n" ;
//Open connection (15s timeout)
$sh = fsockopen ( $server , $port , $err , $err_otp , 15 );
//Check connections
if(! $sh ) return false ;
//Send headers
fputs ( $sh , $hdrs );
//Receive data (1KB)
$rtds = fgets ( $sh , 1024 );
//Close socket
fclose ( $sh );
return strpos ( $rtds , "200 OK" ) > 0 ;
>
?>
NB: This function expects the full server-related pathname to work.
For example, if you run a PHP routine from within, for example, the root folder of your website and and ask:
You will get FALSE even if that file does exist off root.
You need to add
Older php (v4.x) do not work with get_headers() function. So I made this one and working.
function url_exists ( $url ) // Version 4.x supported
$handle = curl_init ( $url );
if ( false === $handle )
return false ;
>
curl_setopt ( $handle , CURLOPT_HEADER , false );
curl_setopt ( $handle , CURLOPT_FAILONERROR , true ); // this works
curl_setopt ( $handle , CURLOPT_NOBODY , true );
curl_setopt ( $handle , CURLOPT_RETURNTRANSFER , false );
$connectable = curl_exec ( $handle );
curl_close ( $handle );
return $connectable ;
>
?>
You could use document root to be on the safer side because the function does not take relative paths:
if( file_exists ( $_SERVER < 'DOCUMENT_ROOT' >. "/my_images/abc.jpg" )) <
.
>
?>
Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.
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.
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.
// .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.
file_exists() will return FALSE for broken links
$ ln -s does_not_exist my_link
$ ls -l
lrwxr-xr-x 1 user group 14 May 13 17:28 my_link -> does_not_exist
$ php -r "var_dump(file_exists('my_link'));"
bool(false)
The code can be used to t a filename that can be used to create a new filename.
function generateRandomString ( $length = 8 )
<
$string = "" ;
//character that can be used
$possible = "0123456789bcdfghjkmnpqrstvwxyz" ;
for( $i = 0 ; $i < $length ; $i ++)
<
$char = substr ( $possible , rand ( 0 , strlen ( $possible )- 1 ), 1 );
if (! strstr ( $string , $char ))
<
$string .= $char ;
>
>
function randomFile ( $folder = '' , $extension = '' )
<
$folder = trim ( $folder );
$folder = ( $folder == '' ) ? './' : $folder ;
//check if directory exist
if (! is_dir ( $folder ))
//generate a filepath
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;
//check if that filepath already exist, if it exist if generates again
//till if gets one that doesn't exist
while( file_exists ( $filepath ))
<
$filepath = $folder . "/" . generateRandomString ( 128 ) . $extension ;
>
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.
$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 );
?>
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):
function __autoload ( $name )
<
$path = explode ( ":" , ini_get ( 'include_path' )); //get all the possible paths to the file (preloaded with the file structure of the project)
foreach( $path as $tryThis )
<
//try each possible iteration of the file name and use the first one that comes up
// name.class.php first
$exists = file_exists ( $tryThis . '/' . $name . '.class.php' );
if ( $exists )
<
include_once( $name . '.class.php' );
return;
>
//ok that didn't work, try the other way around
$exists = file_exists ( $tryThis . '/' . 'class.' . $name . '.php' );
if ( $exists )
<
include_once( 'class.' . $name . '.php' );
return;
>
//neither did that. let's try as an inc.php
$exists = file_exists ( $tryThis . '/' . $name . '.inc.php' );
if ( $exists )
<
include_once( $name . '.inc.php' );
return;
>
>
// can't find it.
die( "Class $name could not be found!" );
>
?>
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
?>
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.
The following function is a good solution:
function file_exists_safe ( $file ) if (! $fd = fopen ( $file , 'xb' )) return true ; // the file already exists
>
fclose ( $fd ); // the file is now created, we don't need the file handler
return false ;
>
?>
The function will create a file if non-existent, following calls will fail because the file exists (in effect being a lock).
IMPORTANT: The file will remain on the disk if it was successfully created and you must clean up after you, f.ex. remove it or overwrite it. This step is purposely omitted from the function as to let scripts do calculations all the while being sure the file won't be "seized" by another process.
function create_and_lock ( $file ) if (! $fd = fopen ( $file , 'xb' )) return false ;
>
if (! flock ( $fd , LOCK_EX | LOCK_NB )) < // may fail for other reasons, LOCK_NB will prevent blocking
fclose ( $fd );
unlink ( $file ); // clean up
return false ;
>
return $fd ;
>
Репутация: 2
Всего: 20
Всем привет!
У меня небольшая проблема: мой PHP не видит некоторых расширений
При запуске любой программы - выбивает что не находит нужные ему dll'ки!
Сначала выбивал мол проблемы с iconv (ну и еще другими) я скачал php 4.3.11 со всеми расширениями и просто заменил их новыми,
Но эффекта это не дало, тоесть частично дало - некоторые он начал видеть а некоторые все равно не находит!
Библиотеки
php_curl.dll
php_domxml.dll
php_mhash.dll
php_xslt.dll
все равно выходят как ошибки, что подскажите сделать?
Репутация: 7
Всего: 45
PHP-Script
значит путь к extensions не правильный.
Посмотри путь к папке ext, в этой папке должны быть нужные тебе dll
Если их в этой папке нету кинь их туда насильно.
Затем открываем php.ini и ищем:
extension_dir
Например у меня так:
Цитата |
extension_dir = "G:/server/php/ext" |
Т.е. в значение надо вписать путь к папке ext
папка ext как правило находится в папке php
Репутация: 2
Всего: 20
Да нет extension_dir у меня в порядке, я же говорю - все остальные библиотеки он находит нормально а вышеперечисленные нет!
Репутация: 7
Всего: 45
PHP-Script
ну а где они лежат то эти dll . засунь их в папку.
Цитата |
заменил их новыми |
может этого нельзя делать
Репутация: 2
Всего: 20
вот мой путь к ним из php.ini:
extension_dir = "D:/MyWeb/PHP/extensions"
все я проверил - там они все красивенько лежат
Репутация: 122
Всего: 261
1. Сервер перезагружал?
2. Попробуй поочередно подключать, а то возможен конфликт.
3. А что он в логах апача за ошибку пишет? Может помимо самих dll надо в c:/windows/system32 что-то скидывать?
Репутация: 2
Всего: 20
Цитата(Mal @ 16.6.2005, 17:54) |
3. А что он в логах апача за ошибку пишет? Может помимо самих dll надо в c:/windows/system32 что-то скидывать? |
нет просто пишет:
Цитата |
PHP Warning: Unknown(): Unable to load dynamic library 'D:/MyWeb/PHP/extensions/php_xslt.dll' - Не найден указанный модуль. |
Репутация: 4
Всего: 13
Может быть несовместимость версий или отсутствие некоторых библ.
На всякий случай проверь существование этих файлов
для curl.dll -- libeay32.dll, ssleay32.dll
для php_domxml.dll -- нужен подключенный iconv.dll
для php_mhash.dll -- libmhash.dll
для php_xslt.dll -- sablot.dll, expat.dll и подключенный iconv.dll
Репутация: -2
Всего: 7
а они расскомментированы в php.ini.
и путь к extensions так пропиши: extension_dir = "./extensions" ну или "./ext" (как там у тебя не знаю)
Репутация: 122
Всего: 261
Цитата(Joes @ 16.6.2005, 22:41) |
extension_dir = "./extensions" ну или "./ext" (как там у тебя не знаю) |
Там должен быть полный путь от корня. (В Винде от диска)
Репутация: 2
Всего: 20
Репутация: 24
Всего: 55
решение проблемы выше:
Цитата |
Может быть несовместимость версий или отсутствие некоторых библ. На всякий случай проверь существование этих файлов для curl.dll -- libeay32.dll, ssleay32.dll для php_domxml.dll -- нужен подключенный iconv.dll для php_mhash.dll -- libmhash.dll для php_xslt.dll -- sablot.dll, expat.dll и подключенный iconv.dll |
Репутация: 2
Всего: 20
Репутация: 122
Всего: 261
Цитата(PHP @ 17.6.2005, 01:22) |
эти библиотеки должны быть в с:/windows/system32 . |
php_* - нет, другие скорее всего
Репутация: 2
Всего: 20
- Не брезгуйте пользоваться тегами [code=php]КОД[/code] для повышения читабельности текста/кода.
- Перед созданием новой темы воспользуйтесь поиском и загляните в FAQ
- Действия модераторов можно обсудить здесь
- Темы "ищу скрипт", "подскажите скрипт" и т.п. будут переноситься в форум "Web-технологии"
- Темы с именами: "Срочно", "помогите", "не знаю как делать" будут УДАЛЯТЬСЯ
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, [email protected] , skyboy, SamDark, MoLeX, awers.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) | |
0 Пользователей: | |
« Предыдущая тема | PHP: Общие вопросы | Следующая тема » |
[ Время генерации скрипта: 0.1983 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Репутация: -1
Всего: 2
Код |
while($m_array = mysql_fetch_row($res)) echo "del file ../".$m_array[0]; if(!file_exists("../".$m_array[0])) echo "no"; echo ""; > |
Так вот, file_exists выдаёт что файла нет, а вслед за этим нормально выводится рисунок.
Во вторых, когда я вместо переменной забиваю путь файда вручную - file_exists говарит что файл есть и нормально выводится рисунок.
Притом когда подставляю путь из массива - выводится в UTF-8, а когда забиваю в ручную - в cp1251. но это ака мне кажется детали.
У кого какие-нить мнения есть по этому поводу?
Я до сих пор в сети копаюсь - ничего найти немогу почему да отчего.
Репутация: нет
Всего: 1
Еще советую учесть, что значения параметров тегов стоит брать в кавычки.
А так же просто сверь имена, что в базе с именами, что выводятся и проверяются и с реальными.
Помимо всего прочего неплохо бы научиться правильно оформлять код и проверить лабуду с кавычками.
Самая страшная ошибка - это ошибка, не имеющая явных причин и конкретных последствий.
Антисоциальный блог.
Репутация: 8
Всего: 32
kaa, пользуйтесь тегами "код"!
Вохможно используется rewrite. То есть подмена путей. Например, скрипт находится в корне, хотя и вызывается как находящийся в папке.
Репутация: -1
Всего: 2
GZep, Извиняюсь - уже исправил.
А как этот rewrite отключить/отследить? А почему он не происходит когла я путь забиваю полностью вручную?
Репутация: 8
Всего: 32
Просто, используете ли вы файл .htaccess? Если нет, или не знаете что это такое, то rewrite у вас врядли стоит.
Попробуйте, вот так:
Репутация: -1
Всего: 2
не, .htccess не пользую
А код выводит '_FILE_'.
З.Ы.: А почему когда я путь ручками вбиваю то всё впорядке?
Репутация: 8
Всего: 32
Что вы вбиваете именно и что вбивает скрипт?
Отличается ли то, что вы вбиваете и:
Репутация: 3
Всего: 71
посмотри что даёт.
Репутация: -1
Всего: 2
GZep, Я вбиваю:
Код |
'../images/ware_img/GU4R4YYl3zeJBNQgnxae/Доска-для-элемента-фона.jpg' |
В массиве все тоже самое.
Правда есть один маленький ньюансик - когда я вбиваю вручную. то всё корректно отображается в win-1251, когда подставляю из массива то для корректного отображения нужно выбрать кодировку просмотра UTF-8.
как ни странно - ничего.
Кароче я савсем уже запутался.
Репутация: 8
Всего: 32
Код |
while($m_array = mysql_fetch_row($res)) echo "del file ../".$m_array[0]; if(!file_exists("../" . urlencode($m_array[0]))) echo "no"; echo ""; > |
Репутация: 1
Всего: 2
kaa, это только с кириличными именами файлов происходит? Я бы советовал от них отказаться для сохранения портирования кода.
Полагаю, что имя файла хранится в базе в утф, а файловая система утф не понимает.
Можно попробовать конвертнуть имя файла
Код |
$path = '../'; while($m_array = mysql_fetch_row($res)) |
$name = iconv("UTF-8", "CP1251", $m_array[0]);
$file = $path.$name;
print "
";
Репутация: -1
Всего: 2
Репутация: 7
Всего: 18
Цитата |
Note: The results of this function are cached. See clearstatcache() for more details. |
может быть поможет?
хотя все странно это.
Репутация: -1
Всего: 2
Powerhead, Дико извиняюсь, я вас обманул. Толькочто еще баг выловил. В общем да, неработает только с русскими - приходится конвертировать в cp1251. ТОлько вот незадача - у меня в базе всё хранится в cp1251 и
я выполняю сразу после подключения к БД.
Кстати, отчего система не поддерживает UTF-8?! Ведь клиенту всё идет именно в этой кодировке - по другому ведь кирилицу не передашь.
Мне нужно загрузить файл в папку и после отправки его через phpmailer. У меня проблема с загрузкой. Не видит $_FILES["filename"]["tmp_name"] и на var_dump это показывает NULL , Также показывает реж C:\fakepath Я читал, что это сторона безопасности. Как избежать этой проблемы и загрузить файл?
example.php
Смотрите также
- is_readable() - Определяет существование файла и доступен ли он для чтения
- is_writable() - Определяет, доступен ли файл для записи
- is_file() - Определяет, является ли файл обычным файлом
- file() - Читает содержимое файла и помещает его в массив
- SplFileInfo
Возвращаемые значения
Возвращает true , если файл или каталог, указанный параметром filename , существует, иначе возвращает false .
Замечание:
Данная функция возвращает false для символических ссылок, указывающих на несуществующие файлы.
Замечание:
Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Другие решения
Вы должны указать полный адрес в $uploads_dir переменная. Похоже, что вы пытаетесь это в системе Windows, поэтому не будет /uploads каталог. Вы должны поставить адрес как C:/directory , Убедитесь, что вы включили разрешение на чтение / запись / удаление для пользователя PHP в этом каталоге. Также обратите внимание, что вы заселяете $uploadedFile Вар, как это:
$uploadedFile = $uploads_dir . basename($_FILES['file_name']['name']."test");
$uploadedFile = $uploads_dir . "/" . basename($_FILES['file_name']['name']."test");
Между именем папки и именем файла должна быть косая черта.
На платформах Windows, для проверки наличия файлов на сетевых ресурсах, используйте имена, подобные //computername/share/filename или \\computername\share\filename .
See Also
- is_readable() - Tells whether a file exists and is readable
- is_writable() - Tells whether the filename is writable
- is_file() - Tells whether the filename is a regular file
- file() - Reads entire file into an array
- SplFileInfo
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Читайте также: