开发者

How to strip a GET property from the URL using PHP

I have the following function that get's the current page URL:

<?php

    // get current page url
    function currentPageUrl() {

        $pageURL = 'http';

        if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}

        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80")开发者_C百科 {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        }
        else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }


        echo $pageURL;

    }

?>

Which prints:

http://localhost/gallery.php?id=23&type=main

I want to remove "&type=main" which is present in the url. So before echoing $pageURL I add the following line:

$pageUrl = preg_replace("&type=main", "", $pageURL);

But it still returns the full url including type=main. How can I get rid of that from the url?


Another solution could be to :

  • use parse_url or $_SERVER['QUERY_STRING'] to extract the list of parameters as a string
  • use parse_str to transform the query string to an array containing each parameter and its value -- indexed by parameters names.
  • Do some magic on that array :
    • do what you have to to filter it
    • For example, unset($array['type']); could probably help ;-)
    • If needed, add more parameters to that array
  • And, then, use http_build_query to re-build a query-string.


A bit more complex than string manipulations, of course -- but much more reliable, I'd say ;-)


You can throw a url into parse_url. It will return an array from which you can rebuild as you see fit.


Try this:

$pageUrl = str_replace('&type=main', '', $pageURL);


did you try any other $_SERVER variables?
there are plenty and some of them already contain everything you need without any replace

phpinfo(32);

will show you all


PHP identifiers are case sensitive. You probably meant to assign it to the same variable.

$pageURL = preg_replace("&type=main", "", $pageURL);

Either that, or you need to change the remnant of code to use $pageUrl instead of $pageURL.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