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

前端 未结 12 694
北荒
北荒 2020-12-05 12:41

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

相关标签:
12条回答
  • 2020-12-05 13:18

    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']);
    
    0 讨论(0)
  • 2020-12-05 13:19

    Use this function:

    function getScriptName()
    {
        $filename = baseName($_SERVER['REQUEST_URI']);
        $ipos = strpos($filename, "?");
        if ( !($ipos === false) )   $filename = substr($filename, 0, $ipos);
        return $filename;
    }
    
    0 讨论(0)
  • 2020-12-05 13:20

    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.

    0 讨论(0)
  • 2020-12-05 13:20

    Your URL:

    $url = 'http://learner.com/learningphp.php?lid=1348';
    $file_name = basename(parse_url($url, PHP_URL_PATH));
    echo $file_name;
    

    output: learningphp.php

    0 讨论(0)
  • 2020-12-05 13:30

    May be i am late

    $e = explode("?",basename($_SERVER['REQUEST_URI']));
    $filename = $e[0];
    
    0 讨论(0)
  • 2020-12-05 13:31

    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!

    0 讨论(0)
提交回复
热议问题