php $_SERVER['PHP_SELF'] to include query string
Solution 1
You could use:
$_SERVER['REQUEST_URI']
to get everything after the domain name folders, query strings etc. You could then either use the other $_SERVER variables to add the domain, or it should be fine to use without a domain name provided you're not changing hosts.
Solution 2
What about:
echo $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
Note that you'll probably want to sanitize that output like so:
$url = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
echo htmlspecialchars($url, ENT_QUOTES, 'utf-8');
to guard against XSS.
Solution 3
The query string is available in $_SERVER['QUERY_STRING']
. Just concatenate them (don't forget the question mark) and you'll be fine. :)
Comments
-
bagofmilk almost 2 years
I'm essentially trying to make a login system that will return the user back to the page they were on. I know this question has been asked a bit, and I've looked at the other answers on SO, but I cannot find a solution to my particular problem.
My site has has a table with reference id numbers (ex: 10001, 10003, 10004, ... 53401, etc.). These numbers are also links. All links point to one page ("mypage.php"), and the reference id number (10004) becomes a query string to that url:
<td><?php echo '<a href="mypage.php?query_ecr=', urlencode($num), '">'; ?><?php echo $num; ?></a></td>
On my "header.php", which is on every page of the site, there is a button on the menu that will open the form below for the user to log in.
<form action='login/process.php' method='post'> <label for='name'>Username:</label> <input type='text' id='userid' name='user_name'/> <label for='password'>Password:</label> <input type='password' name='password' id='userpassword'/> <input type='submit' value='Log In' /> <input type='hidden' name='login' value='1'> <input type='hidden' value='".$_SERVER['PHP_SELF']."' name='redirurl'/> </form>
Notice the "hidden input" with the name='redirurl'. I want to capture the current page the user is on. I already have a login script that will check the username and password and redirect them to the page they need to be.
//login/process.php ...blah blah blah other stuff... global $database,$session; $this->user_status=$database->CheckUserPass($_POST['user_name'],$_POST['password']); $url = $_POST['redirurl']; if($this->user_status==1) { $session->StartSession($_POST['user_name'],$_POST['password']); header("Location: ".$url); } else { ...blah blah blah..... }
My problem is that if the GUEST clicks on a link (ex: 10004), they are taken to the url:
http://www.XXXXXX.XXXX/mypage.php?query_ecr='10004'
However, on that page the value for 'redirurl' is:
http://www.XXXXXX.XXXX/mypage.php
It disregards the query string. So when the user logs in from that page, and my login script re-directs them back to that page, the page has a ton of errors because it needs the query string.
How do I include the query string in: $_SERVER['PHP_SELF'] ?