php: getting rid of ?p= query in url?

2019-06-14 18:44发布

问题:

hey guys, i'm not looking for a mod_rewrite thing or anything related. i'm just not sure if this is possible or not?

i'm using if(isset($_GET['p'])) … to check if ?p=something is set in my url, if not $foo = "bar"; if a ?p= is set e.g. ?p=something –> $foo = "something". got me?

if i manually enter now ?p=bar to my url the string in my url is actually the default one. Because if I don't have a ?p in my url $foo = "bar";

I wonder if that's the case i can get totally get rid of the ?p= part in my url? if the default string is set to my $foo variable i just wanna have a clean url without any distractign ?p=bar in my url.

sorry for the weird foo and bar stuff, i had no better example ;) regards matt

回答1:

if ($_GET['p'] == 'bar') {
        parse_str($_SERVER['QUERY_STRING'], $q);
        unset($q['p']);
        header('Location: ' . $_SERVER['PHP_SELF'] . ($q ? "?" . http_build_query($q) : ''));
}

is a neat way. It does not wipe other GET parameters, if they exist.



回答2:

Is this what you're asking for? (Do a redirect if the default was entered)

if (isset($_GET['p'])) {
  if ($_GET['p'] == $defaultP) {
    header("HTTP/1.1 302 Found");
    header("Location: ".$urlWithoutQuery);
    exit(); // or whatever the function is.
  } else {
    $foo = $_GET['p'];
  }
} else {
  $foo = $defaultP;
}

Note that this must be done before anything at all is sent to the client (as it's part of the header).

As far as I know, the only way to scrub something from the URL on clientside is either a redirect, or javascript (which, in effect, also does a reload, so the redirect is probably a lot faster).



回答3:

Look at this mod_rewrite tutorial: tutorial



回答4:

Use Apache's mod_rewrite to change example.com/?p=pagename to example.com/pagename

Put this in your .htaccess file:

<IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ index.php?p=$1 [L,QSA]
</IfModule>

Voila, no ?p=



回答5:

If you want to implement friendly/clean urls, you might want to take a look at Net_URL_Mapper.



回答6:

if that's the case i can get totally get rid of the ?p= part in my url?

Yes. Just get rid of it. It's nobody but you who set these urls on your site. So, edit your site's HTML and get rid of anything you want.



标签: php url