1

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;
    }
    ?>
5
  • Please show your form code Commented May 6, 2015 at 8:50
  • Typo echo "Welcome $_SESSION[userid]"; must be echo "Welcome $_SESSION['userid']"; it won't solve your problem Commented May 6, 2015 at 8:51
  • Hei @r33drum why you changed the correct answer to another answer after some time and down voted my answer since it is working? Commented May 6, 2015 at 9:11
  • @Sanjay Kumar N S I cant vote, I don't have 15 rep, I used your code and it worked, I appreciate it, I gave you the correct answer. Commented May 6, 2015 at 9:13
  • @r33drum now it came. Commented May 6, 2015 at 9:19

3 Answers 3

2

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;
        }
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }

Comments

0
  • 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.