Search code examples
phpauthenticationsession-variables

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


Solution

  • 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!!