user3762389
user3762389

Reputation: 51

Redirecting to the previous page in PHP

Im aware header('Location: ' . $_SERVER['HTTP_REFERER']); has some security concerns attached to it. However I need to drive a user back to the page he has come from. Just wanted to understand if I store the the page that user came in a cookie and after may be a sign in use the cookie information to redirect the user back to the page? Does that sound secure? Like to here if you have a better suggestion for me? Thank you.

Upvotes: 1

Views: 77

Answers (3)

Ilia Ross
Ilia Ross

Reputation: 13412

There are multiple ways of doing it. I would do it server side.

Example:

class Page
  {    

    public function define()
      {
         empty( $_SESSION['SCRIPT_NAME'] ) && $_SESSION['SCRIPT_NAME'] = 'http://example.com'; // default page
         in_array( $_SERVER['SCRIPT_NAME'], $this->defined()) && $_SESSION['RECOIL_PAGE'] = $_SERVER['REQUEST_URI']; // if the current page is in allowed list, make it recoil page (let user return to it)
      }

    public function defined()
      {
        return array(
            '/index.php',
            '/categories.php',
            '/videos.php',
            '/upload.php'
        );
      }

    public function recoil()
      {
        header( 'Location: ' . $_SESSION['RECOIL_PAGE'] );
        exit;
      }
  }

Usage:

  • On load: $this->page->define(); // To check if the page should be set as allowed, recoil page
  • On execute: $this->page->recoil(); // To redirect a user to the possible recoil page, if not in the list, then redirect to default one

Upvotes: 1

PixelsTech
PixelsTech

Reputation: 3347

I think this method is safe. Although our site is using session to redirect the user back to the previous page after login. It has the same effect as using a cookie.

Using $_SERVER["HTTP_REFERER"] is not reliable. Sometimes it may contain an invalid value. So it's not recommended.

Upvotes: 0

Ayush Ghosh
Ayush Ghosh

Reputation: 487

No its okay, just inform the user that he is being redirected back, It is always used in OAuth, as return url, remember in Facebook, Google or twitter login in any app.

Just make sure that you really intended the user to go back where he come from.

Upvotes: 0

Related Questions