Use $_SERVER['SCRIPT_NAME'] for the requested script path and basename() when only the filename is needed. Escape the value before printing it into HTML.
$script = basename($_SERVER['SCRIPT_NAME'] ?? '');
echo htmlspecialchars($script);This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
file = $_SERVER["SCRIPT_NAME"];
echo $file;
The above lines will print the present file name along with the directory name. For example if our current file is test.php and it is running inside my_file directory then the output of above code will be.
/my_file/test.php
We will add some more code to the above line to get the only file name from the above code. We will use explode command to break the string by using delimiter "/" .
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
Here $pfile is the variable which will have the value of present file name.
$file = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
echo $pfile;
The output is here
test.php
Another easy way is to use basename of pathinfo
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Hello, " . htmlspecialchars($_POST['name']);
}
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Marcel Burkhard | 08-07-2014 |
| How about just using the __LINE__ magic constant? | |