Skip to content

Fix GH-11982: str_getcsv returns null byte for unterminated enclosure #12047

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions ext/standard/file.c
Original file line number Diff line number Diff line change
Expand Up @@ -2017,7 +2017,14 @@ PHPAPI HashTable *php_fgetcsv(php_stream *stream, char delimiter, char enclosure
memcpy(tptr, line_end, line_end_len);
tptr += line_end_len;

/* nothing can be fetched if stream is NULL (e.g. str_getcsv()) */
if (stream == NULL) {
/* the enclosure is unterminated */
if (bptr > limit) {
/* if the line ends with enclosure, we need to go back by
* one character so the \0 character is not copied. */
--bptr;
}
goto quit_loop_2;
}

Expand All @@ -2028,6 +2035,11 @@ PHPAPI HashTable *php_fgetcsv(php_stream *stream, char delimiter, char enclosure
* assign all the data from the start of
* the enclosure to end of data to the
* last element */
if (bptr > limit) {
/* if the line ends with enclosure, we need to go back by
* one character so the \0 character is not copied. */
--bptr;
}
goto quit_loop_2;
}

Expand Down
29 changes: 29 additions & 0 deletions ext/standard/tests/file/fgetcsv_variation33.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
--TEST--
fgetcsv() with unterminated enclosure at the end of file
--FILE--
<?php
$contents = <<<EOS
"cell1","cell2"
"cell1","
EOS;
$stream = fopen('php://memory', 'w+');
fwrite($stream, $contents);
rewind($stream);
while (($data = fgetcsv($stream)) !== false) {
var_dump($data);
}
fclose($stream);
?>
--EXPECT--
array(2) {
[0]=>
string(5) "cell1"
[1]=>
string(5) "cell2"
}
array(2) {
[0]=>
string(5) "cell1"
[1]=>
string(0) ""
}
26 changes: 26 additions & 0 deletions ext/standard/tests/strings/gh11982.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
--TEST--
GH-11982 (str_getcsv returns null byte for unterminated quoted string)
--FILE--
<?php
var_dump(str_getcsv('"'));
var_dump(str_getcsv('"field","'));
var_dump(str_getcsv('"","a'));
?>
--EXPECT--
array(1) {
[0]=>
string(0) ""
}
array(2) {
[0]=>
string(5) "field"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(0) ""
[1]=>
string(1) "a"
}