简体   繁体   中英

Php simple login script via session

I'm new to php and I'm having issues with creating a login scripts. In the first part of code, it can find the correct id belonging to the person logging in and sets in correctly in the $_SESSION['id']. Then the script redirects back to the index but here I get an error saying the id isn't set in the session.

Notice: Undefined index: id in C:\\xampp\\htdocs\\gym\\v1\\content\\body\\panel.php on line 11

$sql="SELECT id FROM user WHERE email='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

$count=mysql_num_rows($result);

if($count==1){
    session_regenerate_id(); //Regenerate session ID to prevent session fixation attacks
    $member = mysql_fetch_assoc($result);
    $_SESSION['id'] = $member['id'];
    session_write_close();
    header("location: ../index.php?page=2");
    exit();
}
else {
    header("Location: ../index.php?page=1");
    exit();
}
?>

session_start();
echo 'session id:' . $_SESSION['id'];
if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) {
    echo 'error not session id set';
    exit();
}
$sql="SELECT * FROM user WHERE id='" . $_SESSION['id'] . "'";
$result=mysql_query($sql);

$member = mysql_fetch_assoc($result);
$mail = $member['emails'];

echo '<h1>Welcome!'. $mail  . ' </h1>';

thanks in advance

In your login script, you never call session_start() prior to setting $_SESSION['id'] .

Also, It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article .

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