Generate a stream resource based on Fopen in PHP 7.4, operate the disk, and adjust it to a memory-based implementation
1. In PHP 7.4, a stream resource is generated based on Fopen, and the disk is operated. The code is implemented as follows.
$tmp = tempnam(sys_get_temp_dir(), 'theme_asset_cdn_zip_stream');
$stream = fopen($tmp, 'w+');
var_dump(stream_get_meta_data($stream), $stream);
exit;
2. Print the result, as shown in Figure 1
array(9) {
["timed_out"]=>
bool(false)
["blocked"]=>
bool(true)
["eof"]=>
bool(false)
["wrapper_type"]=>
string(9) "plainfile"
["stream_type"]=>
string(5) "STDIO"
["mode"]=>
string(2) "w+"
["unread_bytes"]=>
int(0)
["seekable"]=>
bool(true)
["uri"]=>
string(46) "C:\Users\Lenovo\AppData\Local\Temp\the7A4D.tmp"
}
resource(2041) of type (stream)
3. Reference:https://www.php.net/manual/zh/resource.php, list of resource types. Use tmpfile — create a temporary file.
$stream = tmpfile();
var_dump(stream_get_meta_data($stream), $stream);
exit;
4. Print the result, as shown in Figure 2
array(9) {
["timed_out"]=>
bool(false)
["blocked"]=>
bool(true)
["eof"]=>
bool(false)
["wrapper_type"]=>
string(9) "plainfile"
["stream_type"]=>
string(5) "STDIO"
["mode"]=>
string(3) "r+b"
["unread_bytes"]=>
int(0)
["seekable"]=>
bool(true)
["uri"]=>
string(45) "C:\Users\Lenovo\AppData\Local\Temp\php14B.tmp"
}
resource(2041) of type (stream)
5. The main difference between the two is that after the script ends, search: C:\users\lenovo\appdata\local\temp\the7a4d.tmp, which exists. Search: C:\Users\Lenovo\AppData\Local\Temp\php14b.tmp, which has been automatically deleted. as shown in Figure 3
6. The parameter $filename of fopen supports the protocol, refer to:https://www.php.net/manual/zh/wrappers.php.php. Avoid manipulating disks based on php://memory implementation. php://memory and php://temp are a stream-like data stream that allows read and write temporary data. The only difference between the two is that php://memory always stores the data in memory, and php://temp will be stored in the temporary file after the memory amount reaches the predefined limit (default is 2MB). as shown in Figure 4
$stream = fopen('php://memory', 'w+');
var_dump(stream_get_meta_data($stream), $stream);
exit;
array(9) {
["timed_out"]=>
bool(false)
["blocked"]=>
bool(true)
["eof"]=>
bool(false)
["wrapper_type"]=>
string(3) "PHP"
["stream_type"]=>
string(6) "MEMORY"
["mode"]=>
string(3) "w+b"
["unread_bytes"]=>
int(0)
["seekable"]=>
bool(true)
["uri"]=>
string(12) "php://memory"
}
resource(2041) of type (stream)



