0

I'm using PHP $_GET to get a URL from a URL variable like so:

echo 'URL: ' . $_GET['url'];

When I get a regular URL it echos fine, for example:

http://localhost?url=http://google.com

The output is:

URL: http://google.com

But if the URL contains multiple variables, they get cut off, for example:

http://localhost?url=http://google.com?id1=55&id2=88&id3=99

Will return:

URL: http://google.com?id1=55 

If there any way around this so I can get the URL regardless of what it contains? e.g. so it returns:

URL: http://google.com?id1=55&id2=88&id3=99

Updated, in response to Yuu:

$url = $_GET['url'];
$parse = parse_url($url);

$replace_old = array($parse['host'],'http://');
$replace_new = array("","");

$url_vars = str_replace($replace_old,$replace_new,$url);

echo $parse['host'] . htmlentities($url_vars);

2 Answers 2

1

You have to urlencode your URL, in order to parse the special characters.

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="http://google.com?' . htmlentities($query_string) . '">';
?>

https://www.php.net/manual/en/function.urlencode.php

Edit as response to edit:

This would work. You needed to encode the & right at the GET stage.

<?php

$url = $_GET['url'];
unset($_GET['url']);
if ($_GET) {
    $url .= '&' . http_build_query($_GET);
}
$parse = parse_url($url);


$replace_old = array($parse['host'],'http://');
$replace_new = array("","");

$url_vars = str_replace($replace_old,$replace_new,$url);


echo $parse['host'] . $url_vars;


?>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response, but as far as I can see, this unfortunately does not work when the URL is retrieved from a URL using $_GET, because the other variables cannot be retrieved from the URL at all (see code posted above)
@TheBobster You need to urlencode the & symbol to %26. It should work with that.
@TheBobster I have edited my answer with the code, please check if it works now.
0

You need to urlencode first the url value before passing it.

Example:

echo urlencode('http://google.com?id1=55&id2=88&id3=99');

Output:

http%3A%2F%2Fgoogle.com%3Fid1%3D55%26id2%3D88%26id3%3D99

And in your URL

http://localhost?url=http%3A%2F%2Fgoogle.com%3Fid1%3D55%26id2%3D88%26id3%3D99

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.