4
http://localhost/mc/site-01-up/index.php?c=lorem-ipsum

$address = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$stack = explode('/', $_SERVER["REQUEST_URI"]);
$file = array_pop($stack);
echo $file;

result - index.php?c=lorem-ipsum

How to get just file name (index.php) without $_GET variable, using array_pop if possible?

qadenza
  • 8,611
  • 18
  • 61
  • 108

5 Answers5

3

Another method that can get the filename is by using parse_url — Parses a URL and return its components

<?php
$url = "http://localhost/mc/site-01-up/index.php?c=lorem-ipsum";
$data = parse_url($url);
$array = explode("/",$data['path']);
$filename = $array[count($array)-1];
var_dump($filename);

Result

index.php

EDIT: Sorry for posting this answer as it is almost identical to the selected one. I didnt see the answer so posted. But I cannot delete this as it is seen as a bad practice by moderators.

Amit Ray
  • 3,425
  • 2
  • 18
  • 34
2

One way of doing it would be to simply get the basename() of the file and then strip-out all the Query Part using regex or better still simply do pass the $_SERVER['PHP_SELF'] result to the basename() Function. Both will yield the same result though the 2nd approach seems a little more intuitive.

<?php

    $fileName  = preg_replace("#\?.*$#", "", basename("http://localhost/mc/site-01-up/index.php?c=lorem-ipsum"));
    echo $fileName;  // DISPLAYS: index.php

    // OR SHORTER AND SIMPLER:
    $fileName   = basename($_SERVER['PHP_SELF']);
    echo $fileName;  // DISPLAYS: index.php
Poiz
  • 7,519
  • 2
  • 13
  • 17
2

Try this, not tested:

    $file = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $file);
    $file = $parts[count($parts) - 1];
    echo $file;
Muhammad Shahzad
  • 8,624
  • 20
  • 79
  • 128
2

I will follow parse_url() like below (easy to understand):-

<?php
$url = 'http://localhost/mc/site-01-up/index.php?c=lorem-ipsum';

$url=   parse_url($url);
print_r($url); // to check what parse_url() will outputs
$url_path = explode('/',$url['path']); // explode the path part
$file_name =  $url_path[count($url_path)-1]; // get last index value which is your desired result

echo $file_name;
?>

Output:- https://eval.in/606839

Note:- tested with your given URL. Check for other type of URL's at your end. thanks.

Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94
0

If you are trying to use the GET method without variable name, another option would be using the $_SERVER["QUERY_STRING"]

http://something.com/index.php?=somestring

$_SERVER["QUERY_STRING"] would return "somestring"