开发者

Conditions in PHP

How can I simplify this PHP condition?

<?php
function authUser( $user, $pass )
{
    switch( $user )
    {
        case "name01":
            if( md5( $pass ) == "sadf7ds8f7sda8f787f8ads7f8sad7fsa8" )
                return TRUE;
            else
                return FALSE;
            break;

                case "name02":
            if( md5( $pass ) == "sadf89f8dsa9f8sad8fs9d89f89f8ds9a8fsd9a开发者_运维问答" )
                return TRUE;
            else
                return FALSE;
                break;
    }   
}
?>


This would probably be a bit better:

function authUser( $user, $pass )
{
  $users = array('name01' => 'sadf8sad9f8sdaf98sa98fsd9a8fs8df');
  return (array_key_exists($user, $users) && $users[$user] == $pass);
}

Simply add more users to the associative array as needed.

Edit:

If you are still required to use the switch statement, this would be simpler:

function authUser( $user, $pass )
{
    switch( $user )
    {
        case "name01":
            return md5( $pass ) == "sadf7ds8f7sda8f787f8ads7f8sad7fsa8";
        case "name02":
            return md5( $pass ) == "sadf89f8dsa9f8sad8fs9d89f89f8ds9a8fsd9a";
    }   
}


If you want to do it easy i would suggest this:

function authUser( $user, $pass )
{
    $user_list = array(
        'user01' => 'password01',
        'user02' => 'password02',
        'user03' => 'password03',
        'user04' => 'password04',
        'user05' => 'password05'
    );

    if(array_key_exists($user, $user_list))
    {
        if($user_list[$user] == $pass)
        {
            // login stuff
        }
        else
        {
            return "Password incorrect";
        }
    }
    else
    {
        return "User not found.";
    }
}


Here is a way you can do it following your syntax.

<?php

// Predefined Passwords
$passwords = array(
    'user1' => '039a726ac0aeec3dde33e45387a7d4ac',   // User: user1 Password: monsters
    'user2' => 'fe01ce2a7fbac8fafaed7c982a04e229' //User: user2 Password: demo
);

function authUser($user, $pass)
{
    //Switch the user
    switch($user)
    {
        // Default to this function
        case default:
            // Check if the pass matches the user
            if(md5($pass) == $passwords[$user]) {
                // It did, return true
                return true;
            }
            else {
                // Whoops, wrong info
                return false;
            }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