Skip to content

Commit a524785

Browse files
committed
Clean up php_exec() implementation a bit
1 parent d6a19ba commit a524785

File tree

1 file changed

+27
-34
lines changed

1 file changed

+27
-34
lines changed

ext/standard/exec.c

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,28 @@ PHP_MINIT_FUNCTION(exec)
8181
}
8282
/* }}} */
8383

84+
static size_t strip_trailing_whitespace(char *buf, size_t bufl) {
85+
size_t l = bufl;
86+
while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
87+
if (l != (bufl - 1)) {
88+
bufl = l + 1;
89+
buf[bufl] = '\0';
90+
}
91+
return bufl;
92+
}
93+
94+
static void handle_line(int type, zval *array, char *buf, size_t bufl) {
95+
if (type == 1) {
96+
PHPWRITE(buf, bufl);
97+
if (php_output_get_level() < 1) {
98+
sapi_flush();
99+
}
100+
} else if (type == 2) {
101+
bufl = strip_trailing_whitespace(buf, bufl);
102+
add_next_index_stringl(array, buf, bufl);
103+
}
104+
}
105+
84106
/* {{{ php_exec
85107
* If type==0, only last line of output is returned (exec)
86108
* If type==1, all lines will be printed and last lined returned (system)
@@ -92,7 +114,6 @@ PHPAPI int php_exec(int type, char *cmd, zval *array, zval *return_value)
92114
{
93115
FILE *fp;
94116
char *buf;
95-
size_t l = 0;
96117
int pclose_return;
97118
char *b, *d=NULL;
98119
php_stream *stream;
@@ -139,45 +160,17 @@ PHPAPI int php_exec(int type, char *cmd, zval *array, zval *return_value)
139160
bufl += b - buf;
140161
}
141162

142-
if (type == 1) {
143-
PHPWRITE(buf, bufl);
144-
if (php_output_get_level() < 1) {
145-
sapi_flush();
146-
}
147-
} else if (type == 2) {
148-
/* strip trailing whitespaces */
149-
l = bufl;
150-
while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
151-
if (l != (bufl - 1)) {
152-
bufl = l + 1;
153-
buf[bufl] = '\0';
154-
}
155-
add_next_index_stringl(array, buf, bufl);
156-
}
163+
handle_line(type, array, buf, bufl);
157164
b = buf;
158165
}
159166
if (bufl) {
160-
/* output remaining data in buffer */
161-
if (type == 1 && buf != b) {
162-
PHPWRITE(buf, bufl);
163-
if (php_output_get_level() < 1) {
164-
sapi_flush();
165-
}
166-
}
167-
/* strip trailing whitespaces if we have not done so already */
168-
if ((type == 2 && buf != b) || type != 2) {
169-
l = bufl;
170-
while (l-- > 0 && isspace(((unsigned char *)buf)[l]));
171-
if (l != (bufl - 1)) {
172-
bufl = l + 1;
173-
buf[bufl] = '\0';
174-
}
175-
if (type == 2) {
176-
add_next_index_stringl(array, buf, bufl);
177-
}
167+
if (buf != b) {
168+
/* Process remaining output */
169+
handle_line(type, array, buf, bufl);
178170
}
179171

180172
/* Return last line from the shell command */
173+
bufl = strip_trailing_whitespace(buf, bufl);
181174
RETVAL_STRINGL(buf, bufl);
182175
} else { /* should return NULL, but for BC we return "" */
183176
RETVAL_EMPTY_STRING();

0 commit comments

Comments
 (0)