johnnietheblack
johnnietheblack

Reputation: 13340

How to dynamically build a query string for each link?

I am building a method for impersonating a certain user on my website, similar to how Facebook now does it on the profiles with the "View As" button.

The goal here is to be able to append the user id of the person that I would like to impersonate to the query string like so: viewas=1234. Upon seeing that, the site would allow me (as an admin) to "impersonate" that user.

However, the problem comes with carrying the "impersonation" state between page loads. Each link that I click on will need to be adjusted to carry the viewas=1234.

For example, a link that would typically look like this...

<a href='http://www.example.com/profile?profileid=5678'>My Profile</a>

...would have to dynamically know to turn into...

<a href='http://www.example.com/profile?profileid=5678&viewas=1234'>My Profile</a>

...whenever I would like to impersonate the user with the id 1234. And this would have to happen site wide.

Is the best way to somehow do this with JS after the load, with PHP on the server side, or something else?

Upvotes: 0

Views: 804

Answers (3)

Aleks G
Aleks G

Reputation: 57346

Not sure whether this is the answer you'd be looking for, however here it goes. I recently had to implement a similar set of functionality. I went with storing the value of "viewas" in the session variable. This way, there is no need to modify HTML, javascript, etc. - only your code (which you already are modifying anyway to handle the query string) - in the code check the session variable instead.

You can then unset this variable when the admin "logs out" from impersonation.

Upvotes: 1

Phil Lello
Phil Lello

Reputation: 8639

jQuery is ideal for this sort of thing; create a selector for all 'a' tags, and append the query string to the href property.

For example,

$('a').each(function () {
  var href = $(this).attr('href');
  href += '?viewas=1234';
  $(this).attr('href',href);
});

Upvotes: 2

Rene Pot
Rene Pot

Reputation: 24815

You should detect if it has been set, if so, append it for each link.

Something like:

if (isset($_GET['viewas'])){
   $linkurl .= '&viewas='.$_GET['viewas'];
}

of course you should not do the check for every link, but make it a set variable. Also do some security checks so you know for sure it is an valid viewas.

Upvotes: 1

Related Questions