Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

url

php

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?

like image 468
qadenza Avatar asked Jan 05 '23 16:01

qadenza


2 Answers

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.

like image 190
Amit Ray Avatar answered Jan 15 '23 08:01

Amit Ray


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.

like image 34
Anant Kumar Singh Avatar answered Jan 15 '23 10:01

Anant Kumar Singh