douyinyi7766 2016-02-17 07:58
浏览 49
已采纳

PHP:使用会话变量时,登录页面无法进入主页

I have a login page(checklogin.php) that leads to my website's homepage(index.php) on successful sign in. In order to ensure that index.php (& every page in the website) can only be accessed through the login page, i've made use of a session variable which is checked at the start of index.php as follows:

<?php
session_start();
if( !isset($_SESSION['myusername']) )
header("location:checklogin.php"); 
?>

After adding this, logging in through checklogin.php results in an error('wrong username, password' - even thought both are approved); when i get rid of the above session code in the index.php, the homepage opens without error.

Below is the code in checklogin.php:

<?php

$host="localhost"; // Host name 
$username="garbo45"; // Mysql username 
$password="water5"; // Mysql password 
$db_name="garbo45"; // Database name 
$tbl_name="members"; // Table name 

// Connect to server and select database.
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) die($conn->connect_error);

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($conn, $myusername);
$mypassword = mysqli_real_escape_string($conn, $mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($conn, $sql);

// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "loginsuccess.php"
$_SESSION['myusername']= "myusername"; 
$_SESSION['mypassword']= "mypassword"; 
header("location:index.php");
}
else {
echo "Wrong Username or Password";
}
?>

Why is the session code block in the index.php causing this error when the username and password (which i've verified is among those set in the members table) goes through as soon as the session checking is removed? Would appreciate any help in understanding and addressing this.

  • 写回答

1条回答 默认 最新

  • dongzhanjuan5141 2016-02-17 08:02
    关注

    You are missing session_start() on your checklogin.php.

    Without session_start() your following code will not work :

    $_SESSION['myusername']= "myusername"; 
    $_SESSION['mypassword']= "mypassword"; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab