Abu Nooh
Abu Nooh

Reputation: 856

Ajax get passed PHP session variable

I'm using AJAX to delete rows in my db, the ajax is fine passing the ID but I want to be able to use the session that's already present as an added field to make sure users cant delete without being logged in.

Here's my php file:

if(!isset($_SESSION['username']))
{
    echo "<p>You must be logged in to view this page.</p>";
}
else
    session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once './db/conn.php';

if(isset($_GET['delete'])) {
    $user = $_SESSION['username'];
    $sqldel = 'DELETE FROM _bookmarks WHERE bookmark_id =  :ID AND username = :USER';
    $preparedStatement = $conn->prepare($sqldel);
    $preparedStatement->execute(array(':ID' => $_GET['delete'],':USER' => $user));
}

It doesn't seem to find the session to delete it also i'm not getting any errors from the console. It worked then I logged out to try again then it stopped working. I've added session_start() to make sure but that doesn't work either.

if I go direct to the page then it says I need to be logged in which I am.

Upvotes: 0

Views: 759

Answers (1)

Rasclatt
Rasclatt

Reputation: 12505

Session start needs to go at the top of the page. You are checking if the $_SESSION['username'] exists before starting the session:

// Move session_start() here
session_start();

// This should now check for this session variable
if(!isset($_SESSION['username'])) {
    echo "<p>You must be logged in to view this page.</p>";
 }
else {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    require_once './db/conn.php';
    if(isset($_GET['delete'])) {
        $user = $_SESSION['username'];
        $sqldel = 'DELETE FROM _bookmarks WHERE bookmark_id =  :ID AND username = :USER';
        $preparedStatement = $conn->prepare($sqldel);
        $preparedStatement->execute(array(':ID' => $_GET['delete'],':USER' => $user));
    }
}

Upvotes: 1

Related Questions