DimNC
DimNC

Reputation: 130

Current URL parameter in a new link in the page

I am creating a website for a study for my Ph.D. I have multiple versions of a same webpage (different colors, different lengths…), and each version has url parameters.

I'd like to create a link at the bottom of each page, which redirects to a questionnaire site, but automatically retrieving the parameters of the page's url it is on.

Example

Current url is:

http://abcmessage.com/abc?message=1&color=blue&lenght=small

You click on the link and it takes you to the questionnaire website, keeping the parameters:

http://questionnaire.com/abc?message=1&color=blue&lenght=small

What should I put next to my redirecting link to do that?

I found that below, but it didn't really work:

 $text = '?';
$c = 0;
foreach($_GET as $k => $v){
    $text .= ($c>0) ? "&$k=$v" : "$k=$v";
    $c++;
}
$text = ($text=='?') ? "" : $text;

echo $text;

I have to admit I don't know much about php and Java, but I'm working on my own and have to get the things done, so I'll learn. So thank you very much to whomever will help :)

Cheers!

Dim

Upvotes: 3

Views: 502

Answers (2)

ln9187
ln9187

Reputation: 740

You can use http_build_query()

It can be done like this:

all_requests = $_GET;

$build_query_http = http_build_query($all_requests);

echo "http://questionnaire.com/abc?" . $build_query_http;

Or you could even remove all empty requests before passing over:

foreach ($all_requests as $key => $var_val) {
  if(empty($var_val) || $var_val=='')
  {
    unset($all_requests[$key]);
  }
}

It's worth to look at the maximum length of a query string.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178383

Try location.seach:

<a href="#"
onclick="this.href='http://questionnaire.com/abc'+window.location.search">Questionnaire</a>

Upvotes: 1

Related Questions