Delete PHP Temporary Files with unlink()

To remove temporary files uploaded in PHP, you can use the unlink() function to delete the file. The unlink() function is used to delete a file, and the syntax is as follows:

bool unlink ( string $filename [, resource $context ] )

$filename is the name of the file to be deleted, while $context is an optional parameter used for specifying the context (e.g., access control for network files).

Here is a sample code demonstrating how to delete uploaded temporary files.

if(isset($_FILES['file']['tmp_name'])){
    $tmp_file = $_FILES['file']['tmp_name'];
    if(file_exists($tmp_file)){
        unlink($tmp_file);
        echo '临时文件删除成功';
    } else {
        echo '临时文件不存在';
    }
}

In the example above, we first use the isset() function to check if a file has been uploaded, then we use the $_FILES superglobal variable to get the temporary file name of the uploaded file. Next, we use the file_exists() function to check if the temporary file exists, and if it does, we use the unlink() function to delete the temporary file and output the corresponding message.

Please note that the operation of deleting temporary files should be placed after handling the uploaded files to ensure that temporary files are not accidentally deleted before processing the files.

bannerAds