2

I have some code that is accessible from several different pages. Based on which page it comes from and which variables it sends, it does slightly different things.

I guess I could write totally new pages for each referring page but really don't want to do that as the functionality is similar.

In the case of errors, I want to redirect back to the referer page. Similarly, upon success I also want to redirect back to the referer page. However, I'd like to add a parameter that describes the error or let's the user know it was a success to distinguish between a failure and success.

Let's say there are two referer pages, emailstory.php?id=231 and emailsignup.php One has a quesion mark and the other doesn't. I want to send the user back to the referer but add error=1. I need some code that appends &error=1 to the first referer but ?error=1 to the second and is robust to many variations.

php

$referer = $_SERVER['HTTP_REFERER'];
$id = $_POST['id'];
$returnpage = $referer."&error=1";
if (!isset($_REQUEST['id'])) {
header("Location:$returnpage");
}

Above would work in some instances but only if there is already a ? launching a querystring

Is there an easy, foolproof way to do this?

Thanks

user1904273
  • 4,562
  • 11
  • 45
  • 96

2 Answers2

4
<?php
$returnpage = $_SERVER['HTTP_REFERER'] . '?querystring';

if (!isset($_REQUEST['id'])) 
{
    header("Location:$returnpage");
    exit();
}

Well, since after the first '?' all other '?' will be ignored you can do what I did above... It will work perfectly and it is totally valid.

Moreover, do not forget to exit or kill the application as after the header function the application will still continue to run if you do not quit explicitly.

But if you still insist on having one question mark then the snippet below will do the work...

$mark = strpos($_SERVER['HTTP_REFERER'], '?') === false ? '?' : '&';
$returnpage = $_SERVEr['HTTP_REFERER'] . $mark . 'abc=1&def=2&is=t';
Community
  • 1
  • 1
Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
  • I did not realize that subsequent ? are ignored and this is totally valid. I think the second option is better as it lets me add whatever parameters I wish – user1904273 Sep 01 '13 at 15:12
  • How does this work if the http_referer has a bunch of stuff as in emailstory.php?id=231&a=b&c=d and I want to append to it &error=1 – user1904273 Sep 01 '13 at 16:41
  • @user1904273 I don't understand what you mean. You can append as many parameters as you wish. – Savas Vedova Sep 01 '13 at 16:47
0

Perhaps you should check whether $_POST[id] is set or not

$strErrAppend = isset($_POST['id']) ? '&error=1' : '?error=1';

This should append &error=1 in case of emailstory.php?id=123 and ?error=1 in case of emailsignup.php