Php type file path

pathinfo

pathinfo() возвращает информацию о path в виде ассоциативного массива или строки, в зависимости от flags .

Замечание:

Подробнее о получении информации о текущем пути, можно почитать в разделе Предопределённые зарезервированные переменные.

Замечание:

pathinfo() оперирует входной строкой и не знает фактическую файловую систему или компоненты пути, такие как » .. «.

Замечание:

Только в системах Windows символ \ будет интерпретироваться как разделитель каталогов. В других системах он будет рассматриваться как любой другой символ.

pathinfo() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() .

Список параметров

Если указан, то задаёт, какой из элементов пути будет возвращён: PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION и PATHINFO_FILENAME .

Если flags не указан, то возвращаются все доступные элементы.

Возвращаемые значения

Если параметр flags не передан, то возвращаемый ассоциативный массив ( array ) будет содержать следующие элементы: dirname , basename , extension (если есть) и filename .

Замечание:

Если path содержит больше одного расширения, то PATHINFO_EXTENSION возвращает только последний и PATHINFO_FILENAME удаляет только последнее расширение. (смотрите пример ниже).

Замечание:

Если path не содержит расширения, то не будет возвращён элемент extension (смотрите ниже второй пример).

Замечание:

Если basename параметра path начинается с точки, то все последующие символы интерпретируются как расширение файла ( extension ) и имя файла filename будет пустым (смотрите третий пример).

Если указан параметр flags , будет возвращена строка ( string ), содержащая указанный элемент.

Примеры

Пример #1 Пример использования функции pathinfo()

$path_parts = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

echo $path_parts [ ‘dirname’ ], «\n» ;
echo $path_parts [ ‘basename’ ], «\n» ;
echo $path_parts [ ‘extension’ ], «\n» ;
echo $path_parts [ ‘filename’ ], «\n» ;
?>

Результат выполнения данного примера:

/www/htdocs/inc lib.inc.php php lib.inc

Пример #2 Пример с pathinfo() , показывающий разницу между null и отсутствием расширения

$path_parts = pathinfo ( ‘/path/emptyextension.’ );
var_dump ( $path_parts [ ‘extension’ ]);

$path_parts = pathinfo ( ‘/path/noextension’ );
var_dump ( $path_parts [ ‘extension’ ]);
?>

Результатом выполнения данного примера будет что-то подобное:

string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL

Пример #3 Пример pathinfo() для файла, начинающегося с точки

Результатом выполнения данного примера будет что-то подобное:

Array ( [dirname] => /some/path [basename] => .test [extension] => test [filename] => )

Пример #4 Пример использования pathinfo() с разыменованием массива

Параметр flags не является битовой маской. Может быть предоставлено только одно значение. Чтобы выбрать только ограниченный набор разобранных значений, используйте деструктуризацию массива следующим образом:

[ ‘basename’ => $basename , ‘dirname’ => $dirname ] = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

var_dump ( $basename , $dirname );
?>

Результатом выполнения данного примера будет что-то подобное:

string(11) "lib.inc.php" string(15) "/www/htdocs/inc"

Смотрите также

  • dirname() — Возвращает имя родительского каталога из указанного пути
  • basename() — Возвращает последний компонент имени из указанного пути
  • parse_url() — Разбирает URL и возвращает его компоненты
  • realpath() — Возвращает канонизированный абсолютный путь к файлу

Источник

Directory Uploads in PHP 8.1

Directory-uploads in PHP

One of the new features in PHP 8.1 is that PHP’s $_FILES super global variable now contains the path to the files uploaded by the user. This information is provided by browsers that support entire directory uploads, and from PHP 8.1, this information is made available to support directory-uploads in PHP applications.

An HTML form with a file field, containing a webkitdirectory attribute is considered a directory-upload field. Browsers supporting this feature allows the user to select an entire directory instead of individual files. Once the user selects the directory to upload, browser submits all files inside that directory, including all sub directories and their files, to the server.

In a PHP application running PHP 8.1 or later, the file path is made available from the $_FILES super global, and the application can store the file paths in addition to other information such as the file name, size, etc.

Note that the file path provided by browsers is user-input, and must be treated as such. Such fields are prone to path traversal attacks, which are not that uncommon.

webkitdirectory attribute

webkitdirectory is an HTML attribute that can be used in input HTML elements with type=file . It is not a browser-standard, but all major browsers support it, including Chrome 6+, Firefox 50+, Edge 13+, and Safari 11.1+.

HTML directory upload field

Directory uploads reuse the standard input elements with type=file . Browsers that support the webkitdirectory will offer a directory-upload window, and the rest will offer a standard file upload window.

Directory-uploads in field rendered in browser
Directory-uploads window

Accessing file path in PHP

When the user uploads a directory using a directory-upload field, browser submits the relative path to that file along with the file name, file size, and file contents.

In PHP, file upload information is accessed from the $_FILES super global. Prior to PHP 8.1, the relative file path provided by the browser was not passed to $_FILES , making it impossible to determine the directory hierarchy of a directory-upload.

From PHP 8.1, this information is passed to $_FILES , and can be used to store a directory-upload along with their relative paths, or even recreate the directory in the server.

The $_FILES array contains file upload information indexed by the name attribute of the HTML input field. In the example above, the input field is named name=dir_upload[] . It means that the $_FILES array contains a direct $_FILES[‘dir_upload’] array, which in turn contains associative arrays with keys such as name , tmp_name , etc.

