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中文網其他相關文章!