Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only filename from url in php without any variable values which exist in the url

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?

I used basename() function but it gives all the variable values also: learntolearn.php?lid=1348 which are in the URL.

like image 876
sqlchild Avatar asked Oct 21 '11 16:10

sqlchild


4 Answers

This should work:

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

But beware of any malicious parts in your URL.

like image 160
str Avatar answered Nov 19 '22 21:11

str


Following steps shows total information about how to get file, file with extension, file without extension. This technique is very helpful for me. Hope it will be helpful to you too.

  $url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';
        $file = file_get_contents($url); // to get file
        $name = basename($url); // to get file name
        $ext = pathinfo($url, PATHINFO_EXTENSION); // to get extension
        $name2 =pathinfo($url, PATHINFO_FILENAME); //file name without extension
like image 37
Khadka Pushpendra Avatar answered Nov 19 '22 20:11

Khadka Pushpendra


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 to inspect
$url = 'http://www.example.com/image.jpg?q=6574&t=987';

// parsed path
$path = parse_url($url, PHP_URL_PATH);

// extracted basename
echo basename($path);

?>

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

like image 32
foxtrot Avatar answered Nov 19 '22 21:11

foxtrot


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!

like image 22
ComFreek Avatar answered Nov 19 '22 20:11

ComFreek