Search code examples
phphttp-redirecturlvariables

PHP: How to check if URL link contains variable to prevent redirecting (rest of code working)


I am new to PHP and hope someone can help me with this.

I am trying to cover the following scenarios in a header file that is included on all my pages:

  1. IF session variable "status" is not set AND page name is not "login" or "user" THEN redirect to login page.
  2. IF session variable "status" is not set AND page name is "user" AND variable "resetToken" is not set THEN redirect to login page.

So far I have the below which works for all pages when accessing them from the browser but when I use a link from an email like the following I still get redirected even if the link contains the variable "resetToken":

Example link: https://www.myurl.com/user.php?resetToken=abcde

My PHP (in header include):

$baseURL = "https://www.myurl.com";
$pageURL = basename($_SERVER["REQUEST_URI"]);
$pageName = pathinfo(parse_url($pageURL, PHP_URL_PATH), PATHINFO_FILENAME);

if( (!isset($_SESSION["status"])) && ($pageName != "login") && ($pageName != "user") ){
    header("Location: " . $baseURL . "/login.php");
    exit;
}
if( (!isset($_SESSION["status"])) && ($pageName == "user") && (!isset($_GET["resetToken"])) ){
    header("Location: " . $baseURL . "/login.php");
    exit;
}

I have two questions regarding this:

  1. Does $_GET not work when accessing a page through an email link or do I have to change something else here ?
  2. Is there a way to combine these checks in one IF statement instead of having two in a row ?

Many thanks for any help, Mike


Solution

    1. $_GET does work no matter where the url was clicked
    2. combining the two statements is easy, just wrap them with () and combine them with ||

    PHP

    if( 
        (
            (!isset($_SESSION["status"])) && ($pageName != "login") && 
            ($pageName != "user")
        ) || (
            (!isset($_SESSION["status"])) && ($pageName == "user") && 
            (!isset($_GET["resetToken"])) 
        )   
    ){
        header("Location: " . $baseURL . "/login.php");
        exit;
    }
    

    When it is redirecting even tho you have set the token you should dump the variable before. The code as it is should not redirect when the token is set.