Home > OS >  Can't execute script if session not set
Can't execute script if session not set

Time:03-22

Good morning, I am trying to develop a link shortener system with statistics in php (5.6). One of these stats is the number of sessions. I am trying to use this logic:

if session doesn't exist
    start the session
    add  1 to the session field and  1 to the click field
else
    just add  1 to the click field.

With my first approach i tried to put session_start in the middle of the code and it didn't work. I realized I can't do it and I moved the statement in the first line of the code, making a big if condition.

<?php if (session_status() === PHP_SESSION_NONE) { session_start();
    ...config and stuff...
    $pdo->query("UPDATE links SET session = session   1 WHERE slug = '$slug'");
    $pdo->query("UPDATE links SET click = click   1 WHERE slug = '$slug'");
    } else {
    ...config and stuff...
    $pdo->query("UPDATE links SET click = click   1 WHERE slug = '$slug'");
    }
?>

When I debug this the session field is always updated, but it should increase only the first time. What am I missing?

Side note: this is the redirect page, i don't know if it is a useful info.

CodePudding user response:

session_status() === PHP_SESSION_NONE will always result in true before the session is actually started. You should use a flag instead. Just put session_start on the first line and do something like:

<?php
    session_start();
    if (!isset($_SESSION['flag'])) {
       $stmt = $pdo->prepare("UPDATE links SET session = session   1 WHERE slug = :slug");
       $stmt->execute([':slug' => $slug, ]);
       $_SESSION['flag'] = true;
    }
    
    $stmt = $pdo->query("UPDATE links SET click = click   1 WHERE slug = :slug");
    $stmt->execute([':slug' => $slug, ]);    

CodePudding user response:

session_status shows only status of current session, not if user has ever started a session. That's why your session_status() === PHP_SESSION_NONE are always true on first requests execution of that if statement.

Maybe you want to do something like storing some flag in session to indicate if it's user's first visit or not

session_start();

if (!isset($_SESSION['initialized'])) {
    $_SESSION['initialized'] = time();
    ...config and stuff...
    $pdo->query("UPDATE links SET session = session   1 WHERE slug = '$slug'");
    $pdo->query("UPDATE links SET click = click   1 WHERE slug = '$slug'");
} else {
    ...config and stuff...
    $pdo->query("UPDATE links SET click = click   1 WHERE slug = '$slug'");
}
  • Related