- PHP Directory
- Basic directory operations
- Get the current directory
- Create a new directory
- Delete a directory
- Check if a path is a directory
- Summary
- ftp_chdir
- Список изменений
- Примеры
- Смотрите также
- User Contributed Notes 2 notes
- chdir
- Список параметров
- Возвращаемые значения
- Ошибки
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 3 notes
- chdir
- Errors/Exceptions
- Examples
- Notes
- See Also
PHP Directory
Summary: in this tutorial, you will learn how to work with directories using various built-in functions in PHP.
Basic directory operations
PHP provides a set of handy functions that allow you to work with directories effectively. To manage a directory, you need to get a directory handle.
To get the directory handle of a directory, you pass the directory path to the opendir() function as follows:
$dh = opendir('./public');
Code language: HTML, XML (xml)
If an error occurs while opening the directory, the opendir() function returns false .
When you’re done with the directory, you need to close the directory handle by using the closedir() function:
closedir($dh);
Code language: HTML, XML (xml)
Each directory may contain a list of files or sub-directories. It may also contain the dot entry ( .) that represents the current directory and the entry ( .. ) that represents the parent directory.
To get the next entry (a file or a directory) in a directory, you pass the directory handle to the readdir() function.
Suppose the public directory is as follows:
. ├── css │ └── style.css └── js └── app.js
Code language: CSS (css)
The following example lists all subdirectories in the public directory:
$dh = opendir('./public'); if ($dh) < while ($e = readdir($dh)) < if ($e !== '.' && $e !== '..') < echo $e , PHP_EOL; > > > closedir($dh);
Code language: HTML, XML (xml)
Note that the readdir() function returns the directories and files of the current directory specified by the directory handle. It doesn’t recursively returns the files and directories of the subdirectories.
The following code is functionally equivalent to the above example except that it uses the try. catch. finally statement to handle the error:
try < $dh = opendir('./public'); if (!$dh) < throw new Exception('Error openning the directory'); > while ($e = readdir($dh)) < if ($e !== '.' && $e !== '..') < echo $e . '
'; > > > catch (\Throwable $e) < echo $e->getMessage(); > finally < if ($dh) < closedir($dir); >>
Code language: PHP (php)
Get the current directory
By default, the current directory is the directory that contains the currently running script file. The current directory is important because it is used as the base directory for relative file paths.
To get the current directory, you use the getcwd() function:
echo getcwd();
Code language: HTML, XML (xml)
To change the current directory to a new one, you use the chdir() function:
chdir('./dev'); echo getcwd();
Code language: HTML, XML (xml)
After calling the chdir() function, the current directory changes to ‘./dev’. And you can verify it by calling the getcwd() function.
Create a new directory
To create a directory, you use the mkdir() function by passing the directory path. The mkdir() function returns true if it created the directory successfully of false otherwise.
$dir = './public/img'; if (mkdir($dir)) < echo ' The dir ', $dir, 'created successfully!'; >
Code language: HTML, XML (xml)
Notice that the parent directory public must exist.
By default the mkdir() function sets 0777 to the new directory. If you want to set different a permission, you can pass it to the mkdir() function or use the chmod() function. For example:
$dir = './public/assets'; mkdir($dir, 0644);
Code language: HTML, XML (xml)
For more information on setting permissions on the file or directory, check it out the file permissions tutorial.
Delete a directory
To delete a directory, you use the rmdir() function. And you need to have sufficient permissions to remove the directory.
Also, the directory needs to be empty. In other words, it doesn’t contain any files or sub-directories.
The following example deletes the directory assets under the public directory:
rmdir('./public/assets');
Code language: HTML, XML (xml)
Check if a path is a directory
To check if a path is a directory, you use the is_dir() function:
is_dir ( string $filename ) : bool
Code language: PHP (php)
The is_dir() function returns true if the $filename exists and is a directory. For example:
$path = './public'; if (is_dir($path)) < echo $path, ' is a directory.'; >
Code language: HTML, XML (xml)
Summary
- Use the opendir() function to open a directory and get the directory handle and the closedir() function once you are done with the directory.
- Use the readdir() function to read the entries in a directory specified by a directory handle.
- Use the mkdir() function to create a new directory.
- Use the rmdir() function to remove a directory.
- Use the is_dir() function to check if a path is a directory and that directory exists in the file system.
ftp_chdir
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки. Если изменение директории завершилось неудачей, PHP вызовет предупреждение.
Список изменений
Примеры
Пример #1 Пример использования ftp_chdir()
// установка соединения
$ftp = ftp_connect ( $ftp_server );
// вход с именем пользователя и паролем
$login_result = ftp_login ( $ftp , $ftp_user_name , $ftp_user_pass );
// проверка соединения
if ((! $ftp ) || (! $login_result )) die( «Не удалось подключиться к FTP-серверу!» );
>
echo «Текущая директория: » . ftp_pwd ( $ftp ) . «\n» ;
// пытаемся сменить текущую директорию на somedir
if ( ftp_chdir ( $ftp , «somedir» )) echo «Новая текущая директория: » . ftp_pwd ( $ftp ) . «\n» ;
> else echo «Не удалось сменить директорию\n» ;
>
// закрытие соединения
ftp_close ( $ftp );
?>
Смотрите также
User Contributed Notes 2 notes
Thanks to h3 at valleyfield dot net
Same function with some minor changes and comments added
FTP function checks if a directory exists
function ftp_is_dir ( $dir ) global $ftpcon ;
// get current directory
$original_directory = ftp_pwd ( $ftpcon );
// test if you can change directory to $dir
// suppress errors in case $dir is not a file or not a directory
if ( @ ftp_chdir ( $ftpcon , $dir ) ) // If it is a directory, then change the directory back to the original directory
ftp_chdir ( $ftpcon , $original_directory );
return true ;
>
else return false ;
>
>
?>
Works like the other functions in this page’s notes, but this one doesn’t make use of a global FTP connection, so it takes parameters like the other functions in the extension
function ftp_directory_exists ( $ftp , $dir )
<
// Get the current working directory
$origin = ftp_pwd ( $ftp );
// Attempt to change directory, suppress errors
if (@ ftp_chdir ( $ftp , $dir ))
<
// If the directory exists, set back to origin
ftp_chdir ( $ftp , $origin );
return true ;
>
// Directory does not exist
return false ;
>
?>
chdir
Изменяет текущий каталог PHP на указанный в качестве параметра directory .
Список параметров
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Ошибки
В случае неудачного выполнения выдаёт ошибку уровня E_WARNING .
Примеры
Пример #1 Пример использования chdir()
// текущий каталог
echo getcwd () . «\n» ;
// текущий каталог
echo getcwd () . «\n» ;
Результатом выполнения данного примера будет что-то подобное:
/home/vincent /home/vincent/public_html
Примечания
Если PHP-интерпретатор собран с поддержкой ZTS (Zend Thread Safety), любые изменения в текущем каталоге, сделанные с помощью chdir() , не будут обнаружены операционной системой. Все встроенные функции PHP будут по-прежнему учитывать изменения в текущем каталоге; это не относится к вызываемым функциям внешних библиотек, подключённых через FFI. Используйте php -i или встроенную константу PHP_ZTS , чтобы узнать, собран ли PHP с ZTS.
Смотрите также
User Contributed Notes 3 notes
When working with FFI under a PHP ZTS environment, there is no standard way to change the directory with libraries (dll/so/dylib/etc), so to get around this problem, you should use something like this polyfill:
switch (\ PHP_OS_FAMILY ) case ‘Windows’ :
\ FFI :: cdef ( ‘extern unsigned char SetDllDirectoryA(const char* lpPathName);’ , ‘kernel32.dll’ )
-> SetDllDirectoryA ( $directory )
;
break;
case ‘Linux’ :
case ‘BSD’ :
\ FFI :: cdef ( ‘int setenv(const char *name, const char *value, int overwrite);’ )
-> setenv ( ‘LD_LIBRARY_PATH’ , $directory , 1 )
;
break;
case ‘Darwin’ :
\ FFI :: cdef ( ‘int setenv(const char *name, const char *value, int overwrite);’ )
-> setenv ( ‘DYLD_LIBRARY_PATH’ , $directory , 1 )
;
break;
>
When changing dir’s under windows environments:
$path = «c:\temp»‘;
chdir($path);
/* getcwd() gives you back «c:\temp» */
$path=»c:\temp\»‘ ;
chdir ( $path );
/* getcwd() gives you back «c:\temp\» */
?>
to work around this inconsistency
doing a chdir(‘.’) after the chdir always gives back «c:\temp»
When using PHP safe mode and trying to change to a dir that is not accessible due to the safe mode restrictions, the function simply fails without generating any kind of error message.
(Tested in PHP 4.3.10-16, Debian Sarge default)
chdir
Возвращает true в случае успеха или false в случае неудачи.
Errors/Exceptions
В случае ошибки E_WARNING ошибку уровня E_WARNING .
Examples
Пример # 1 ChDir () Пример
// current directory echo getcwd() . "\n"; chdir('public_html'); // current directory echo getcwd() . "\n"; ?>
Из приведенного выше примера будет выведено нечто подобное:
/home/vincent /home/vincent/public_html
Notes
Если интерпретатор PHP был построен с включенным ZTS (Zend Thread Safety), любые изменения в текущем каталоге, сделанные с помощью chdir (), будут невидимы для операционной системы. Все встроенные функции PHP по-прежнему будут учитывать изменения в текущем каталоге; но функции внешней библиотеки, вызываемые с помощью FFI , не будут. Вы можете определить, была ли ваша копия PHP создана с включенным ZTS, используя php -i или встроенную константу PHP_ZTS .
See Also
PHP 8.2
(PHP 4 4.0.4,5,7,8)call_user_func_array callback with an of parameters Вызывает обратный вызов,заданный первым параметром,с параметрами в args.
(PHP 4,5,7,8)ceil Округление дробей в большую сторону Возвращает следующее наибольшее целое значение,при необходимости округляя num в большую сторону.
(PHP 4,5,7,8)checkdnsrr записи,соответствующие заданному IP-адресу имени хоста в Интернете Ищет в DNS записи типа,соответствующего имени хоста.