Bird
0
0

You want to count how many times a user visits a page using sessions. Which code correctly increments the visit count each time the page loads?

hard📝 Application Q15 of 15
PHP - Sessions and Cookies
You want to count how many times a user visits a page using sessions. Which code correctly increments the visit count each time the page loads?
<?php
// Fill in the missing part

if (isset($_SESSION['visits'])) {
    $_SESSION['visits']++;
} else {
    $_SESSION['visits'] = 1;
}
echo "Visit number: " . $_SESSION['visits'];
?>
Asession_start();
Bsession_destroy();
Csession_unset();
Dsession_write_close();
Step-by-Step Solution
Solution:
  1. Step 1: Recognize session must be started

    To use $_SESSION variables, the session must be started with session_start(); at the top.
  2. Step 2: Understand the code logic

    The code checks if 'visits' exists in the session, increments it if yes, or sets it to 1 if no, then prints the count.
  3. Final Answer:

    session_start(); -> Option A
  4. Quick Check:

    Start session before using $_SESSION to track visits [OK]
Quick Trick: Always call session_start() before session variables [OK]
Common Mistakes:
  • Forgetting session_start() causes no session data
  • Using session_destroy() resets visits
  • Confusing session_unset() with starting session

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes