Jump to content

Help writing a switch statement


Ricky55

Recommended Posts

Hi,

 

I have the code below that using for a simple login system (security not a concern at all)

 

This code works but it now has around ten if statements (not included them all for clarity), would this be best written as a switch statement? if so can you help me code it. I can write basic switch statements but I don't know how to match two cases. The login and the password.

 

If a switch statement isn't the best option can you suggest what is and perhaps give me an example?

 

Thanks guys!

 

The code:

 
<?php
session_start();
 
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
 
if($username == 'richard' && $password == '123')
{
$_SESSION['isLoggedIn'] = true;
echo ("login-richard"); 
}
if($username == 'john' && $password == '456')
{
$_SESSION['isLoggedIn'] = true;
echo ("login-john"); 
}
}
 
?>
Link to comment
https://forums.phpfreaks.com/topic/282798-help-writing-a-switch-statement/
Share on other sites

Rather than have a switch/case statement. You can just put all usernames/passwords into an array. like

$users = array(
    'username1' => 'password1',
    'username2' => 'password2',
    // etc...
);

Then use the following to proccess the login

$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
    $username = $_REQUEST['username'];
    $password = $_REQUEST['password'];

    // check that the user exists in the $users array
    // and the password for that user matches the entered password
    if(isset($users[$username]) && $users[$username] == $password)
    {
        $_SESSION['isLoggedIn'] = true;
        echo ("login-$username");
    }
}

However if you find you're adding more username/password entries then you may want to start looking into using a database.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.