If I have PHP script, how can I get the filename from inside that script?
Also, given the name of a script of the form jquery.js.php
, how can I extract just the "jquery.js" part?
If I have PHP script, how can I get the filename from inside that script?
Also, given the name of a script of the form jquery.js.php
, how can I extract just the "jquery.js" part?
Let's say you have two files a.php
and b.php
on same folder.
Code on the file b.php
<?php
echo "hi";
?>
and code on a.php
<?php
$data = file_get_contents('b.php');
echo $data;
You access a.php
on browser.
What do you see? A blank page.
Please check the page source now. It is there.
But not showing in browser as <?php
is not a valid html tag. So browser can not render it properly to show as output.
<?php
$data = htmlentities(file_get_contents('b.php'));
echo $data;
Now you can see the output in browser.
You can investigate script collection at:
var scripts = document.getElementsByTagName("script");
For each element in the returned scripts
array you can access its src
attribute.
The currently executing include file will always be the last one in the scripts
array. So you can access it at scripts[scripts.length-1]
.
Of course this will only work at time of initial code run and would not be useful for example within a function that is called after initial script is loaded, so if you need the value available later, you would need to save it to a variable.
You probably want to try the PHP Tokenizer.
http://www.php.net/manual/en/ref.tokenizer.php
From an external script:
<?php
var_dump(token_get_all(file_get_contents('myscript.php')));
?>
// With help from huynhjl
// http://.com/questions/8129185#8131613
import scala.util.matching.Regex.MatchIterator
object ScriptName {
val program = {
val filenames = new RuntimeException("").getStackTrace.map { t => t.getFileName }
val scala = filenames.indexOf("NativeMethodAccessorImpl.java")
if (scala == -1)
"<console>"
else
filenames(scala - 1)
}
def main(args: Array[String]) {
val prog = program
println("Program: " + prog)
}
}
Rosetta Code
Just use the PHP magic constant
__FILE__
to get the current filename.But it seems you want the part without
.php
. So...A more generic file extension remover would look like this...
Using standard string library functions is much quicker, as you'd expect.