File create in memory without disk storage using PHP

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.

File create in memory without disk storage using PHP
File create in memory without disk storage using PHP

Steps for file create in memory without disk storage

  1. Prepare file path(temporary file) and name using sys_get_temp_dir()
  2. Create and write content in file.
  3. Use file in process e.g., send as attachment, upload to FTP
  4. Remove file from memory after use
  5. 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);
    
    ?>