Create temporary file and auto removed

mrblue picture mrblue · Nov 22, 2009 · Viewed 19.9k times · Source

I am writing a anti-leeching download script, and my plan is to create a temporary file, which is named by session ID, then after the session expires, the file will be automatically deleted. Is it possible ? And can you give me some tips how to do that in PHP ?

Thanks so much for any reply

Answer

TheGrandWazoo picture TheGrandWazoo · Nov 22, 2009

PHP has a function for that name tmpfile. It creates a temporary file and returns a resource. The resource can be used like any other resource.

E.g. the example from the manual:

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

The file is automatically removed when closed (using fclose()), or when the script ends. You can use any file functions on the resource. You can find these here. Hope this will help you?

Another solution would be to create the file in the regular way and use a cronjob to regular check if a session is expired. The expiration date and other session data could be stored in a database. Use the script to query that data and determine if a session is expired. If so, remove it physically from the disk. Make sure to run the script once an hour or so (depending on your timeout).