duangouyan3328 2014-02-03 10:07
浏览 87
已采纳

聊天密码和用户名认证,获取IP和端口

Can you guys check this?I have a problem with this code i don't know which part but i think it's on the function authenticateUser. I just need to log in using this PHP in my android and when the user have logged in it will update the authenticationTime, IP and port but in my app i can only login and the table are not updated.

This is what happened it my table:

14 || rona       || aTzImAs21dN4fUersYiYXCA0WFE2ZGY1   ||   6df57d141e  ||  0000-00-00 00:00:00     ||  0   ||  0000-00-00 00:00:00     ||   ||       || 0||

This is what supposed to happen

14 || rona       || aTzImAs21dN4fUersYiYXCA0WFE2ZGY1   ||   6df57d141e  ||  0000-00-00 00:00:00     ||  0   ||  0000-00-00 00:00:00     ||   (user key here) || 127.0.0.1 ||    15145

now this is my PHP code please check!

<?php
/****************************************
*       Server of Android IM Application
*
*       Author: ahmet oguz mermerkaya
*       Email: ahmetmermerkaya@hotmail.com
*       Editor: Dominik Pirngruber
*       Email: d.pirngruber@gmail.com
*       Date: Jun, 25, 2013     
*   
*       Supported actions: 
*           1.  authenticateUser
*               if user is authentiated return friend list
*           
*           2.  signUpUser
*       
*           3.  addNewFriend
*       
*           4.  responseOfFriendReqs
*
*           5.  testWebAPI
*************************************/


//TODO:  show error off

require_once("mysql.class.php");

$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "healthhelp";


$db = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName);

// if operation is failed by unknown reason
define("FAILED", 0);

define("SUCCESSFUL", 1);
// when  signing up, if username is already taken, return this error
define("SIGN_UP_USERNAME_CRASHED", 2);  
// when add new friend request, if friend is not found, return this error 
define("ADD_NEW_USERNAME_NOT_FOUND", 2);

// TIME_INTERVAL_FOR_USER_STATUS: if last authentication time of user is older 
// than NOW - TIME_INTERVAL_FOR_USER_STATUS, then user is considered offline
define("TIME_INTERVAL_FOR_USER_STATUS", 60);

define("USER_APPROVED", 1);
define("USER_UNAPPROVED", 0);


$username = (isset($_REQUEST['username']) && count($_REQUEST['username']) > 0) 
                            ? $_REQUEST['username'] 
                            : NULL;
$password = isset($_REQUEST['password']) ? md5($_REQUEST['password']) : NULL;
$port = isset($_REQUEST['port']) ? $_REQUEST['port'] : NULL;

$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : NULL;
if ($action == "testWebAPI")
{
    if ($db->testconnection()){
    echo SUCCESSFUL;
    exit;
    }else{
    echo FAILED;
    exit;
    }
}

if ($username == NULL || $password == NULL)  
{
    echo FAILED;
    exit;
}

$out = NULL;

