Php read temporary file

tmpfile

Creates a temporary file with a unique name in read-write-binary (w+b) mode and returns a file handle.

The file is automatically removed when closed (for example, by calling fclose() , or when there are no remaining references to the file handle returned by tmpfile() ), or when the script ends.

If the script terminates unexpectedly, the temporary file may not be deleted.

Parameters

This function has no parameters.

Return Values

Returns a file handle, similar to the one returned by fopen() , for the new file or false on failure.

Examples

Example #1 tmpfile() example

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

The above example will output:

See Also

  • tempnam() — Create file with unique file name
  • sys_get_temp_dir() — Returns directory path used for temporary files

User Contributed Notes 7 notes

To get the underlying file path of a tmpfile file pointer:

$file = tmpfile ();
$path = stream_get_meta_data ( $file )[ ‘uri’ ]; // eg: /tmp/phpFx0513a

I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no «file» to upload, this solved the problem nicely:

# Upload setup.inc
$fSetup = tmpfile ();
fwrite ( $fSetup , $setup );
fseek ( $fSetup , 0 );
if (! ftp_fput ( $ftp , «inc/setup.inc» , $fSetup , FTP_ASCII )) echo «
Setup file NOT inserted

» ;
>
fclose ( $fSetup );
?>

The $setup variable is the contents of the textarea.

And I’m not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn’t effect it.

Since this function may not be working in some environments, here is a simple workaround:

function temporaryFile($name, $content)
$file = DIRECTORY_SEPARATOR .
trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) .
DIRECTORY_SEPARATOR .
ltrim($name, DIRECTORY_SEPARATOR);

register_shutdown_function(function() use($file) unlink($file);
>);

at least on Windows 10 with php 7.3.7, and Debian Linux with php 7.4.2,

the mode is not (as the documentation states) ‘w+’ , it is ‘w+b’

(an important distinction when working on Windows systems)

To get tmpfile contents:
$tmpfile = tmpfile ();
$tmpfile_path = stream_get_meta_data ( $tmpfile )[ ‘uri’ ];
// . write to tmpfile .
$tmpfile_content = file_get_contents ( $tmpfile_path );
?>

Perhaps not the best way for production code, but good enough for logging or a quick var_dump() debug run.

No, the fseek() is necessary — after writing to the file, the file pointer (I’ll use «file pointer» to refer to the current position in the file, the thing you change with fseek()) is at the end of the file, and reading at the end of the file gives you EOF right away, which manifests itself as an empty upload.

Where you might be getting confused is in some systems’ requirement that one seek or flush between reading and writing the same file. fflush() satisfies that prerequisite, but it doesn’t do anything about the file pointer, and in this case the file pointer needs moving.

Beware that PHP’s tmpfile is not an equivalent of unix’ tmpfile.
PHP (at least v. 5.3.17/linux I’m using now) creates a file in /tmp with prefix «php», and deletes that file on fclose or script termination.
So, if you want to be sure that you don’t leave garbage even in case of a fatal error, or killed process, you shouldn’t rely on this function.
Use the classical method of deleting the file after creation:
$fn = tempnam ( ‘/tmp’ , ‘some-prefix-‘ );
if ( $fn )
$f = fopen ( $fn , ‘w+’ );
unlink ( $fn ); // even if fopen failed, because tempnam created the file
if ( $f )
do_something_with_file_handle ( $f );
>
>
?>

Источник

Techniques for Efficient Memory Usage while Reading Files in PHP

The script I used was effective as it enabled me to download a zip file without requiring the actual files or saving the zip file. To serve files directly through your web server (Apache), ensure that the image file is located in its designated folder, which is usually the «public» folder in a Zend Framework application.

How to save memory when reading a file in Php?

echo memory_get_usage(), PHP_EOL; // 333200 $file = new SplFileObject('bible.txt'); // 996kb $file->seek(5000); // jump to line 5000 (zero-based) echo $file->current(), PHP_EOL; // output current line echo memory_get_usage(), PHP_EOL; // 342984 vs 3319864 when using file() 

To display the current line, you have two options: either use current() or simply echo $file . Personally, I prefer the former method for clarity. Alternatively, you can utilize fgets() to obtain the following line.

The middle three lines are sufficient. The memory_get_usage calls are included as evidence that this method consumes minimal memory.

To locate a specific line, you must read through every line until you find it, unless you already know the offset. To discard irrelevant lines, you can use a loop to go through the file, as shown in fgets() . (Note: @Gordon’s approach is preferable to using fgets() .)

One probable alternative could be to utilize a database, which would relieve you of the burden of storing the strings and enable you to easily retrieve a specific «line» (although it would be a record with a numerical ID). This would eliminate the need to go through the previous records.

If the file’s contents remain constant or change only occasionally, it’s possible to create a list of offsets specifying where to read the data. For example, if the file changes once a year but is read frequently throughout the day, pre-calculating the offsets of the desired lines and jumping directly to them is a viable option.

 $offsets = array(); while ($line = fread($filehandle)) < . find line 10 . >$offsets[10] = ftell($filehandle); // store line 10's location . find next line $offsets[20] = ftell($filehandle); 

Following that, it is easy to navigate to the position of the mentioned line using this method.

 $fh = fopen('file.txt', 'rb'); fseek($fh, $offsets[20]); // jump to line 20 

However, it is possible that this may be excessive. Conduct a benchmark analysis by comparing the time it takes to perform a traditional «read 20 lines» operation with that of precomputing/jumping.

