1

I'm writing a small extenstion for PHP. Is there way to know at runtime, the name of the script file (e.g.: test.php) that is running? Maybe some global or environment variables?

3 Answers 3

5

You can fetch $_SERVER['PHP_SELF'] (or any other $_SERVER variable if you need to), like this:

// This code makes sure $_SERVER has been initialized
if (!zend_hash_exists(&EG(symbol_table), "_SERVER", 8)) {
    zend_auto_global* auto_global;
    if (zend_hash_find(CG(auto_globals), "_SERVER", 8, (void **)&auto_global) != FAILURE) {
        auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC);
    }
}

// This fetches $_SERVER['PHP_SELF']
zval** arr;
char* script_name;
if (zend_hash_find(&EG(symbol_table), "_SERVER", 8, (void**)&arr) != FAILURE) {
    HashTable* ht = Z_ARRVAL_P(*arr);
    zval** val;
    if (zend_hash_find(ht, "PHP_SELF", 9, (void**)&val) != FAILURE) {
        script_name = Z_STRVAL_PP(val);
    }
}

The script_name variable will contain the name of the script.

In case you're wondering, the first block, that initializes $_SERVER, is necessary because some SAPIs (e.g.: the Apache handler) will initialize $_SERVER only when the user script accesses it (just-in-time). Without that block of code, if you try to read $_SERVER['PHP_SELF'] before the script tried accessing $_SERVER, you'd end up with an empty value.

Obviously, you should add error handling in the above code in case anything fails, so that you don't invoke undefined behavior when trying to access script_name.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this snippet: I was trying to initialize '_SERVER' by using 'zend_auto_global_disable_jit', but somehow it wasn't working. This also helped me confirm something I had found in another question: the hash find function needs the size of the key, including the terminating char, which wasn't the case for the 'disable_jit function. The question I was talking about is here:stackoverflow.com/questions/1906565/…
0

Try the variable $argv. The first item in that array contains the name of the script.

EDIT

For C the function

int main takes two paramters argc and argv (see here). The same still holds as above. i.e. argv[0] is the command name.

Comments

0

I tried this script, but it didn't work for me. The first statement:

if (!zend_hash_exists(&EG(symbol_table), "_SERVER", 8)

fails. I'm running PHP from the CLI. However, I did set variables through my PHP script and when I use print_r($_SERVER) through the same script I get a full array of values.

I think the negation in before the zend_hash_exists() is not necessary in this context.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.