parse_url函数php

I'm extracting tlds from my urls content with php's parse_url. than I have an array of top level domains which are compared with the extracted top level domain if they match or not.

  $url = parse_url($tag->getAttribute('href'));

  if (in_array($url['host'], $affi_urls) || $url['host'] == "www.example.com"){   

    $tag->setAttribute('href', '/redirect.php?url='.$href);       


   }

this works fine if the ur['host'] contains the top level domain. if the url['host'] is a relative path than is a big mess overthere.

/redirect.php?url=/example/test

how could I avoid this case?

You need to save the hostname of the page that you're processing. If $url['host'] is empty, use that hostname in its place.

You should encode the url parameters.

$tag->setAttribute('href', '/redirect.php?url='.urlencode($href));

And then after getting the data by parse_url, use urldecode to decode the data.