PHP and invoking url? [duplicate]

2020-05-10 09:00发布

问题:

This question already has answers here:
Closed 8 years ago.

Possible Duplicate:
getting current URL

I wan't to use url (with any GET parameters, etc) in PHP code.

So when my website is on url: http:/sample.com/art/id/title I want to display this string in website.

There is also one thing... My code would be fired up on various servers with various url conventions.

回答1:

// Get HTTP/HTTPS (the possible values for this vary from server to server)
$myUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']),array('off','no'))) ? 'https' : 'http';
// Get domain portion
$myUrl .= '://'.$_SERVER['HTTP_HOST'];
// Get path to script
$myUrl .= $_SERVER['REQUEST_URI'];
// Add path info, if any
if (!empty($_SERVER['PATH_INFO'])) $myUrl .= $_SERVER['PATH_INFO'];
// Add query string, if any (some servers include a ?, some don't)
if (!empty($_SERVER['QUERY_STRING'])) $myUrl .= '?'.ltrim($_SERVER['REQUEST_URI'],'?');

echo $myUrl;

Should account for just about any variations you might encounter (although mod_rewrite may screw it up in an un-correctable way, I'm not sure).



回答2:

The following should give you both the domain and URL:

$_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];


回答3:

You have to have an .htaccess file, it's called URL re-write, an example .htaccess file:

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php?query=$1&%{QUERY_STRING}

This will send everything like art/id/title to your index.php page and will be usable using $_GET['query']. So in the index.php file, you can use the variable like so:

echo $_GET['query'];