开发者

Passing parameters via GET to any url in universal way

I have back_url given to me from the outside. I need to generate a hash and to make redirect to this back_url with this param: header("Location: $back_url?hash=123sdf"). But the problem is that I don't know the format of back_url.

  • It may be www.example.com and I do header("Location: $back_url/?hash=123sdf")开发者_如何转开发 sj that's fine.
  • It maybe www.example.com/?param=value and if I do header("Location: $back_url/?hash=123sdf") it's wrong, because it would be www.example.com/?param=value/?hash=123asd.

And so on. The question is: what's the universal way to pass params to back_url ignoring its format?


A complex but very clean way is

  • Use parse_url() to extract the query string (if any) from the URL into an array
  • Add hash to the resulting array: $params["hash"] = "1234";
  • Use http_build_query() to glue the parameters back into a query string
  • Take all the components returned by parse_url() and glue them back into a full URL

one thing to note is that this dissects the URL into it components and glues it back together, so it's likely it won't work with URLs that are broken in the first place.


Have you tried using http://php.net/manual/en/function.parse-url.php ?


If you have the PECL HTTP extension, use http_build_url:

$url = '...';
$hash = '...';
$new_url = http_build_url($url, array('hash' => $hash), HTTP_URL_JOIN_QUERY);

If you don't have http_build_url, you can use parse_url to find the different parts if a URL. Then it's just a matter of pasting them together. Here's a solution in the manual which can be tailored for your needs.


Well, you would need to detect if $back_url has other query parameters (or GET variables) and append your hash using ?hash=123asd if it hadn't, or using &hash=123asd if indeed it had query parameters.

If you know that $back_url is a full url like http://whatever.com/blah/blah (the important part being http://whatever.com, you can use parse_url to get all components, and then continue with Pekka's answer. If your $back_url doesn't begin with http://..., then prepend the right value (I assume http://$_SERVER['host'] and, again, continue with Pekka's answer.


Wrote this function:

 private function addUrlParam(array $params, $url){
    $parsed = parse_url($url);
    if(!isset($parsed['query']))
    {
        $slash = '';
        if(substr($url, -1) !== '/')
            $slash = '/';
        $start_with = $slash.'?';
    }
    else
        $start_with = '&';

    $scheme = '';
    if(!isset($parsed['scheme']))
        $scheme = 'http://';

    $query = http_build_query($params);
    return $scheme.$url.$start_with.$query;
}  

Looks like it's perfect for me. Thanks everyone.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