PHP 文件扩展名对于对任何上传的文件进行正确的验证非常有用。从文件名或文件位置获取扩展名非常有用,因为它让程序员知道他们必须上传或操作仅与 PHP 相关的文件,而不是任何其他编程语言或具有任何其他扩展名的文件。每当需要获取文件扩展名时,自定义 PHP 都会发挥重要作用,因为这些函数会返回所需的文件扩展名,使用该扩展名可以更新所需的 PHP 相关文件。
广告 该类别中的热门课程 PHP 开发人员 - 专业化 | 8 门课程系列 | 3次模拟测试开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
每种编程语言都有文件扩展名,PHP 文件也有,表示为:
public SplFileInfo::getExtension() : string, filename etc.
哪里,
有很多方法可以在任何编程语言中获取文件扩展名,因为它有助于识别内容和文件,这与 PHP 相关以便于操作。因此,PHP 中的文件扩展名有很多优点和缺点,在 PHP 中获取扩展名的方法如下:
以下是下面提到的示例
此程序演示了使用 SplFileInfo 作为其 inbuild 函数的 getExtension 函数,该函数允许传递带有扩展名的任何字符串以获得 PHP 代码库的支持,如输出所示。
代码:
<?php $in_1 = new SplFileInfo('foam.txt'); var_dump($in_1->getExtension()); $in_1 = new SplFileInfo('import_ant.tar.gz'); var_dump($in_1->getExtension()); $in_1 = new SplFileInfo('image_with.jpeg'); var_dump($in_1->getExtension()); ?>
输出:
This program demonstrates the pathinfo, which tells about the given file’s information and can be used to get the directory name, base name, file name, and extension. It will return the text file as shown in the output.
Code:
<?php $fil_nm = 'directory_1/anu.txt'; $extnsn = pathinfo($fil_nm, PATHINFO_EXTENSION); var_dump($extnsn); ?>
Output:
This program demonstrates the approach to get the file extension if in a file with multiple periods or dots exists then also pathinfo will work as shown in the output.
Code:
<?php $fl_nm = 'fldr/exmpl.txt.jpeg.tar.gz'; $extnsn = pathinfo($fl_nm, PATHINFO_EXTENSION); var_dump($extnsn); ?>
Output:
This program demonstrates the custom function which is used for returning substring by calling the function wherever required, as shown in the output.
Code:
<?php function get_fl_extnsn($fname) { return substr(strrchr($fname,'.'),1); } echo get_fl_extnsn('extension.jpg.txt'); ?>
Output:
This program demonstrates the output if there is no extension if an empty string with pathinfo() function will return as shown.
Code:
<?php $fl_pth = 'path/to_1/file_n/'; $extn = pathinfo($fl_pth, PATHINFO_EXTENSION); var_dump($extn); ?>
Output:
This program demonstrates the pathinfo regarding the file name with an extension which is being included and is manipulated as per the requirement as shown in the output. It can support a multi dot file structure for getting the extension.
Code:
<?php $pth_pp = pathinfo('include/bin.include.php'); echo $pth_pp['extension'], "\n"; echo $pth_pp['filename'], "\n"; ?>
Output:
PHP get file extension like other programming languages is used for identifying the type of PHP file that will get uploaded and manipulated by giving some must information like a directory, extension, file name, basename. It is advantageous when some troubleshooting is required from getting out of a stuck situation.
以上是PHP 获取文件扩展名的详细内容。更多信息请关注PHP中文网其他相关文章!