error_log($action."
", 3, "error.log");
switch($action) 
{

    case "authenticateUser":


        if ($userId = authenticateUser($db, $username, $password)) 
        {                   

            // providerId and requestId is Id of  a friend pair,
            // providerId is the Id of making first friend request
            // requestId is the Id of the friend approved the friend request made by providerId

            // fetching friends, 
            // left join expression is a bit different, 
            //      it is required to fetch the friend, not the users itself

            $sql = "select u.Id, u.username, (NOW()-u.authenticationTime) as authenticateTimeDifference, u.IP, 
                                        f.providerId, f.requestId, f.status, u.port 
                            from friends f
                            left join users u on 
                                        u.Id = if ( f.providerId = ".$userId.", f.requestId, f.providerId ) 
                            where (f.providerId = ".$userId." and f.status=".USER_APPROVED.")  or 
                                         f.requestId = ".$userId." ";

            //$sqlmessage = "SELECT * FROM `messages` WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 ";

            $sqlmessage = "SELECT m.id, m.fromuid, m.touid, m.sentdt, m.read, m.readdt, m.messagetext, u.username from messages m 
"
    . "left join users u on u.Id = m.fromuid WHERE `touid` = ".$userId." AND `read` = 0 LIMIT 0, 30 ";


            if ($result = $db->query($sql))         
            {
                    $out .= "<data>"; 
                    $out .= "<user userKey='".$userId."' />";
                    while ($row = $db->fetchObject($result))
                    {
                        $status = "offline";
                        if (((int)$row->status) == USER_UNAPPROVED)
                        {
                            $status = "unApproved";
                        }
                        else if (((int)$row->authenticateTimeDifference) < TIME_INTERVAL_FOR_USER_STATUS)
                        {
                            $status = "online";

                        }
                        $out .= "<friend  username = '".$row->username."'  status='".$status."' IP='".$row->IP."' userKey = '".$row->Id."'  port='".$row->port."'/>";

                                                // to increase security, we need to change userKey periodically and pay more attention
                                                // receiving message and sending message 

                    }
                        if ($resultmessage = $db->query($sqlmessage))           
                            {
                            while ($rowmessage = $db->fetchObject($resultmessage))
                                {
                                $out .= "<message  from='".$rowmessage->username."'  sendt='".$rowmessage->sentdt."' text='".$rowmessage->messagetext."' />";
                                $sqlendmsg = "UPDATE `messages` SET `read` = 1, `readdt` = '".DATE("Y-m-d H:i")."' WHERE `messages`.`id` = ".$rowmessage->id.";";
                                $db->query($sqlendmsg);
                                }
                            }
                    $out .= "</data>";
            }
            else
            {
                $out = FAILED;
            }           
        }
        else
        {
                // exit application if not authenticated user
                $out = FAILED;
        }



    break;

    case "signUpUser":
        if (isset($_REQUEST['email']))
        {
             $email = $_REQUEST['email'];       

             $sql = "select Id from  users 
                            where username = '".$username."' limit 1";



             if ($result = $db->query($sql))
             {
                    if ($db->numRows($result) == 0) 
                    {
                            $sql = "insert into users(username, password, email)
                                values ('".$username."', '".$password."', '".$email."') ";                          

                                error_log("$sql", 3 , "error_log");
                            if ($db->query($sql))   
                            {
                                    $out = SUCCESSFUL;
                            }               
                            else {
                                    $out = FAILED;
                            }                           
                    }
                    else
                    {
                        $out = SIGN_UP_USERNAME_CRASHED;
                    }
             }                      
        }
        else
        {
            $out = FAILED;
        }   
    break;

    case "sendMessage":
    if ($userId = authenticateUser($db, $username, $password)) 
        {   
        if (isset($_REQUEST['to']))
        {
             $tousername = $_REQUEST['to']; 
             $message = $_REQUEST['message'];   

             $sqlto = "select Id from  users where username = '".$tousername."' limit 1";



                    if ($resultto = $db->query($sqlto))         
                    {
                        while ($rowto = $db->fetchObject($resultto))
                        {
                            $uto = $rowto->Id;
                        }
                        $sql22 = "INSERT INTO `messages` (`fromuid`, `touid`, `sentdt`, `messagetext`) VALUES ('".$userId."', '".$uto."', '".DATE("Y-m-d H:i")."', '".$message."');";                       

                                error_log("$sql22", 3 , "error_log");
                            if ($db->query($sql22)) 
                            {
                                    $out = SUCCESSFUL;
                            }               
                            else {
                                    $out = FAILED;
                            }                       
                        $resultto = NULL;
                    }   

        $sqlto = NULL;
        }
        }
        else
        {
            $out = FAILED;
        }   
    break;

    case "addNewFriend":
        $userId = authenticateUser($db, $username, $password);
        if ($userId != NULL)
        {

            if (isset($_REQUEST['friendUserName']))         
            {               
                 $friendUserName = $_REQUEST['friendUserName'];

                 $sql = "select Id from users 
                                 where username='".$friendUserName."' 
                                 limit 1";
                 if ($result = $db->query($sql))
                 {
                        if ($row = $db->fetchObject($result))
                        {
                             $requestId = $row->Id;

                             if ($row->Id != $userId)
                             {
                                     $sql = "insert into friends(providerId, requestId, status)
                                         values(".$userId.", ".$requestId.", ".USER_UNAPPROVED.")";

                                     if ($db->query($sql))
                                     {
                                            $out = SUCCESSFUL;
                                     }
                                     else
                                     {
                                            $out = FAILED;
                                     }
                            }
                            else
                            {
                                $out = FAILED;  // user add itself as a friend
                            }                                                
                        }
                        else
                        {
                            $out = FAILED;                      
                        }
                 }                               
                 else
                 {
                        $out = FAILED;
                 }              
            }
            else
            {
                    $out = FAILED;
            }           
        }
        else
        {
            $out = FAILED;
        }   
    break;

    case "responseOfFriendReqs":
        $userId = authenticateUser($db, $username, $password);
        if ($userId != NULL)
        {
            $sqlApprove = NULL;
            $sqlDiscard = NULL;
            if (isset($_REQUEST['approvedFriends']))
            {
                  $friendNames = split(",", $_REQUEST['approvedFriends']);
                  $friendCount = count($friendNames);
                  $friendNamesQueryPart = NULL;
                  for ($i = 0; $i < $friendCount; $i++)
                  {
                    if (strlen($friendNames[$i]) > 0)
                    {
                        if ($i > 0 )
                        {
                            $friendNamesQueryPart .= ",";
                        }

                        $friendNamesQueryPart .= "'".$friendNames[$i]."'";

                    }               

                  }
                  if ($friendNamesQueryPart != NULL)
                  {
                    $sqlApprove = "update friends set status = ".USER_APPROVED."
                                    where requestId = ".$userId." and 
                                                providerId in (select Id from users where username in (".$friendNamesQueryPart."));
                                ";      
                  }

            }
            if (isset($_REQUEST['discardedFriends']))
            {
                    $friendNames = split(",", $_REQUEST['discardedFriends']);
                  $friendCount = count($friendNames);
                  $friendNamesQueryPart = NULL;
                  for ($i = 0; $i < $friendCount; $i++)
                  {
                    if (strlen($friendNames[$i]) > 0)
                    {
                        if ($i > 0 )
                        {
                            $friendNamesQueryPart .= ",";
                        }

                        $friendNamesQueryPart .= "'".$friendNames[$i]."'";

                    }                   
                  }
                  if ($friendNamesQueryPart != NULL)
                  {
                    $sqlDiscard = "delete from friends 
                                        where requestId = ".$userId." and 
                                                    providerId in (select Id from users where username in (".$friendNamesQueryPart."));
                                            ";
                  }                     
            }
            if (  ($sqlApprove != NULL ? $db->query($sqlApprove) : true) &&
                        ($sqlDiscard != NULL ? $db->query($sqlDiscard) : true) 
               )
            {
                $out = SUCCESSFUL;
            }
            else
            {
                $out = FAILED;
            }       
        }
        else
        {
            $out = FAILED;
        }
    break;

    default:
        $out = FAILED;      
        break;  
}

echo $out;



///////////////////////////////////////////////////////////////
function authenticateUser($db, $username, $password)
{       

    $sql22 = "select * from users 
                    where username = '".$username."' and password = '".$password."' 
                    limit 1";


     $no_of_rows = mysql_num_rows($sql22);
        if ($no_of_rows > 0) {
            $sql22 = mysql_fetch_array($sql22);
            $salt = $sql22['salt'];
            $encrypted_password = $sql22['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $sql22;
            }
        } else {
            // user not found
            return false;
        }

    $out = NULL;
    if ($result22 = $db->query($sql22))
    {
        if ($row22 = $db->fetchObject($result22))
        {
                $out = $row22->Id;

                $sql22 = "update users set authenticationTime = NOW(), 
                                                                 IP = '".$_SERVER["REMOTE_ADDR"]."' ,
                                                                 port = 15145 
                                where Id = ".$row22->Id."
                                limit 1";

                $db->query($sql22);             


        }       
    }

    return $out;
}

    function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

?>

The signUp part is not used already coz in my own application i register it with other feild such as fname,lname and password is encrypted. I just found this php on web and i just want this to implement in my project. Please help me.

EDIT

function authenticateUser($db, $username, $password)
{       

    $sql22 = "select * from users 
                    where username = '".$username."' and password = '".$password."' 
                    limit 1";


//$sql11 =  mysql_query("SELECT * FROM users WHERE username = '$username'") or die(mysql_error());

    $no_of_rows = mysql_num_rows($db->query($sql22));
        if ($no_of_rows > 0) {
            $sql22 = mysql_fetch_array($sql22);
            $salt = $sql22['salt'];
            $encrypted_password = $sql22['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $sql22;
            }
        } else {
            // user not found
            return false;
        }



    $out = NULL;
    $result22 = $db->query($sql22);
 if ($result22)
    {
        while($row22 = $db->fetchObject($result22))
        {
            $out = $row22->Id;

            $sql22 = "update users set authenticationTime = NOW(),
                                                                 IP = '".$_SERVER["REMOTE_ADDR"]."' ,
                                                                 port = 15145
                                where Id = ".$row22->Id."
                                limit 1";

            $db->query($sql22);


        }
    }   



}

mysql.class.php

<?php
/************************************************
*
*   File Name:   mysql.php
*   Begin:       Sunday, Dec, 23, 2005
*   Author:      ahmet oðuz mermerkaya  
*   Email:       ahmetmermerkaya@hotmail.com
*   Description: Class to connect mysql database
*   Edit :       Sunday, Nov, 18, 2007
*   Version:     1.1
*
***********************************************/ 

class MySQL
{   
    private $dbLink;
    private $dbHost;
    private $dbUsername;
        private $dbPassword;
    private $dbName;
    public  $queryCount;

    function MySQL($dbHost,$dbUsername,$dbPassword,$dbName)
    {
        $this->dbHost = $dbHost;
        $this->dbUsername = $dbUsername;
        $this->dbPassword = $dbPassword;
        $this->dbName = $dbName;    
        $this->queryCount = 0;      
    }
    function __destruct()
    {
        $this->close();
    }
    //connect to database
    private function connect() {    
        $this->dbLink = mysql_connect($this->dbHost, $this->dbUsername, $this->dbPassword);     
        if (!$this->dbLink) {           
            $this->ShowError();
            return false;
        }
        else if (!mysql_select_db($this->dbName,$this->dbLink)) {
            $this->ShowError();
            return false;
        }
        else {
            mysql_query("set names latin5",$this->dbLink);
            return true;
        }
        unset ($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);     
    }   
    /*****************************
     * Method to close connection *
     *****************************/
    function close()
    {
        @mysql_close($this->dbLink);
    }
    /*******************************************
     * Checks for MySQL Errors
     * If error exists show it and return false
     * else return true  
     *******************************************/
    function ShowError()
    {
        $error = mysql_error();
        //echo $error;      
    }   
    /****************************
     * Method to run SQL queries
     ****************************/
    function  query($sql)
    {   
        if (!$this->dbLink) 
            $this->connect();

        if (! $result = mysql_query($sql,$this->dbLink)) {
            $this->ShowError();         
            return false;
        }
        $this->queryCount++;    
        return $result;
    }
    /************************
    * Method to fetch values*
    *************************/
    function fetchObject($result)
    {
        if (!$Object=mysql_fetch_object($result))
        {
            $this->ShowError();
            return false;
        }
        else
        {
            return $Object;
        }
    }
    /*************************
    * Method to number of rows
    **************************/
    function numRows($result)
    {
        if (false === ($num = mysql_num_rows($result))) {
            $this->ShowError();
            return -1;
        }
        return $num;        
    }
    /*******************************
     * Method to safely escape strings
     *********************************/
    function escapeString($string)
    {
        if (get_magic_quotes_gpc()) 
        {
            return $string;
        } 
        else 
        {
            $string = mysql_escape_string($string);
            return $string;
        }
    }

    function free($result)
    {
        if (mysql_free_result($result)) {
            $this->ShowError();
            return false;
        }   
        return true;
    }

    function lastInsertId()
    {
        return mysql_insert_id($this->dbLink);
    }

    function getUniqueField($sql)
    {
        $row = mysql_fetch_row($this->query($sql));

        return $row[0];
    }
    function testconnection() { 
        $this->dbLink = mysql_connect($this->dbHost, $this->dbUsername, $this->dbPassword);     
        if (!$this->dbLink) {           
            $this->ShowError();
            return false;
        }
        else if (!mysql_select_db($this->dbName,$this->dbLink)) {
            $this->ShowError();
            return false;
        }
        else {
            mysql_query("set names latin5",$this->dbLink);
            return true;
        }
        unset ($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);     
    }       
}
  • 写回答

1条回答 默认 最新

  • dongzhong7443 2014-02-03 10:11
    关注

    You are doing something seriously wrong here on your authenticateUser()

    function authenticateUser($db, $username, $password)
    {
    
        $sql22 = "select * from users 
                        where username = '".$username."' and password = '".$password."' 
                        limit 1";
        $no_of_rows = mysql_num_rows($sql22);// <-------- You are passing a string here instead of a resource !
    

    Also, the if statement doesn't look right.

    if ($row22 = $db->fetchObject($result22))
    {
    

    The Mistakes

    • You are not at all executing the query.
    • You are passing a string to the mysql_num_rows()

    Rewrite like this.

     $result22 = $db->query($sql22);
     if ($result22)
        {
            while($row22 = $db->fetchObject($result22))
            {
                $out = $row22->Id;
    
                $sql22 = "update users set authenticationTime = NOW(),
                                                                     IP = '".$_SERVER["REMOTE_ADDR"]."' ,
                                                                     port = 15145
                                    where Id = ".$row22->Id."
                                    limit 1";
    
                $db->query($sql22);
    
    
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 基于52单片机的酒精浓度检测系统加继电器和sim800
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答