Change URL using PHP - 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.

Related

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).

php and javascript redirect

Hi in a simple page i use php and javascript redirect to return to referrer page.
header("Location: $refererScript");
onclick="window.location.href='<?=$refererScript?>';"
Which is the best way to protect those scripts from generate errors:
Ex. should i use urlencode for $refererScript (or at least for query string ) and if so will this acceptable from javascript or must use escape (or something else)
For $refererScript i use the code above
$ref=$_SERVER["HTTP_REFERER"];
$refererParts = parse_url($_SERVER['HTTP_REFERER']);
$refererQuery=$refererParts["query"];
$refererFolders=explode("/",$refererParts["path"]);
$refererScript=$refererFolders[sizeof($refererFolders)-1];
if($refererQuery!="")
{ $refererScript.="?".$refererQuery; }
Thanks
I would suggest you to use php header approach because if javascript is disabled, then there will be no redirect and you should url encode it eg:
$refererScript = urlencode($refererScript);
header("Location: $refererScript");
In the $_SERVER["HTTP_REFERER"]; should be already valid URL. If not, someone changed it manually and will get redirected to the wrong page.
I don't see any security risks here. Your code is fine.

How to display URL parameters in PHP script?

I want to redirect my browser to a PHP page such that when the page loads, it will display to the user a substring of the current URL.
For example, let's say I have a page called substring.php.
My browser forwards me to:
http://www.example.com/substring.php?oauth_token=123456
Is it possible to write some PHP code that will then display to the user, "123456"?
If so, can anyone help me on how to do this?
Thanks!
All the query parameters in the URL will be inside the superglobal $_GET array, so you could simply do this:
echo $_GET['oauth_token'];
BE forewarned that if you're going to output anything that comes in from a URL (ie. user input), you should make sure to sanitize it properly for output. In this case, htmlspecialchars() would be prudent:
echo htmlspecialchars($_GET['oauth_token']);
<?php
echo $_GET['oauth_token'];
?>
Can't you just use the $_GET superglobal? It stores the contents of the query string part of the URI as an associative array:
echo $_GET['oauth_token'];
You can retrieve the value of oauth_token via the $_GET superglobal array:
echo $_GET['oauth_token'];
Of course you should use caution when outputting data you get as input from a user, but that's how it works in short.

need help in particular php job, dont know how to do it

I want to do something but cant figure out how to do this (i m newbie in php)
suppose, i have a list of URL's which shows live with this preg_replace,
$html = preg_replace('/\s(\w+:\/\/)(\S+)/', ' GO ', $html);
my output is like
http://localhost/get.php?url=http://yahoo.com
its obvious that you can view that links at output page, now i want to hide them at front page and make them clickable and working
something like we can change links into variables and then call them by clicking and something works in backgroud which can perform same thing as we are clicking on the link at front page
ya it seems bit confusing :(
you could save the url into a $_SESSION vars and when some users click the link retrive the url from $_SESSION and redirect to it...
//page1 - parse, save link in session and print a call to page2
<?php
session_start();
$_SESSION['url'] = preg_replace('/\s(\w+:\/\/)(\S+)/', ' GO ', $html);
....
echo 'GO';
?>
//page2
<?php
session_start();
header('Location: '.$_SESSION['url']);
?>
If i undeerstood what you meant...
Obviously now I used $_SESSION['url'] as a single string, but you can use a multidimensional array intead...
UPDATE:
anyway is better if you use an array on script..
example: http://www.test.org/go.php?page=# (where # is a number)
<?php
$array=("http://www.google.com","http://stackoverfloc.com","ecc");
//you can add more contorl in if statement, like between etc...
if (is_numeric($_GET['page']) header('Location: '.$array[$_GET['page']]);
?>
I'm sorry, maybe I'm not understanding quite well, but, isn't best approch use an array for in side server and use another Get variable to do that?
for example ?link=yahoo
and then
find link in array of url?
BY the way, I'm using NoScript and reports me like a warning..
You build up links with looking like this:
yourdomain.com/redirector.ph?url=#
where # represents an identifier.
In redirector.php you check if you know that identifier and send the redirect HTTP Header:
header("Location: http://www.example.com/");
Important Note:
You may not send any data before sending the header and the code after sending it won't be executed.
Info
http://php.net/manual/en/function.header.php
EDIT
Using this header is not absolutely proper in regards to standard, but it's not too far off, as the response really is at another location.

How to remove a specific $_GET variable from a URL

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.

Categories