- char *php_ini_file_name = NULL;
- char *php_ini_search_path = NULL;
-+ // value for php_ini_loaded_file() to be stored into php_ini_opened_path
-+ char *php_ini_loaded_file = NULL;
- int php_ini_scanned_path_len;
- char *open_basedir;
- int free_ini_search_path = 0;
-@@ -561,8 +568,29 @@
- }
- }
- }
-+ /* Search (global) php.ini file in search path */
-+ if (!fh.handle.fp) {
-+ fh.handle.fp = php_fopen_with_path("php.ini", "r", php_ini_search_path, &php_ini_opened_path TSRMLS_CC);
-+ if (fh.handle.fp) {
-+ fh.filename = php_ini_opened_path;
-+
-+ // parse the ini file now
-+ PG(open_basedir) = open_basedir;
-+ fh.type = ZEND_HANDLE_FP;
-+ zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t) php_ini_parser_cb, &configuration_hash TSRMLS_CC);
-+ open_basedir = PG(open_basedir);
-+ PG(open_basedir) = NULL;
-+ fh.handle.fp = NULL;
-
-- /* Otherwise search for php-%sapi-module-name%.ini file in search path */
-+ // save this for later
-+ php_ini_loaded_file = estrdup(php_ini_opened_path);
-+
-+ efree(php_ini_opened_path);
-+ fh.filename = php_ini_opened_path = NULL;
-+ }
-+ }
-+
-+ /* Also search for php-%sapi-module-name%.ini file in search path */
- if (!fh.handle.fp) {
- const char *fmt = "php-%s.ini";
- char *ini_fname;
-@@ -594,15 +601,12 @@
- if (fh.handle.fp) {
- fh.filename = opened_path->val;
- }
-- }
-
-- /* If still no ini file found, search for php.ini file in search path */
-- if (!fh.handle.fp) {
-- fh.handle.fp = php_fopen_with_path("php.ini", "r", php_ini_search_path, &opened_path);
-- if (fh.handle.fp) {
-- fh.filename = opened_path->val;
-- }
-- }
-+ // restore previous value, so php_ini_loaded_file() works as expected
-+ if (php_ini_loaded_file) {
-+ php_ini_opened_path = php_ini_loaded_file;
-+ }
-+ }
- }
-
- if (free_ini_search_path) {
-@@ -597,6 +622,10 @@
-
- {
- zval tmp;
-+ // use main php.ini if loaded
-+ if (php_ini_loaded_file) {
-+ fh.filename = php_ini_loaded_file;
-+ }
-
- Z_STRLEN(tmp) = strlen(fh.filename);
- Z_STRVAL(tmp) = zend_strndup(fh.filename, Z_STRLEN(tmp));
-@@ -630,13 +659,15 @@