How to remove a specific $_GET variable from a URL - php

I have a website authored in PHP where any time a user receives an error I will redirect them to a another page (using header(Location:...)) and put the error ID in the URL so that I know which error to display.
E.g. If the user tries to access a product page but that item is no longer available I will redirect back to the category of items they were previously looking at and display an error based on the error ID I have specified in the URL.
www.example.com/view_category.php?product_category_id=4&error_id=5
There are two things I don't like about this approach:
It displays the error_id in the URL.
if the page is refreshed, the error will still display.
Is there a way to cleanly remove a specific $_GET variable from a URL while leaving the rest of the variables intact AFTER the page is loaded?
I'm thinking maybe it's using modRewrite or a redirect back to the page itself but removing the error_id from the URL or using a $_SESSION variable and avoiding putting the error_id in the URL. Your thoughts?
I really am learning a lot from this community and thought if I posed the question I might be able to learn something new or to get some varied ideas as I'm fairly new to scripting.

No, there's no way to do that explicitly - at least not without a page refresh but then you'd lose the data anyway.
You're better off using a temporary session variable.
if ( /* error condition */ )
{
$_SESSION['last_error_id'] = 5;
header( 'Location: http://www.example.com/view_category.php?product_category_id=4' );
}
Then, in view_category.php
if ( isset( $_SESSION['last_error_id'] ) )
{
$errorId = $_SESSION['last_error_id'];
unset( $_SESSION['last_error_id'] );
// show error #5
}

Yes, there is a way to remove especific $_GET from PHP...
varToRemove = "anyVariable";
foreach($_GET as $variable => $value){
if($variable != varToRemove){
$newurl .= $variable.'='.$value.'&';
}
}
$newurl = rtrim($newurl,'&');
Then, put the $newurl in the link.. like this:
pageurl?something=something&<? echo $newurl; ?>
I know it´s an old post, but, other programers may be search for it!

First, log the error in your database :)
After that, set a cookie or session variable and then redirect the user to safe page. When that page is loaded, have it check for the variable, display the error, and then delete variable from the cookie or session array.

One way is to compare the HTTP_REFERER with the SCRIPT_NAME. They'll be the same if the user has hit Refresh.

Quick Hack: You could have also imploded()'d on "&" in the the $_SERVER['QUERY_STRING'] variable to manipulate that string and then explode()'d it back.

Wouldn't this approach work?
<?php
$params = array_diff($_GET, array("variable_name" => $value));
$new_query_string = http_build_query($params);
?>
<script>window.history.pushState('verify_email', 'Verify Email', '?<?php echo $new_query_string; ?>');</script>

i had same problem
try : http://www.azazia.com/kb/entry/26/
if (!empty($_GET['passvar'])) {
unset($_GET['passvar']);
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"0; URL=".$_SERVER['PHP_SELF']."\" >";
}
work perfectly for me.

Related

Set session variable on <a> click

