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?

3

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

Try this, not tested:

    $file = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $file);
    $file = $parts[count($parts) - 1];
    echo $file;

Comments

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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.