简体   繁体   中英

PHP storing session data, storing userid in session

Sorry but I'm new to this. The following code only displays 'Please login'. Code does work but it's not doing what I want it to, I'm trying to store userid in a session. Here is my code

<?php

    if(!isset($_SESSION)) session_start();


    if(isset($_POST['userid'])){
         $userid = $_POST['userid']; 
         $_SESSION['userid']=$userid;
         echo "Welcome $_SESSION[userid]";
    }

    if (!isset($_SESSION['userid'])){
        echo "Please login";
        exit;
    }
    ?>

session_start(); shouldn't be in your if condition, it has to be at the beginning of the script and always launched

<?php

    session_start();


    if(isset($_POST['userid'])){
        $_SESSION['userid']= $_POST['userid'];
        echo "Welcome ".$_SESSION['userid'];
    }

    if (!$_SESSION['userid']){
        echo "Please login";
        exit;
    }

session_start() should be at the beginning without any condition. And also one extra closing bracket ) in the second if condition statement. Try this:

 <?php
   session_start();


        if(isset($_POST['userid'])){
            $_SESSION['userid']= $_POST['userid'];
            echo "Welcome {$_SESSION['userid']}";
        }

        if (!$_SESSION['userid']){
            echo "Please login";
            exit;
        }
  • session_start() need to be before you start to work with session.
  • I suggest you to replace isset() by empty(), because empty() checked for:
    • "" (an empty string)
    • 0 (0 as an integer)
    • 0.0 (0 as a float)
    • "0" (0 as a string)
    • NULL
    • FALSE
    • array() (an empty array)
    • $var; (a variable declared, but without a value)

Thanks for answering. It works now, I was also defining the wrong session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM