登录在第一次尝试在实时服务器上不起作用

时间:2013-12-26 13:32:09

标签: php login

我是PHP的新手,我做了一个简单的登录页面。它在本地服务器上工作正常,但在首次尝试使用实时服务器时不起作用。在第一次尝试后,然后工作。我认为问题出在会话中,但我无法弄清楚确切的问题。再次详细描述(在第一次尝试后的任何浏览器中,它显示相同的登录页面,而不是main.php上的重定向。然后在第二次尝试后,它重定向到main.php页面并正常工作,直到浏览器运行。第二天再次需要它如果第1次尝试时错误的凭据正常工作,但尝试正确,则需要尝试2次尝试。)

**login.php**
<form action="login.php" method="post" onsubmit="return loginvalidate()" name="loginfrm">
<table width="600" border="0">
  <tr>
    <td>User Name</td>
    <td><input name="txtusername" type="text" maxlength="15" id="txtusername"/></td> 
    <span id="message"></span>
  </tr>
  <tr>
    <td></td>
    <td><span style="color:#FF0000">*</span> Minimum 5 alphanumeric letters (a-z A-Z 0-9)</td></tr>
  <tr>

    <td>Password</td>

    <td><input name="txtpass" type="password" maxlength="7" />

    <span style="color:#FF0000">*</span> Minimum 5 alphanumeric letters (a-z A-Z 0-9)</td>

  </tr>

  <tr>

    <td>&nbsp;</td>

    <td><input type="submit" name="submit"/></td>

  </tr>

   <tr>

    <td><a href="">Forget password?</a></td>

    <td><a href="registration.php">New Register</a></td>

  </tr>

  </table>

</form>



<?PHP

session_start();
function login()
{
include ("includes/dbConfig.php");
$uname = $_POST["txtusername"];
$pass = $_POST["txtpass"];
$uname = stripslashes($uname); 
$pass =  stripslashes($pass);
$uname = mysql_real_escape_string($uname);
$pass = mysql_real_escape_string($pass);
$log = mysql_query("SELECT * FROM logininfo WHERE username = '$uname' and password = '$pass'");
if(mysql_num_rows($log)==1)
{
  $_SESSION["username"] = $uname;
  //header("location: main.php");
  echo ("<script type='text/javascript'>window.location.href='main.php'</script>");                 
}
else
{
  echo "<script type='text/javascript'>alert('Login Fail - Check Username and password')</script>";
}
mysql_close($ms);
}

if(isset($_POST['submit']))
{
   login();
} 
?>

main.php

<?php
session_start();
$temp = $_SESSION["username"];
echo "$temp";
if (!isset($_SESSION["username"]))
{
header('Location: admin.php');
}
?>

1 个答案:

答案 0 :(得分:0)

你把session_start();在页面顶部但不在登录功能中。使用此代码。

 **login.php**  

<?PHP
function login()
{
include ("includes/dbConfig.php");
$uname = $_POST["txtusername"];
$pass = $_POST["txtpass"];
$uname = stripslashes($uname); 
$pass =  stripslashes($pass);
$uname = mysql_real_escape_string($uname);
$pass = mysql_real_escape_string($pass);
$log = mysql_query("SELECT * FROM logininfo WHERE username = '$uname' and password = '$pass'");
    if(mysql_num_rows($log)==1)
    {
    session_start();
    $_SESSION["username"] = $uname;
        //header("location: main.php");
    echo ("<script type='text/javascript'>window.location.href='main.php'</script>");               
}
else
{
    echo "<script type='text/javascript'>alert('Login Fail - Check Username and password')</script>";

    }
mysql_close($ms);
}

  if(isset($_POST['submit']))
 {
    login();
 } 
?>