views:

150

answers:

4

I am trying to get the filename of the script that is running (But not the include it is calling).

echo basename(__FILE__); # will always output include.php

echo basename($_SERVER['SCRIPT_FILENAME']);
# This will do what I want (echo myscript.php), but I was wondering if there was
# a better way to grab it, as I have had problems with $_SERVER['SCRIPT_FILENAME']
# when running certain scripts from a cron.

Any suggestions?

<?
#myscript.php
require('include.php');
echo "Hello all";
?>

<?
#include.php
echo basename(__FILE__);
echo basename($_SERVER['SCRIPT_FILENAME']);
?>

Thanks!

A: 

I remember using '$_SERVER["SCRIPT_NAME"]' but have no idea if it has problem with corn.

NawaMan
I think you mean cron.
Matthew Scharley
But I like corn. :p
NawaMan
+2  A: 

You have to use $_SERVER['SCRIPT_NAME'], as explained in the reserved_variables man page

'SCRIPT_NAME' Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

AlberT
Just to let you know, for what ever reason, an older server I was using the $_SERVER['SCRIPT_FILENAME'] and possibly $_SERVER['SCRIPT_NAME'] was returning nothing when run via the cron. But I take your point about using SCRIPT_NAME over SCRIPT_FILENAME. So thanks
Lizard
$_SERVER["argv"][0] may have what you want also.
Neel
argv[0] is the script name as it is invoked by the cmd line, so the path included is absolute, relative ( path/name.php, ./path/name.php, etc) depending on __how__ you invoke the script. Moreover it could be undefined when not in cli environment
AlberT
+1  A: 

If you're using something `php -f /home/me/foo.php in your crontab (i.e. php-cli) you might also be interested in the $argv array. $argv[0] contains the path/name of the script initially passed to php.

VolkerK
Thanks that will be helpful! Not thought of using that for this scenario.
Lizard
A: 

When PHP is executed from the command line (likely how you have cron set up) SCRIPT_FILENAME will contain the path specified by the user. If your script is executed as ../myscript.php then that is the value you will get. Seeing as you are passing the value through basename() anyway, it should still suit your needs. What problems were you having with it exactly?

SCRIPT_NAME is another predefined variable to look at, but this will not always contain the absolute path to the executed file either.

Alex Barrett
Not really sure why it was happening or how, we have moved servers since then and everything working as expected now. Just wanted to check that the $_SERVER variable was the one I should be using.
Lizard