project_files ├── data │ └── data.csv ├── outlines │ ├── intro.doc │ └── welcome.doc ├── presentation.pdf ├── presentations │ ├── ayesh.ppt │ ├── mentor.doc │ └── phpwatch.ppt └── report.xls

With a directory structure similar to above, the $_FILES array only returns the base file name from $_FILES[‘dir_upload’][‘name’] .

array(1) < ["dir_upload"]=>array(6) < ["name"]=>array(8) < [0]=>string(8) "data.csv" [1]=> string(16) "presentation.pdf" [2]=> string(9) "intro.doc" [3]=> string(11) "welcome.doc" [4]=> string(10) "report.xls" [5]=> string(12) "phpwatch.ppt" [6]=> string(9) "ayesh.ppt" [7]=> string(10) "mentor.doc" > . type, tmp_name, error, size

Notice how the relative paths are missing from the $_FILES[‘dir_upload’][‘name’] array, which makes it impossible to retrieve the relative path to the files from the user file system.

From PHP 8.1 and later, a new array is added to each file upload field in $_FILES , which contains the relative path to the files.

array(1) < ["dir_upload"]=>array(6) < ["name"]=>array(8) < [0]=>string(8) "data.csv" [1]=> string(16) "presentation.pdf" . > + ["full_path"]=> array(8) < + [0]=>string(27) "project-files/data/data.csv" + [1]=> string(30) "project-files/presentation.pdf" + [2]=> string(32) "project-files/outlines/intro.doc" + [3]=> string(34) "project-files/outlines/welcome.doc" + [4]=> string(24) "project-files/report.xls" + [5]=> string(40) "project-files/presentations/phpwatch.ppt" + [6]=> string(37) "project-files/presentations/ayesh.ppt" + [7]=> string(38) "project-files/presentations/mentor.doc" > . type, tmp_name, error, size

The new full_path array in each file upload field lists the complete path to the file.

On directory uploads, it is now possible to store the full path to each uploaded file. Applications that prefer to store the uploaded files in the same directory structure as the user who uploaded the files can do so by moving the files recursively to the relevant directories on the server.

Security Hardening

The full_path array in each $_FILES field is not safe, because it is direct user input. All values from this array must be validated to prevent potential vulnerabilities, especially when storing the uploaded files in sub directories on the server.

  • The submitted full_path value might trigger path traversal. For example, if the server saves the user uploaded files, make sure to reject values that might attempt path traversal
  • Validate nested levels and lengths of the file paths. Deeply nested sub directories, or excessively long file paths can lead to errors and may lead to file system failures.

Recent Articles on PHP.Watch

How to extend lifetime of legacy PHP applications

How to extend lifetime of legacy PHP applications

As PHP continue to evolve with new breaking changes, and while that is great for most PHP applications, there are legacy applications that can’t justify the human and financial cost of keeping up. Here is a guide on how to extend the lifetime of legacy PHP applications with security updates and maintenance.

PHP 8.2 Highlights: What

PHP 8.2 Highlights: What’s New and Changed

How to install/upgrade PHP 8.2 on Debian and Ubuntu systems

How to install/upgrade PHP 8.2 on Debian and Ubuntu systems

You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what’s changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.

© 2018-2023 PHP.Watch, with ❤ from Ayesh • About PHP.Watch

Источник

PHP pathinfo

Summary: in this tutorial, you will learn how to use the PHP pathinfo() function to get the information on a file path.

Introduction to the PHP pathinfo() function

The PHP pathinfo() function accepts a file path and returns its components:

pathinfo ( string $path , int $flags = PATHINFO_ALL ) : array|stringCode language: PHP (php)

The pathinfo() function has two parameters:

  • $path is the file path from which you want to get the information.
  • $flags parameter specifies the part element to return.

The following table shows the valid flag values:

Flag Meaning
PATHINFO_DIRNAME Return the directory name
PATHINFO_BASENAME Return the base name
PATHINFO_EXTENSION Return the file extension
PATHINFO_FILENAME Return the file name (without the extension)

If you don’t pass the $flag argument, the pathinfo() function will return all components of a file path.

PHP pathinfo() function examples

Let’s take some examples of using the pathinfo() function.

1) Using the pathinfo() function to get all components of a file path

The following example uses the pathinfo() function to get the components of a file path:

 $path = 'htdocs/phptutorial/index.php'; $parts = pathinfo($path); print_r($parts);Code language: HTML, XML (xml)
Array ( [dirname] => htdocs/phptutorial [basename] => index.php [extension] => php [filename] => index )Code language: PHP (php)

2) Using the pathinfo() function to get only a specific component of a file path

The following example uses the pathinfo() function get the basename of a file path:

 $path = 'htdocs/phptutorial/index.php'; $basename = pathinfo($path, PATHINFO_BASENAME); echo $basename;Code language: HTML, XML (xml)
index.phpCode language: CSS (css)

3) Using the pathinfo() function to get the path components of a dot-file path

The following example uses the pathinfo() function to get components of the path of a dot-file:

 $path = '/htdocs/phptutorial/.gitignore'; $parts = pathinfo($path); print_r($parts);Code language: HTML, XML (xml)
Array ( [dirname] => /htdocs/phptutorial [basename] => .gitignore [extension] => gitignore [filename] => )Code language: PHP (php)

Summary

  • Use the PHP pathinfo() function to get the components of a file path including dirname, basename, filename, and extesion.

Источник

Читайте также:  Hide for mobile css
Оцените статью