Php save file temporary in memory Code Example, php file_get_contents disable ssl check. Warning: file_get_contents (): Failed to enable crypto in. php get latest file in directory. check image is available on server php. take files from one folder and move to another folder in php. php current file name. know php file name. create and download text file in php.

Phpqrcode — save file to temporary directory

Your browser is unable to locate the image at the specified URL «http://domain.tld/temptest.png». The location it is searching for is «/Applications/MAMP/htdocs/surveyanyplace/site/public/temptest.png» on your disk, but the file was not saved there. You have noticed that it is actually saved at «/temptest.png».

To serve files through your Apache web server, it is important to ensure that the image file is located within its designated directory, which is usually the «public» folder of your Zend Framework application.

To modify $pngAbsoluteFilePath and $urlRelativeFilePath , you can create a new directory at /Applications/MAMP/htdocs/surveyanyplace/site/public/qrcodecaches.

$pngAbsoluteFilePath = APPLICATION_PATH . '/../public/qrcodecaches/' . $fileName; $urlRelativeFilePath = '/qrcodecaches/' . $fileName; 

It is possible to eliminate $tempDir from the system.

Please consider referring to Zend_View_Helper_BaseUrl for enhancing the portability of $urlRelativeFilePath in scenarios where applications are nested inside subdirectories.

Php — Writing files to temporary locations, php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit … Code sample$tmp_handle = fopen(‘php://temp’, ‘r+’);fwrite($tmp_handle, ‘my awesome text to be emailed’);rewind($tmp_handle);$file_contents = stream_get_contents($tmp_handle);fclose($tmp_handle);Feedback

Manipulate an Archive in memory with PHP (without creating a temporary file on disk)

After facing a similar issue, I managed to discover a solution that was relatively hard to come by and thought it would be beneficial to share it on this platform.

While browsing through the «libraries» directory, I stumbled upon the impressive zip.lib.php / unzip.lib.php scripts that come with phpmyadmin .

I found that implementing zip.lib.php was highly effective.

require_once(LIBS_DIR . 'zip.lib.php'); . //create the zip $zip = new zipfile(); //add files to the zip, passing file contents, not actual files $zip->addFile($file_content, $file_name); . //prepare the proper content type header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=my_archive.zip"); header("Content-Description: Files of an applicant"); //get the zip content and send it back to the browser echo $zip->file(); 

With this script, there is no requirement of having the files as actual files or saving the zip as a file, but you can still download the zip.

It’s unfortunate that this feature isn’t included in a broader PHP toolkit.

This is the zip.lib.php file from the phpMyAdmin source, and you can access it at the following link: https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php.

Ensure to eliminate the initial verification in zip.lib.php to prevent abrupt termination of the script.

The updated version of this code can also be found in the CodeIgniter project repository at the following link: https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php.

Have you considered using either the stream php://temp or php://memory for reading and writing to/from the archive?

Visit the URL http://php.net/manual/en/wrappers.php.php.

As for your feedback that php://temp is functional except for when it’s closed, you can try leaving it open, flushing the output, resetting it to 0, and then reading it.

Refer to this link for additional illustrations: http://us.php.net/manual/en/function.tmpfile.php.

Additionally, investigate the techniques of output buffering and capturing by referring to the documentation available at http://us.php.net/manual/en/function.ob-start.php.

How to save memory when reading a file in Php?, Unless you know the offset of the line, you will need to read every line up to that point. You can just throw away the old lines (that you don’t want) by looping through the file with something like fgets(). (EDIT: Rather than fgets(), I would suggest @Gordon’s solution). Possibly a better solution would be to use a …

Load a ‘php://temp’ or ‘php://memory’ file within a Symfony File object

It is believed that php://temp writes to memory and then switches to writing to a file when the memory becomes full. On the other hand, php://memory only writes to memory without any fallback options.

It is probable that this occurs due to the fact that php://temp and php://memory cannot be reused. Therefore, once you have written to them, the content may not persist when you need it again. This information is provided by the PHP manual.

The streams php://memory and php://temp cannot be reused, meaning that once they have been closed, they cannot be referenced again.

file_put_contents('php://memory', 'PHP'); echo file_get_contents('php://memory'); // prints nothing 

Before focusing on Symfony’s File class, it’s crucial to determine how you’ll communicate with php://temp . It’s likely that php://temp will have expired by the time you create an instance of File .

It is important to mention that when utilizing php://temp , a file will be generated in the temporary location on the disk. Therefore, it is recommended to use write to a tempnam() handle instead. This way, you will have a reference to a physical file, albeit temporary.

I proposed the idea of passing the file’s data directly to Symfony’s MIME type guesser instead of just the file path. This would allow for on-the-fly guessing and is discussed further on the following GitHub issue: https://github.com/symfony/symfony/issues/40916.

Here’s how I do it right now:

use Symfony\Component\Mime\MimeTypes; $tmpFilename = tempnam(sys_get_temp_dir(), 'guessMimeType_'); file_put_contents($tmpFilename, $content); $mimeTypes = new MimeTypes(); $guessedMimeType = $mimeTypes->guessMimeType($tmpFilename); unlink($tmpFilename); 

The source of the initial statement is cited as https://www.php.net/manual/en/function.tempnam.php#93256.

Php — phpqrcode — save file to temporary directory, I’m trying to create a QR-code with the php library phpqrcode. I want to save the file in a temporary file so I can use it afterwards. Something like this. I’m using the Zend Framework and want to use the temporary directory. This is what I have so far:

Источник

Читайте также:  Document
Оцените статью