views:

62

answers:

2

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

+3  A: 

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");
Sarfraz
Thanks, JavaScript redirect is necessary too.
ntan
@You are welcome :)
Sarfraz
and there are ways to detect whether javascript is enabled or not on user's browser
Sarfraz
A: 

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.

Petr Peller