Stephen DuVall
Stephen DuVall

Reputation: 31

Validate admin is logged in php

I have a php script that generates an RSS feed, but I only want it to be accessible by admins. I currently use this method

if($_SESSION['isAdmin'] != true) {
  $_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
  header("Location: /");
}

It works on other pages but for some reason it not working here.

I want it the page to, validate the user is an admin ($_SESSION['isAdmin] == true), execute the script updating the RSS file, the redirect back to the regular admin page.

Here is a basic skeleton of the page. I removed all the stuff that doesn't matter

<?php

  if($_SESSION['isAdmin'] != true) {
    $_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
    header("Location: /");
  }

  $file = fopen('rss.xml', "w") or die("Unable to open file");

  try {
    // Connect to db
    $conn = new PDO("mysql:host=" . SERVERNAME . ";" . "dbname=" . DBNAME, USERNAME, PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = $conn->query('SELECT * FROM * ORDER BY upload_date DESC ');
    $result = $query->fetchAll(PDO::FETCH_OBJ);

    $rssfeed = 'This gets set based on what the db returns';

  } catch (PDOException $e) {
    echo $e->getMessage();
  }

  fwrite($file, $rssfeed);
  fclose($file);

  header("Location: /admin.php");

In my testing, when I'm not logged in, it still executes the script (generating the rss.xml file), then redirects me back to the admin page. Which I'm not logged in so that redirects me back to / with the error saying I'm not allowed to access admin.php

Upvotes: 0

Views: 387

Answers (3)

Stephen DuVall
Stephen DuVall

Reputation: 31

After reading the comments I realized I never started the session with session_start();🤦

However I also added exit(); to the end of the redirect because that seems like good practice I guess.

Still learning a lot about php so any advice you guys give me is much appreciated. Thanks for the help!!

Upvotes: 0

Mzndako
Mzndako

Reputation: 82

Add exit() to the end of the location header redirect. This will prevent the code after that from being executed.

<?php

  if($_SESSION['isAdmin'] != true) {
    $_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
    header("Location: /");
    exit(); // It will stop here.
  }

// The rest of the code
.........

Upvotes: 2

RalfFriedl
RalfFriedl

Reputation: 1130

You need to exit after sending the Location header.

The header function just adds a header to the result that will be sent eventually. As you don't exit, all the code that follows is still executed, and the output from that code is sent to the client, together with the Location header.

Upvotes: 3

Related Questions