Jump to content

Help writing a switch statement


Ricky55
Go to solution Solved by Ch0cu3r,

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
Share on other sites

  • Solution

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.

Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.