Search code examples
phpurlgetstoreexternal-url

PHP - Proper Protocol for storing URLs in $_GET


What is the proper protocol for storing other websites URL's in your own php page's URL?

For example if I wanted to store google it would be easy.

MySite.com/test.php?url=http://www.google.com


But what about a URL more complex than http://www.google.com, like if I wanted to store another website's PHP page.

(e.g. http://www.AnotherSite.com/page1.php?key=value&key2=value2&key3=value3)

Then how would I store it in my PHP page's URL? Do you replace all of the "&" symbols with a "\&" phrase? Is there a better method? Does that even work in the first place?


Thanks!!!


Solution

  • If you don't want to think about it:

    $url = 'mysite.com/test.php?' . http_build_query(array(
        'url' => $anything_you_want,
    ));
    

    Otherwise:

    $url = 'mysite.com/test.php?url=' . urlencode($anything_you_want);
    

    You could also use rawurlencode(). Notable difference is that it follows RFC 3986.

    Further reading:

    http_build_query() urlencode() rawurlencode()