How to get file name from url without $ _GET variable?

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;

the result is index.php?c=lorem-ipsum

How to get only file name ( index.php) without a variable $_GET, using array_popif possible?

+4
source share
4 answers

I will follow parse_url()as shown 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;
?>

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

Note: - checked with the given URL. Check the other type of URL at the end. thank.

+2
source

Another method that can get the file name is to use parse_url - Parses the URL and returns 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: , . . , .

+3

One way to do this would be to simply get the basename()file and then cross out the entire part of the query using a regular expression, or better yet, just pass the result $_SERVER['PHP_SELF']to a function basename(). Both give the same result, although the second 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
+2
source

Try this, not verified:

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

Source: https://habr.com/ru/post/1648214/


All Articles