File create in memory without disk storage using PHP. Create file in memory using PHP sys_get_temp_dir() funtion, without use of disk storage. File create in memory with example code snippet.
PHP have great featured functions. sys_get_temp_dir() is one of them, it returns directory path used for temporary files. By using temporary files path, we able to generate file in memory and use it in process.
Here given sample code first prepare filename with temporary files path, second it create file there, use in process and remove file from memory.
Why File create in memory without disk storage required
When you not want to use disk storage in PHP file process. For example you want to run file process code in Docker image + AWS environment, where you not use storage for dynamic scaling.
Steps for file create in memory without disk storage
- Prepare file path(temporary file) and name using sys_get_temp_dir()
- Create and write content in file.
- Use file in process e.g., send as attachment, upload to FTP
- Remove file from memory after use
PHP code snippet for file create in memory without disk storage
<?php $filename = 'Myfile.txt'; $fileInMemory = sys_get_temp_dir().'/'.$filename; //create file $myfile = fopen($fileInMemory, 'w'); $txt = 'This is myfile.\n'; fwrite($myfile, $txt); fclose($myfile); //use file here //$fileInMemory is your file with path to use. //attach with mail //upload to FTP //etc., //remove file from memory unlink($fileInMemory); ?>