开发者

In PHP, how can I get any string after the domain to be a php variable? Ex: me.com/FOO, me.com/VAR3

so my index.php can be this:

<?php
      $restOfURL = ''; //idk how to get this
      print $restOfURL; //this should print 'FOO', 开发者_运维百科'VAR3', or any string after the domain.
 ?>


You want to use,

<?php
    $restOfURL = $_SERVER['REQUEST_URI'];

    // If you want to remove the slash at the beginning you can use ltrim()
    $restOfURL = ltrim($restOfURL, "/");
?>

You can find more of the predefined server variables in the PHP documentation.

Update
Based on your comment to the question, I guess you're using something like mod_rewrite to rewrite the FOO, etc and route everything to just one file (index.php). In that case I would expect the rest of the URL to already be passed to the index.php file. However, if not, you can use mod_rewrite to pass the rest of the URL as a GET variable, and then just use that GET variable in your index.php file.

So if you enable mod_rewrite and then add something like this to your .htaccess file,

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

Then the rest of the URL will be available to you in your index.php file from the $_GET['url'] variable.


Reading $_SERVER['REQUEST_URI'], as everybody has pointed out, can tell you what the URL looks like, but it doesn't really work the way you want it unless you have a way to point requests for me.com/VALUE1 and me.com/VALUE2 to the script that will do the processing. (Otherwise your server will return a 404 error unless you have a script for each value you want, in which case the script already knows the value...)

Assuming you're using apache, you want to use mod_rewrite. You'll have to install and enable the module and then add some directives to your .htaccess, httpd.conf or virtual host config. This allows you make a request for me.com/XXX map internally to me.com/index.php?var=XXX, so you can read the value from $_GET['var'].


$var = ltrim( $_SERVER['REQUEST_URI'], '/' )

http://www.php.net/manual/en/reserved.variables.server.php


Just by looking at the examples, i think you are looking for the apache mod_rewrite. You can apply a RewriteRule via an htaccess file, for example:

Options +FollowSymlinks
RewriteEngine on

RewriteRule ^([\w]+)$ /checkin.php?string=$1 [L]

For example this url http://foo.com/aka2 will be process by checkin.php script and will have "aka2" passed as $_GET['string'].

Make no mistake, the URL will still be visible in the browser as http://foo.com/aka2 but the server will actually process http://foo.com/checkin.php?string=aka

mod_rewrite documentation


$_SERVER['REQUEST_URI']


Why bother with all the fancy mod_rewrite/query_string business? There's already $_SERVER['PATH_INFO'] available for just such data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