每當需要在PHP 中刪除檔案時,我們都會使用PHP 中稱為unlink 函數的函數,該函數有兩個參數,即檔案名稱和上下文,其中檔案名稱是要刪除的檔案所在的檔案位置的路徑已刪除的位置,上下文表示文件句柄的上下文,它們是一組能夠更改文件流行為的選項,並且取消鏈接函數的此參數是可選的,以防取消鏈接函數無法刪除給定文件由文件路徑指定,將產生錯誤訊息。
開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
文法:
unlink(path_of_the_file, context)
哪裡,
下面給出的是提到的例子:
代碼:
<html> <body> <?php #a file is opened in write mode using fopen function and the contents are written to the file using fwrite function and then the file is closed using fclose function $nameofthefile = fopen("filename.txt","w"); echo fwrite($nameofthefile,"Welcome to PHP"); fclose($nameofthefile); #the file that was created is opened in read mode using fopen function and the contents are read from the file using fread function and displayed as the output on the screenand then the file is closed using fclose function $fileread = fopen("filename.txt", "r"); echo fread($fileread, filesize("filename.txt")); fclose($fileread); #unlink function is used to delete the file that was just being read unlink("filename.txt"); #again we try to read the contents of the file that was just deleted using unlink function $fileread = fopen("filename.txt", "r"); echo fread($fileread, filesize("filename.txt")); fclose($fileread); ?> </body> </html>
輸出:
在上面的程式中,使用 fopen 函數以寫入模式開啟文件,並使用 fwrite 函數將內容寫入文件,然後使用 fclose 函數關閉文件。然後使用 fopen 函數以讀取模式開啟相同文件,並使用 fread 函數讀取文件的內容,並將文件的內容以及文件的大小作為輸出顯示在螢幕上,然後關閉文件使用 fclose 函數。然後我們使用 unlink 函數刪除同一個建立的檔案。然後,如果我們嘗試再次讀取已刪除的文件,螢幕上會顯示警告錯誤訊息。輸出如上面的快照所示。
代碼:
<html> <body> <?php #a file is opened in write mode using fopen function and the contents are written to the file using fwrite function and then the file is closed using fclose function $nameofthefile = fopen("filename.txt","w"); echo fwrite($nameofthefile,"Learning is fun"); fclose($nameofthefile); #the file that was created is opened in read mode using fopen function and the contents are read from the file using fread function and displayed as the output on the screenand then the file is closed using fclose function $filerad = fopen("filename.txt", "r"); echo fread($fileread, filesize("filename.txt")); fclose($fileread); #unlink function is used to delete the file that was just being read unlink("filename.txt"); #again we try to read the contents of the file that was just deleted using unlink function $fileread = fopen("filename.txt", "r"); echo fread($fileread, filesize("filename.txt")); fclose($fileread); ?> </body> </html>
輸出:
在上面的程式中,使用 fopen 函數以寫入模式開啟文件,並使用 fwrite 函數將內容寫入文件,然後使用 fclose 函數關閉文件。然後使用 fopen 函數以讀取模式開啟相同文件,並使用 fread 函數讀取文件的內容,並將文件的內容以及文件的大小作為輸出顯示在螢幕上,然後關閉文件使用 fclose 函數。然後我們使用 unlink 函數刪除同一個建立的檔案。然後,如果我們嘗試再次讀取已刪除的文件,螢幕上會顯示警告錯誤訊息。輸出如上面的快照所示。
在本文中,我們透過範例及其輸出了解了 unlink 函數的定義、語法、工作原理,了解了 PHP 中使用 unlink 函數刪除檔案的概念。
以上是PHP刪除文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!