Создать временный файл на php

PHP Create Temp File

Summary: in this tutorial, you will learn how to use the PHP tmpfile() and tempnam() functions to create a temporary file.

Introduction to the temp file

A temporary file only exists during the execution of the script. It means that PHP automatically deletes the temporary file when the script ends.

To create a temporary file, you use the tmpfile() function:

tmpfile ( ) : resource|falseCode language: JavaScript (javascript)

The tmpfile() function creates a temporary file in a read/write ( w+ ) mode. The tmpfile() function returns the filehandle. If the function fails to create the file, it returns false .

Note that the tmpfile() function creates a temporary file with a unique name.

In fact, PHP automatically deletes the temporary file created by the tmpfile() function:

  • When you close the file by calling the fclose() function.
  • When the file handle doesn’t have any references.
  • or when the script ends.

PHP tmpfile() function example

The following example uses the tmpfile() function to create a new temporary file and write a text to it:

 $f = tmpfile(); if (false !== $f) < // write some text to the file fputs($f, 'The current time is ' . strftime('%c')); > echo 'The current time is ' . strftime('%c'); exit(1); Code language: HTML, XML (xml)
  • First, create a new temporary file using the tmpfile() function.
  • Second, write a string to the file using the fputs() function.

The tempnam() function

The tempnam() function creates a temporary file in a directory and returns the full path to the temporary file:

tempnam ( string $directory , string $prefix ) : string|falseCode language: PHP (php)

The tempnam() function has two parameters.

  • $directory is the directory of the temporary file. If the directory doesn’t exist or isn’t writable, the tempnam() creates the temporary file in the system temporary directory specified by the TMPDIR environment variable on Unix or the TMP environment variable on Windows.
  • $prefix is the prefix of the temporary file name.

The following example shows how to use the tempnam() function to create a temporary file in the tmp directory:

 $name = tempnam('tmp', 'php'); // full path to the temp file echo $name; //C:\xampp\htdocs\tmp\phpA125.tmp // open the temporary file $f = fopen($name, 'w+'); if ($f) < // write a text to the file fputs($f, 'the current time is ' . strftime('%c')); fclose($f); >Code language: HTML, XML (xml)

In this example, if you pass an empty string to the directory, the tempnam() function will create the temporary file in the system temporary directory e.g., on Windows, it is: C:\Users\\AppData\Local\Temp\php778.tmp

Summary

  • Use the tmpfile() function to create a temporary file that exists only during the execution of the script.
  • Use the tmpname() function to create a temporary file in a directory and return the full path of the file.

Источник

PHP tmpfile() Function

Create a temporary file with a unique name in read-write (w+) mode:

fwrite($temp, «Testing, testing.»);
//Rewind to the start of file
rewind($temp);
//Read 1k from file
echo fread($temp,1024);

//This removes the file
fclose($temp);
?>

The output of the code above will be:

Definition and Usage

The tmpfile() function creates a temporary file with a unique name in read-write (w+) mode.

Note: The file is automatically removed when closed, with fclose() or when the script ends.

Tip: See also the tempnam() function.

Syntax

Technical Details

Return Value: A file handle (similar to the one returned by fopen() for the new file), FALSE on failure
PHP Version: 4.0+

❮ PHP Filesystem Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Create temporary file and auto removed

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

Could you please be more specific about what you are trying to achieve? Anti-Leeching DL Script is a bit vague. What is the UseCase or problem the script is trying to solve?

Hi lkke, I just want to let the user download in his/her session only, like he can’t simply copy & paste the link to somebody else Hi Gordon, I want to force the users to download files from my site, control the speed. So, I think to create a temporary file in a temporary directory in HTTP docs so user can download them and then removed them (automatically) after session expires

7 Answers 7

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:

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).

I don’t think that’s a solution for mrblue’s question cause the file is deleted on script end/fclose() and not when the session expires.

You’re right I guess. Must have been reading over that part. Added more information to my post. It’s now up to him 😉

Hi TheGrandWazoo, thanks for your answer. I have thought about that solution, but it couldn’t be possible due toe the performance issue if the site scales up and Philippe is right, my concern is that PHP supports «hook» function, like automatically called after the session expires or starts.

There is no need to involve a database when using a cronjob. When the dl files share the name of the session file for this user, the script called by cron just has to remove all dl files for which currently no sessionfile exists.

So we have one or more files available for download. Creating a temporary file for each download requests is not a good idea. Creating a symlink() for each file instead is a much better idea. This will save loads of disk space and keep down the server load.

Naming the symlink after the user’s session is a decent idea. A better idea is to generate a random symlink name & associate with the session, so the script can handle multiple downloads per session. You can use session_set_save_handler() (link) and register a custom read function that checks for expired sessions and removes symlinks when the session has expired.

Hi Philippe, Yes, I really want to user $_SESSION (actually I did), but I can’t find any document or topic to mention about something, like «hook» action, for example: we can make a function that the system automatically called after a session expire or start. That is my idea and concern. Thank for your time

go the other way. react when a new session is created (eg. $_SESSION is empty and you filled it previously), not when a session expires. the problem is, a session can expire without any action taken by the user (session is out of date and removed by the garbage collector). what are you trying to do exactly?

Ok, so we have the following requirements so far

  1. Let the user download in his/her session only
  2. no copy & paste the link to somebody else
  3. Users have to download from the site, e.g. no hotlinking
  4. Control speed

Let’s see. This is not working code, but it should work along these lines:

Hi Gordon, That is nearly 90% that what I was writing in my code, but yours have a better security check with token. Much appreciated for that.

The token adds security, but it also makes that you dont have to symlink or copy your files anymore, because the token is unique for session+file. The token is basically what pygorex1 would create for a symlink name. Just instead of creating a symlink from it which you later would have to remove somehow, you just send the name/token with the regular fileId. Less maintenance.

I’d suggest you not to copy the file in the first place. I’d do the following: when user requests the file, you generate a random unique string to give him the link this way: dl.php?k=hd8DcjCjdCkk123 then put this string to a database, storing his IP address, maybe session and the time you’ve generated the link. Then another user request that file, make sure all the stuff (hash, ip and so on) matches and the link is not expired (e.g. not more that N hours have passed since the generation) and if everything is OK, use PHP to pipe the file. Set a cron job to look through the DB and remove the expired entries. What do you think?

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle. The file is automatically removed when closed (using fclose()), or when the script ends.

I don’t think that’s a solution for mrblue’s question cause the file is deleted on script end/fclose() and not when the session expires.

Hi roddik, Philippe was right, I thought about that solution, but it is not applicable in my circumstance especially the performance issue

Maybe it’s to late for answering but I’m try to share on feature googlize!

if you use CPanel there is a short and quick way for blocking external request on your hosted files which name is: HotLink.

you can Enable HotLinks on you Cpanel and be sure nobody can has request o your file from another hosting or use your files as a download reference.

To acheive this, I would make one file and protect it using chmod — making it unavailable to the public. Or, alternatively, save the contents in a database table row, fetch it whenever required.

Making it downloadable as a file. To do so, I would get the contents from the protected file, or if it is stored in a database table, fetch it and simply output it. Using php headers, I would, give it a desired name, extension, specify it’s type, and finally force the browser to download the output as a solid file.

This way, you only need to save data in one place either, in a protected file or in database. Force client browser to download it as many times as the the conditions meet e.g., as long as the user is logged-in and so on. Without having to worry about the disk space, making any temp file, cronJobs and or auto-deletion of the file.

Источник

Читайте также:  Steam bot api python
Оцените статью