I'm trying to make an <a> link which triggers PHP code on the next page. I've tried using $_GET variables to do this but the thing is I also want to remove the variable afterwards, as I automatically link back to the redirected page with header(). There don't seem to be any feasible ways to do this without redirecting the user to one page alone, but the thing is they're expected to be redirected to the page they were on previously. Keeping $_GET variables then cause an endless loop of redirects.
In general, I wish to avoid using $_GET as it could be abused in the context I'm using it in. Any other workarounds would be greatly appreciated, though. Basically I'm just trying to use an <a> link to remove an entry from a MySQL database.
Here's the PHP that handles the variable.
if (isset($_GET['rm'])) # 'rm' contains the uuid of the entry to be deleted.
{
$uuid = $_GET['rm'];
unset($_GET['rm']); # Didn't expect this to work, of course it didn't remove the variable from the URL.
$query = "DELETE FROM posts WHERE uuid = '$uuid'";
$result = $mysqli->query($query);
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
EDIT: I realize now that I have wildly complicated my explanation here. The main goal was to make the click of an <a> link trigger PHP code, with a variable specific to the link clicked. (Each link is a delete button on a post, and each post has a UUID)
If there is a way to alternatively trigger javascript code, that would be immensely helpful as well, since I'm looking to use such a method here too. I will likely be making a separate thread asking about this.
You can use $_SESSION to delete the variable after for example
if (isset($_SESSION['rm'])) # 'rm' contains the uuid of the entry to be deleted.
{
$uuid = $_SESSION['rm'];
unset($_SESSION['rm']); # Didn't expect this to work, of course it didn't remove the variable from the URL.
$query = "DELETE FROM posts WHERE uuid = '$uuid'";
$result = $mysqli->query($query);
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
consider that you have register the value of the next shape.
$_SESSION['rm'] = "My value";
If your goal is to redirect to the current page but remove the query string, you can redirect to header("Location: ?"); which is essentially just that. (Technically you are redirecting to a new query string with no value which is different than no query string at all but php will just show an empty array for $_GET which is essentially the same)
I was going to mention additional options like variables from $_SERVER, but many of those have various security or other issues associated with them. I only mention this because I wouldn't suggest using any unless necessary. Also, it really doesn't get easier than the above.

PHP get previous page url after redirect

I want to have a navigation bar that tells the user where they just came from.
Example: Homepage -> Post
But if they are in their posts manager and click on a post, I want it to say
Posts manager -> Post
I read that $_SERVER['HTTP_REFERER'] is not good enough to get the full url so that's not useful as I want the navigation bar all clickable
Any help is much appreciated!
I believe what you want is called breadcrumbs.
What to use for navigation chain storage is actually up to you. You might use even $_SERVER['HTTP_REFERER'] if you want, but that'd be unreliable as it's client-side. Usual way to store such chain is actual URI or session.
For example, you have such URI: http://www.example.com/post_manager/post
Then you can iterate through explode("/", $_SERVER["REQUEST_URI"]) to get each step.
That's basic explanation to guide you to a right direction. You can google alot of samples and snippets using keyword breadcrumbs.
On the topic of saving last visited location (the way to determine wether abonent came from manager or homepage): you can use session's variables to do that. Here's an example:
This way you can set a variable on your homepage:
<?php
session_start();
$_SESSION['previous_location'] = 'homepage';
?>
And then you just access it from another page:
<?php
$previous_location = $_SESSION['previous_location'];
?>
It's important to set session.save_path in your PHP configuration file or your sessions might get lost.
You could do it on the client side if you use the Javascript document.referrer property. However, a better solution may be to use the global session array.
if (!isset($_SESSION['referrer'])) {
$_SESSION['referrer'] = $current_uri;
} else {
$previous_uri = $_SESSION['referrer'];
$_SESSION['referrer'] = $current_uri;
}
The best solution IMO is to save the location into session, every time the user goes to a 'meaningful' page (that you want to be able to navigate back to via this feature), then simply use this array of, say, last 2 visited pages to pull up all the information. Simple and effective.
<?php
session_start();
$_SESSION['user_interactions'][] = $_SERVER['HTTP_REFERER'];
// get previous
$previous_page = end($_SESSION['user_interactions']);
// list all user interactions
foreach($_SESSION['user_interactions'] as $key => $value){
echo $value;
if(count($_SESSION['user_interactions'])-1 != $key) echo ">";
}
?>

check if a querystring exists, if not create one - PHP

I have several pages which use querystrings to highlight an option in a menu, all the url's on the page have the currant querystring phrased in them so the same menu option will be highlighted on the next page if the user clicks the link.
However the problem arrises when someone visits the page without the querystring included in the url, the menu option isn't highlighted.
What i would like to do is check the URL to see if a querystring is present, if one isnt, create one.
The url's are phrased as such www.mysite.co.uk/Folder1/Folder2/Page.php?id=3
and i would like the default querystring to be ?id=1 if one isn't already present in the url.
Any ideas on how you do this?
And what would happen if a user visits using the URL www.mysite.co.uk/Folder1/Folder2/Page.php?
Would the URL end up as www.mysite.co.uk/Folder1/Folder2/Page.php??id=1
or would it be www.mysite.co.uk/Folder1/Folder2/Page.php?id=1
Thanks,
Maybe there are plenty of ways. You can assign value to $_GET key if one does not exist. Or if you really need to query string, you can renavigate the user to the same page with present querystring.
if (!isset($_GET['id'])) {
header("Location: Page.php?id=1");
exit;
}
It should be before any output in the page. So if user visits Page.php or Page.php? or Page.php?someDifferentParamThanId=10 it will return false on isset($_GET['id']) thus it will redirect to Page.php?id=1
This should work:
if(isset($_GET['id'])){
//It exists
}else{
//It does not, so redirect
header("Location: Page.php?id=1");
}
Do something like:
if(!isset($_GET['id'])){
header('LOCATION:www.mysite.co.uk/Folder1/Folder2/Page.php?id=1'); die();
}
In php, the query string is loaded into $_REQUEST variable. In your case, $_REQUEST['id'] will be equal to 1, 3 or whatever you get in the query string.
For solving the problem when no id is given via GET, I think will be enough to add this line at the beginning of each php page:
<?php
if ( $_REQUEST['id']=='' ) {$_REQUEST['id']=1;}
?>
It is not necessary to change the URL on the fly.

Hide ?ref string in URL but pass it to script

How can I hide ?ref string from users but pass it to php code so it will grab it?
For example, visitor visits this page:
http://mysite.com/?ref=ref+string
In browser URL I want to hide it, so user will see"
http://mysite.com/
But I want to grab content of ref string via this:
$ref = $_GET['ref'];
Is it possible?
No, if you want to use GET variables, they will always be in the url.
However, you can use an alternative, like $_SESSION or $_POST variables.
You could try something like this at the top of your PHP script:
session_start();
if (isset($_GET['ref'])) {
$_SESSION['ref'] = $_GET['ref'];
header('Location: /');
exit();
}
You would have to use $_SESSION['ref'] to access the value from then on, however.
This is not how the http protocol works with query strings. If you have information that needs to be in the query string that you want to hide or obfuscate from the user, I would recommend a simple encryption to change it. If you're attempting to get rid of this information for aesthetic reasons, you will need to pursue a different method of generating the header or storing the information (session/cookies/etc).

Change URL using PHP

e.g. i have page with url http://mysite.com?page=3&var=10 also there is form on page.
When form submitted there some actions in php but i need to remove this ?page=3&var=10 after form was submitted somehow is there way compatible with all browsers trough PHP without mod_rewrite?
This is an old topic, but just in case anyone else is searching for this in the future, you can use the javascript replaceState to change the history and browser bar label. A simple php function to do this:
function set_url( $url )
{
echo("<script>history.replaceState({},'','$url');</script>");
}
Then would simply call this function with the desired url (presumably dropping the post variables):
set_url("http://example.com");
A page reload or a back after calling another page will now have the new url location in the history.
I think that using POST may be a more elegant solution, but if you must use GET this is a work around.
If you're using action=index.php, then all values will be posted to index php, ?page=3&var=10 will be automatically removed.
If you want to post to the same page you can either use 'action=index.php?page=3&var=10' or action=<?php echo $_SERVER['PHP_SELF'] ?>
You can check at the beginning of the page if something submitted and then redirect to whatever you want with header('Location: http://www.example.com/'); More about header function http://php.net/manual/en/function.header.php
Yeah, the solution is quite simple (even if not really SEO friendly):
<?php
header("Location: http://mysite.com")
?>
just for information...why do you need it?
use parse_str to get the query string as an associative array that is easy to modify. Then use http_build_query to convert the associative array into a query string.
$queryString = $s['QUERY_STRING'];
$params = array();
parse_str($queryString, $params);
//change $params as needed
$queryString = http_build_query($params);
if ($queryString) {
$queryString = '?'.$queryString;
}
return preg_replace("/\\?.*/s","",$s['REQUEST_URI']).$queryString;
preg_replace("/\\?.*/s","",$s['REQUEST_URI']) removes the original query string allowing you to replace it.
Does this work for you?
header('Location:/');
mod_rewrite cannot affect what's displayed in the user's browser address bar, UNLESS the rewrite does an externally visible redirect. Otherwise it only rewriting things within the webserver, and that's invisible to the user.
If you want to affect the user's address bar, you'll have to do a redirect via header('Location: ...') after the form's finished processing.

Categories