tags:

views:

59

answers:

5

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") {
            $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&amp;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?

A: 

Try this:

$pageUrl = str_replace('&type=main', '', $pageURL);
Sarfraz
Weird, still same problem remains.
James
+1  A: 

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

webbiedave
A: 

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

Col. Shrapnel
+3  A: 

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 ;-)

Pascal MARTIN
A: 

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.

BalusC