tags:

views:

54

answers:

2

I am new to php and trying to write a login function. Bit stuck and getting the error. here my function:

<?php

if(!defined('_VALID_ACCESS')) die('direct access is not allowed.');
include('includes/connect.php'); 

function login($username, $password)
{
    $username = trim($username);
    $password = trim($password);
    echo $username;
    echo $password;
    $login_sql  = "SELECT * FROM user WHERE user = '".($username)."' 
    AND pass = '".(md5($password))."'";
    $login_result = $mysqli->query($login_sql) or die(mysqli_error());
    $row=$login_result->fetch_row();
    if($row[0] == 1)
    {
     return true;
    }
    else
    {
     return false;
    }
}
?>

connect.php

<?php
$db_name = "coolmates";
$db_server = "localhost";
$db_user = "justron";
$db_pass = "Justron9004";

$mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name) or die(mysqli_error());

?>

Notice: Undefined variable: mysqli in ..\login.php on line 14

Fatal error: Call to a member function query() on a non-object in ..\login.php on line 14

help me.

+4  A: 

You're missing the global identifier. Namely:

function login($username, $password)
{
    global $mysqli;
    $username = trim($username);
    $password = trim($password);
    echo $username;
    echo $password;
    $login_sql  = "SELECT * FROM user WHERE user = '".($username)."' 
    AND pass = '".(md5($password))."'";
    $login_result = $mysqli->query($login_sql) or die(mysqli_error());
    $row=$login_result->fetch_row();
    if($row[0] == 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

One thing I'd like to add: don't construct SQL like that, particularly when using mysqli. Use bind parameters. Do this:

$login_result = $mysqli->query("SELECT COUNT(1) result FROM user WHERE user = ? AND pass = ?");
$login_result->bind_param("ss", $username, md5($password));
$login_result->execute();
$login_result->bind_result($count);
$login_result->fetch();
if ($count == 1) {
  // success
} else {
  // failure
}
cletus
Go one step further and change the end of the login function to be:return ($row[0] == 1);
Nerdling
+4  A: 

The problem is "Include" died silently. This is a lovely feature of PHP that Includes will just not tell you when they were unsuccessful.

Replace your "include" with "require" so that it will fatally die when the file is not found.

Also, go read up on SQL Injection and XSS security NOW. Your SQL is BRUTALLY insecure, and attempted logins with username set to ( literally, quotes included )

' or true or '' = '

will instantly make a would-be attackers life an easier task.

select 'hello' = '' or true or '' = '' and 'world' = '1';

returns "true" you see.

Kent Fredric