- file_exists
- Возвращаемые значения
- Ошибки
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 31 notes
- post — проверка PHP, есть ли файл, выбранный для загрузки
- Решение
- Другие решения
- PHP проверить, есть ли файл, выбранный для загрузки
- is_uploaded_file
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
file_exists
На платформах Windows, для проверки наличия файлов на сетевых ресурсах, используйте имена, подобные //computername/share/filename или \\computername\share\filename .
Возвращаемые значения
Возвращает true , если файл или каталог, указанный параметром filename , существует, иначе возвращает false .
Замечание:
Данная функция возвращает false для символических ссылок, указывающих на несуществующие файлы.
Замечание:
Проверка происходит с помощью реальных UID/GID, а не эффективных идентификаторов.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примеры
Пример #1 Проверка существования файла
if ( file_exists ( $filename )) echo «Файл $filename существует» ;
> else echo «Файл $filename не существует» ;
>
?>
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Смотрите также
- is_readable() — Определяет существование файла и доступен ли он для чтения
- is_writable() — Определяет, доступен ли файл для записи
- is_file() — Определяет, является ли файл обычным файлом
- file() — Читает содержимое файла и помещает его в массив
- SplFileInfo
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 😉
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
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.
file_exists() does NOT search the php include_path for your file, so don’t use it before trying to include or require.
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.
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.
NOTE: This method fails if the above function is not used for checking in all other scripts/processes as it doesn’t actually lock the file.
FIX: You could flock() the file to prevent that (although all other scripts similarly must check it with flock() then, see https://www.php.net/manual/en/function.flock.php). Be sure to unlock and fclose() the file AFTER you’re done with it, and not within the above function:
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 ;
>
if ( $lock = create_and_lock ( «foo.txt» )) // do stuff
flock ( $fd , LOCK_UN ); // unlock
fclose ( $fd ); // close
>
?>
SEE ALSO: https://linux.die.net/man/2/open about O_CREAT|O_EXCL (which is used with the ‘x’ modifier for fopen()) and problems with NFS
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..
$file = ‘http://www.domain.com/somefile.jpg’;
$file_headers = @get_headers($file);
if($file_headers[0] == ‘HTTP/1.1 404 Not Found’) $exists = false;
>
else $exists = true;
>
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!
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.
With PHP 7.0 on Ubuntu 17.04 and with the option allow_url_fopen=On, file_exists() returns always false when trying to check a remote file via HTTP.
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.
here a function to check if a certain URL exist:
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:
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 );
>
>
?>
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 )
post — проверка PHP, есть ли файл, выбранный для загрузки
У меня есть эта форма, и я хотел бы проверить, выбрал ли пользователь файл или нет.
Я написал этот код PHP, чтобы проверить его
if (empty($_POST) === false) < $fileupload = $_POST['file_upload']; if (empty($fileupload) === true) < // echo "Error no file selected"; >else < print_r($_FILES); >>
Но я получаю «Ошибка, файл не выбран», даже если я выбираю что-то. Любая подсказка? Извините, я действительно новичок в PHP.
РЕДАКТИРОВАТЬ: Я уже пробовал заменить $fileupload = $_FILES[‘file_upload’] но он печатает пустую ошибку
(Array ([file_upload] => Array ([name] => [type] => [tmp_name] =>
[ошибка] => 4 [размер] => 0)))
Решение
Использовать $_FILES массив и UPLOAD_ERR_NO_FILE постоянная:
if(!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] == UPLOAD_ERR_NO_FILE) < echo "Error no file selected"; >else
Вы также можете проверить UPLOAD_ERR_OK который указывает, был ли файл успешно загружен (присутствует и ошибок нет).
Примечание: вы не можете использовать empty() на $_FILES[‘file_upoad’] массив, потому что даже если файл не загружен, массив все еще заполнен и error элемент установлен, что означает empty() вернусь false ,
Другие решения
Сначала нажмите «Отправить» без выбора файла.
/* check input 'submit' */ if (isset($_POST['submit']))
> Массив ( > [file_upload] => Массив > ( > [name] => > [тип] => > [tmp_name] => > [ошибка] => 4 > [размер] => 0 >) > >)
Есть множество [file_upload] [error] = 4, НЕ ноль или пробел.
Значение кода = 4, что означает UPLOAD_ERR_NO_FILE.
Если успех и ошибки нет, кодовое значение = 0.
Проверьте Вот
Так что используйте функцию Исеть, не пустой
/* check input submit */ if (isset($_POST['submit'])) < /* check input file_upload on error */ if (isset($_FILES['file_upload']['error'])) < /* check code error = 4 for validate 'no file' */ if ($_FILES['file_upload']['error'] == 4) < echo "Please select an image file .."; >> >
В соответствии с http://www.php.net с php 4.1.0 доступно $ _FILES. Эта переменная хранит информацию о загруженных файлах. Так что вы должны код
$fileupload = $_FILES['file_upload']; if (isset($fileupload)) < print_r($_FILES); >else
PHP проверить, есть ли файл, выбранный для загрузки
У меня есть эта форма, и я хотел бы проверить, выбрал ли пользователь файл или нет.
Я написал этот PHP-код, чтобы проверить его
if (empty($_POST) === false) < $fileupload = $_POST['file_upload']; if (empty($fileupload) === true) < // echo "Error no file selected"; >else < print_r($_FILES); >>
Но я получаю “Ошибка без файла”, даже если я что-то сделаю. Любая подсказка? Прости, что я действительно новичок в PHP.
EDIT: я уже пытался заменить $fileupload = $_FILES [‘file_upload’], но он печатает пустую ошибку (Array ([file_upload] = > Array ([name] = > [type] = > [tmp_name] = > [error] = > 4 [size] = > 0))), когда я не вхожу в файл?
Используйте массив $_FILES и константу UPLOAD_ERR_NO_FILE :
if(!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] == UPLOAD_ERR_NO_FILE) < echo "Error no file selected"; >else
Вы также можете проверить UPLOAD_ERR_OK , который указывает, был ли файл успешно загружен (присутствует и нет ошибок).
Примечание: вы не можете использовать empty() в массиве $_FILES[‘file_upoad’] , потому что даже если файл не загружен, массив все еще заполняется и элемент error установлен, что означает, что empty() вернет false .
Сначала нажмите “Отправить” без выбора файла
/* check input 'submit' */ if (isset($_POST['submit']))
> Array ( > [file_upload] => Array > ( > [name] => > [type] => > [tmp_name] => > [error] => 4 > [size] => 0 > ) > > )
Существует массив [file_upload] [error] = 4, НЕ нулевой или пробельный.
Значение кода = 4, что означает UPLOAD_ERR_NO_FILE.
Если успех и отсутствие ошибки, значение кода = 0.
Проверьте здесь
Поэтому используйте функцию isset, а не empty
/* check input submit */ if (isset($_POST['submit'])) < /* check input file_upload on error */ if (isset($_FILES['file_upload']['error'])) < /* check code error = 4 for validate 'no file' */ if ($_FILES['file_upload']['error'] == 4) < echo "Please select an image file .."; >> >
В соответствии с http://www.php.net существует $_FILES, доступный с php 4.1.0. Эта переменная хранит информацию о загруженных файлах. Поэтому вы должны закодировать
$fileupload = $_FILES['file_upload']; if (isset($fileupload)) < print_r($_FILES); >else
is_uploaded_file
Возвращает TRUE , если файл filename был загружен при помощи HTTP POST. Это полезно для удостоверения того, что злонамеренный пользователь не пытается обмануть скрипт так, чтобы он работал с файлами, с которыми работать не должен — к примеру, /etc/passwd .
Такие проверки особенно полезны, если существует вероятность того, что операции над файлом могут показать его содержимое пользователю или даже другим пользователям той же системы.
Для правильной работы, функции is_uploaded_file() нужен аргумент вида $_FILES[‘userfile’][‘tmp_name’] , — имя закачиваемого файла на клиентской машине $_FILES[‘userfile’][‘name’] не подходит.
Список параметров
Возвращаемые значения
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования функции is_uploaded_file()
if ( is_uploaded_file ( $_FILES [ ‘userfile’ ][ ‘tmp_name’ ])) echo «Файл » . $_FILES [ ‘userfile’ ][ ‘name’ ] . » успешно загружен.\n» ;
echo «Отображаем содержимое\n» ;
readfile ( $_FILES [ ‘userfile’ ][ ‘tmp_name’ ]);
> else echo «Возможная атака с участием загрузки файла: » ;
echo «файл ‘» . $_FILES [ ‘userfile’ ][ ‘tmp_name’ ] . «‘.» ;
>
Смотрите также
- move_uploaded_file() — Перемещает загруженный файл в новое место
- $_FILES
- Простой пример использования можно найти в разделе «Загрузка файлов на сервер».