Viewed   55 times

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?



Just use the PHP magic constant __FILE__ to get the current filename.

But it seems you want the part without .php. So...

basename(__FILE__, '.php'); 

A more generic file extension remover would look like this...

function chopExtension($filename) {
    return pathinfo($filename, PATHINFO_FILENAME);

var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('')); // string(15) "bob.i.have.dots"

Using standard string library functions is much quicker, as you'd expect.

function chopExtension($filename) {
    return substr($filename, 0, strrpos($filename, '.'));
Saturday, November 19, 2022

Let's say you have two files a.php and b.php on same folder.

Code on the file b.php


echo "hi";


and code on a.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.

$data = htmlentities(file_get_contents('b.php'));
echo $data;

Now you can see the output in browser.

Sunday, September 11, 2022

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.

Sunday, October 16, 2022

You probably want to try the PHP Tokenizer.

From an external script:



Thursday, December 8, 2022
// With help from huynhjl
// http://.com/questions/8129185#8131613

import scala.util.matching.Regex.MatchIterator

object ScriptName {
    val program = {
        val filenames = new RuntimeException("") { t => t.getFileName }
        val scala = filenames.indexOf("")

        if (scala == -1)
            filenames(scala - 1)

    def main(args: Array[String]) {
        val prog = program
        println("Program: " + prog)

Rosetta Code

Tuesday, August 2, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :