2019-03-16 18:09
浏览 7


Can i grab folder name into variable in php from browser?

For example i access this link:


it should be inside my main


I tried before and it work with htaccess but i need to make it inside the index.php to make htaccess work with another folder.

$a = "folder";
$b = "1928-1293";
echo $a . $b;

And it will showing me folder1928-1293

Thanks !

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dq23171 2019-03-16 21:55

    If I understand correctly, you want to configure your site so that when someone accesses "example.com/folder/1928-1293", you want that request to be handled by example.com/index.php, and you want index.php to be able to read the path/folders in the request.

    If so, then yes, you can. However, as you mentioned, this is only something you can do with the rewrite engine (.htaccess is the usual way of implementing it). This .htaccess snippet will take all requests that do not match up to an existing folder or file, and send them to index.php:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]

    It's basically the same rewriting function from WordPress.

    This way, if someone asks for example.com/otherfolder/otherfile.jpg and that folder/file is actually a real, physical file, then the .htaccess file will not change that request. It will only route requests for folders/files that don't physically exist.

    Inside index.php, you can then see the original path/request in the $_SERVER["REQUEST_URI"] variable and split the path into pieces with explode():

    // $_SERVER["REQUEST_URI"] = "/folder/1928-1293"
    $path_pieces = explode("/",ltrim($_SERVER["REQUEST_URI"],"/"));
    echo $path_pieces[0]; // "folder"
    echo $path_pieces[1]; // "1928-1293"

    You can also use the .htaccess for multiple rules, in case you need to handle more/other URLs in your .htaccess file.

    解决 无用
    打赏 举报

相关推荐 更多相似问题