My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Best practices for using a tmp directory in a PHP class?

Deactivated User's photo
Deactivated User
·May 19, 2016

Hello,

I am writing an application that downloads some files from the internet and then parses them.

Currently I generate a random session token and make a ./tmp/{SESSION_TOKEN} directory (by session I mean the session of running the script). This happens during bootstrapping phase.

Then I pass this directory around to classes that need it (as a dependency), basically telling them "hey, this a directory where you can do your stuff".

Now I am not happy with this, because I have to clean up after the application finishes. Sometimes it may end prematurely, therefore leaving the directory. Also, I create it during bootstrapping phase, but there is no equivalent during the termination of the application.

So my question is: How do you manage temporary directories in a class that needs it?.

I'm looking to find a clean, simple, sustainable way. I'm trying to write decoupled classes, so at first passing the directory as dependency seemed like a good idea. Now it does not.

Do you use functions like sys_get_temp_dir and tmpfile, tempnam and are they reliable? Is it good to do this temporary stuff inside the class itself or should receive just the content/file path?