Get only filename from url in php without any vari

2019-01-14 20:23发布

I want to get filename without any $_GET variable values from a url in php?

My url is http://learner.com/learningphp.php?lid=1348

I only want to retrieve the learningphp.php from the url?

How to do this? Please help.

I used basename but it gives all the variable values also- learntolearn.php?lid=1348 which are in the url.

10条回答
Juvenile、少年°
2楼-- · 2019-01-14 20:38

This should work:

echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);

But beware of any malicious parts in your URL.

查看更多
老娘就宠你
3楼-- · 2019-01-14 20:38

Use parse_url() as Pekka said:

<?php
$url = 'http://www.example.com/search.php?arg1=arg2';

$parts = parse_url($url);

$str = $parts['scheme'].'://'.$parts['host'].$parts['path'];

echo $str;
?>

http://codepad.org/NBBf4yTB

In this example the optional username and password aren't output!

查看更多
▲ chillily
4楼-- · 2019-01-14 20:38

Try the following code:

For PHP 5.4.0 and above:

$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);

For PHP Version < 5.4.0

$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);
查看更多
Explosion°爆炸
5楼-- · 2019-01-14 20:39

You can use,

$directoryURI =basename($_SERVER['SCRIPT_NAME']);

echo $directoryURI;
查看更多
放荡不羁爱自由
6楼-- · 2019-01-14 20:46

Is better to use parse_url to retrieve only the path, and then getting only the filename with the basename. This way we also avoid query parameters.

<?php
$url = 'http://www.example.com/image.jpg?q=6574&t=987'
$path = parse_url($url, PHP_URL_PATH);
echo basename($path);
?>

Is somewhat similar to Sultan answer excepting that I'm using component parse_url parameter, to obtain only the path.

查看更多
Animai°情兽
7楼-- · 2019-01-14 20:46

An other way to get only the filename without querystring is by using parse_url and basename functions :

$parts = parse_url("http://example.com/foo/bar/baz/file.php?a=b&c=d");
$filename = basename($parts["path"]); // this will return 'file.php'
查看更多
登录 后发表回答