Get a sub-directory folder in the URL and echo it .

前端 未结 3 1145
盖世英雄少女心
盖世英雄少女心 2021-01-16 20:13

How do I get the value of an URL eg. www.example.php/folders/crowd? I\'m trying to echo out crowd with PHP. I have tried using the $_SERVER [\'SCRIPTNAME\

相关标签:
3条回答
  • 2021-01-16 20:30

    To get the current directory of the file (which is just "crowd" in your "www.example.php/folders/crowd" example), use:

    $cur_dir = basename(dirname($_SERVER[PHP_SELF]))

    If you just want the file, then try this:

    $cur_file = $_SERVER[PHP_SELF];

    0 讨论(0)
  • 2021-01-16 20:31

    Maybe you want to have a look at the Apache module mod_rewrite. Many web hosting provider offer this module. If you even operate a dedicated server owned by you, it's no problem to install / enable this module.

    mod_rewrite can be used to transparently "transform" request URLs to requests for defined php scripts with query string parameters derived from the original request. This is often used for SEO-friendly URLs like http://mywebpage/article/how-to-cook-pizza-123.html. In this case a script might be invoked taking only the 123 from the URL as a parameter (e.g. http://mywebpage/article/how-to-cook-pizza-123.html => /article.php?id=123).

    In your case you could use a configuration like this (put this into an .htaccess file or your Apache/vhost configuration):

    RewriteEngine on
    RewriteRule ^folders/[A-Za-z]+$ showfolder.php?user=$1 [L]
    

    Your showfolder.php might look like this:

    <?php
        if (isset($_GET['user'])) {
            echo htmlentities($_GET['user']);
        } else {
            echo "No parameter found.";
        }
    ?>
    

    Any word after folders/ that consists of letters (A-Z and a-z) will be taken as the user parameter of your php script. Then you can easily echo this value, fetch it from a database or whatever. For example, a request for /folders/crowd will result in your script being executed with this parameter: showfolder.php?user=crowd. The user of your website won't see anything of this hidden internal forwarding.

    If you use some other web server software (nginx, ...): There are similar modules for other web server products, too.

    0 讨论(0)
  • 2021-01-16 20:37

    You can use parse_url, because scriptname will return the real php file execution "index.php" for example.

    php > var_dump(parse_url('http://www.example.php/folders/crowd', PHP_URL_PATH));
    // "/folders/crowd"
    

    But if you want just the last part you can:

    $tmp = explode('/', 'www.example.php/folders/crowd');
    var_dump(end($tmp));
    // "crowd"
    

    Or another way:

    var_dump(basename(parse_url('http://www.example.php/folders/crowd', PHP_URL_PATH)));
    // "crowd"
    
    0 讨论(0)
提交回复
热议问题