简体   繁体   中英

Session in php are not enough clear to me

I find sessions in php kind of confusing, can anybody of you explain those to me. I have an example which is not working in my case: I register sessions this way, would you please tell me is this the right way of registering sessions

 //this is the page from where i register myusername in sessions
if($count==1){
    session_start();
    $_SESSION['myusername'] = $_POST['myusername']; 
    include("enterpincover.php");
}
else {
    echo "Wrong Pin";
}

here i check first whether the username is registered in sessions in oder to open his account , otherwise open again login.

It works, if user is not loged in, it will show login page which is right, if user is loged it shows welcome message but not the Welcome the name of the user as I want. for ex: Welcome David

<?php
session_start();
if(isset($_SESSION['myusername']))
{
    echo 'Welcome '.$_SESSION['myusername']; 
}
else
{
    include("leftmodules.php");
    include("rightmodules.php");
    include("login.php");
}
?>

When registering a session with $_POST or $_GET , you should check if those variables exists.

Example :

if(isset($_POST['myusername'])) $_SESSION['myusername'] = $_POST['myusername'];
else die("Undefined \"myusername\"");

If you intend to use a variable from session in MySQL query, you should escape it before putting in a session (or cookie, or ANY other variable). Use mysql_real_escape_string() .

Example :

$_SESSION['myusername'] = mysql_real_escape_string($_POST['myusername']);

Also, always put your session_start() to the TOP of a script, before every other output or your script will not work (you'll get the headers already sent warning).

session_start() should be at the very top of page where is used sessions - right after <?php Setting session is correct and checking too. But I suppose You don't get into if part, because $count is 0 (You told that it is used to check whether username is registered in sessions. You can try to simply alert something if it goes inside if.

echo 'alert("test");';

I suppose You simply need session_start() at the top of document.

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