Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't execute script if session not set

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading