|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2005-12-08 03:56 UTC] rabbitt at gmail dot com
 Description:
------------
Without long options built into zif_getopt(), zif_getopt()'s calls to getopt() will only return a populated result once. The reason for this is that 'optind' does not get reset on each call to getopt(). optind is used to keep track of the most option processed internally in getopt(). Once getopt() has finished processing the options, optind remains at the last value it was set to (typically, at this point, optind == argc). 
The problem with this is that when getopt() is called a second time, it thinks that it's already finished with processing the options due to optind being equal to argc. Worse still, with long optoins built in (-DHARTMUT_0), it causes a segfault in glibc's getopt.c (function: _getopt_internal_r() - line 521 specifically).
Reproduce code:
---------------
create file called test.php and add:
<?php
    print_r(@getopt('t', array('test')));
    print_r(@getopt('t', array('test')));
?>
then run: 
php test.php -t
Expected result:
----------------
Array
(
    [t] =>
)
Array
(
    [t] =>
)
Actual result:
--------------
One of two things will happen:
Array
(
    [t] =>
)
Array
(
)
or:
Array
(
)
Segmentation fault (core dumped)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 13:00:01 2025 UTC | 
The following patch appears to fix the problem: --- ext/standard/basic_functions.c 2005-12-07 20:41:49.000000000 -0500 +++ ext/standard/basic_functions.c 2005-12-07 20:44:59.000000000 -0500 @@ -1597,6 +1597,9 @@ /* Disable getopt()'s error messages. */ opterr = 0; + /* Force reinitialization of getopt() (via optind reset) on every call. */ + optind = 0; + /* Invoke getopt(3) on the argument array. */ #ifdef HARTMUT_0 while ((o = getopt_long(argc, argv, options, longopts, &longindex)) != -1) {