0

I'm trying to make a login session on PHP, but it appears that the $_SESSION['username'] dies inside the IF sentence (I thought $_SESSION where globals by default), and I cant echo it out of the IF

heres My code

if($name=="admin" && $password=="admin")
{
session_start();
$_SESSION['username'],$_SESSION['sesion'];
$_SESSION['username']=$name;
$_SESSION['sesion']=1;
echo $_SESSION['username'];
echo "<br>";
echo $_SESSION['sesion'];
}
echo "<br>";
echo $_SESSION['username'];

The last echo doesnt print its VALUE, So when I redirect it to another page, the page doesnt take the username value

I'm kind of new in this matter So dont be so harsh on me :P How can I do this??

3 Answers 3

3

Move session_start() to the top of the file:

// foo.php
<?php
  session_start();

  //....

  if($name=="admin" && $password=="admin")
  {
    // $_SESSION['username'],$_SESSION['sesion']; // Remove this line
    $_SESSION['username']=$name;
    $_SESSION['sesion']=1;
    echo $_SESSION['username'];
    echo "<br>";
    echo $_SESSION['sesion'];
  }
  echo "<br>";
  echo $_SESSION['username'];
Sign up to request clarification or add additional context in comments.

Comments

0

When You are using sessions in php You must start it with session_start() in every file/page You want to get or set session values, so just add this line to this file and that file You're redirecting to.

Comments

0

session_start() should be above the if statment. best to put it right below the ?php

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.