Skip to content

Commit 84c18f9

Browse files
bitbaendigercmb69
authored andcommitted
Preserve file-position when php://temp switches to temporary file
Closes GH-8333.
1 parent 3aaf2f6 commit 84c18f9

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ PHP NEWS
1010
. Fixed bug GH-8267 (MySQLi uses unsupported format specifier on Windows).
1111
(cmb)
1212

13+
- Streams:
14+
. Fixed php://temp does not preserve file-position when switched to temporary
15+
file. (Bernd Holzmüller)
16+
1317
14 Apr 2022, PHP 8.0.18
1418

1519
- Core:
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
--TEST--
2+
BUG: php://temp does not preserve file-pointer once it switches from memory to temporary file
3+
--FILE--
4+
<?php
5+
6+
$f = fopen('php://temp/maxmemory:1024', 'r+');
7+
fwrite($f, str_repeat("1", 738));
8+
fseek($f, 0, SEEK_SET);
9+
fwrite($f, str_repeat("2", 512));
10+
11+
fseek($f, 0, SEEK_SET);
12+
var_dump(fread($f, 16));
13+
14+
fseek($f, 0, SEEK_END);
15+
var_dump(ftell($f));
16+
17+
?>
18+
--EXPECT--
19+
string(16) "2222222222222222"
20+
int(738)

main/streams/memory.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -375,10 +375,11 @@ static ssize_t php_stream_temp_write(php_stream *stream, const char *buf, size_t
375375
return -1;
376376
}
377377
if (php_stream_is(ts->innerstream, PHP_STREAM_IS_MEMORY)) {
378-
size_t memsize;
379-
char *membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize);
380-
381-
if (memsize + count >= ts->smax) {
378+
zend_off_t pos = php_stream_tell(ts->innerstream);
379+
380+
if (pos + count >= ts->smax) {
381+
size_t memsize;
382+
char *membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize);
382383
php_stream *file = php_stream_fopen_temporary_file(ts->tmpdir, "php", NULL);
383384
if (file == NULL) {
384385
php_error_docref(NULL, E_WARNING, "Unable to create temporary file, Check permissions in temporary files directory.");
@@ -388,6 +389,7 @@ static ssize_t php_stream_temp_write(php_stream *stream, const char *buf, size_t
388389
php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE);
389390
ts->innerstream = file;
390391
php_stream_encloses(stream, ts->innerstream);
392+
php_stream_seek(ts->innerstream, pos, SEEK_SET);
391393
}
392394
}
393395
return php_stream_write(ts->innerstream, buf, count);

0 commit comments

Comments
 (0)