公共用户未登录时访问时为会话设置的条件

时间:2015-10-23 11:01:26

标签: php

<?php

$connection = mysql_connect("localhost", "root", "");

$db = mysql_select_db("tumy", $connection);
session_start();

$user_check=$_SESSION['username'];

$ses_sql=mysql_query("select username from customer where   username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
//if(!isset($_SESSION['username'])){
//header('Location: homepage.php');
//}

?>

我是否知道在公众访问我的网站时是否需要设置任何条件? 因为它显示

undefined index: username in $user_check.

当标题Location: homepage.php时,它会直接显示空白页。

我可以知道它的解决方案吗?

2 个答案:

答案 0 :(得分:0)

我认为您需要对逻辑/流程有所帮助。这将是我使用您的代码建议的方法:

// always start this first
session_start();

// check for logged-in user..
if(!isset($_SESSION['username'])){

    // ..and redirect if necessary
    header('Location: homepage.php');
    exit;

} else {

    // only do a db connection if needed
    $connection = mysql_connect("localhost", "root", "");
    $db = mysql_select_db("tumy", $connection);

    $user_check = $_SESSION['username'];

    $ses_sql=mysql_query("select username from customer where   username='$user_check'", $connection);
    $row = mysql_fetch_assoc($ses_sql);

    if($row['username'] != ''){
        $_SESSION['username'] = $row['username'];
    }

    // redirect if required.. ..or continue

}

我希望这会有所帮助。

答案 1 :(得分:0)

session_start();  must be on top of the file.

你可以使用条件

$user_check = isset($_SESSION['username'])?$_SESSION['username']:"";