Home » Php » exception handling – PHP returning an error message and false

exception handling – PHP returning an error message and false

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a very simple PHP function to check log-in

function check_login($user, $pass) {
    if(!isset($user) || $user == '') {
        return  'Please enter a valid username';
    }
    else if(!isset($pass) || $pass == '') {
        return  'Please enter a valid password';
    }
    else {
        return 'true';
    }
}

How can I return an error message and false same time and return true instead of ‘true’ as a string. Like,

function check_login($user, $pass) {
    if(!isset($user) || $user == '') {
        return  'Please enter a valid username' //return false;
    }
    else if(!isset($pass) || $pass == '') {
        return  'Please enter a valid password' //return false;
    }
    else {
        return true;
    }
}

So I can check like if(check_login($uname, $pword)){ instead of checking like if(check_login($uname, $pword)=='true'){ 🙂

How to&Answers:

Why not just check if it’s true, and handle from there.

$login = check_login('user', 'pass');

if($login === true)
    loginUser(); //login was successful, finalize or whatever
else
    echo $login; //error message

Answer:

Another method you could use is to set an error message inside the class and call a function to fetch it later.

  class exampleClass {
        private $error_message = '';

        function exampleFunction($argument) {

            if($argument == 'lemons') {
                return true;
            } else {
                $this->error_message = 'Argument was not lemons.';
                return false;
            }

        }

        function getErrorMessage() {
            return $this->error_message;
        }

    }

    $example_session = new exampleClass();

    if( ! $example_session->exampleFunction('apples') )
        echo $example_session->getErrorMessage();

Answer:

Why not try throwing an exception

function check_login($user, $pass) {
    if (empty($user)) {
        throw new InvalidArgumentException('Please enter a valid username');
    }
    if (empty($pass)) {
        throw new InvalidArgumentException('Please enter a valid password');
    }
    return true
}

// snip

try {
    check_login($userValue, $passValue);
} catch (Exception $e) {
    // an error occurred
    echo $e->getMessage();
}

Answer:

I know this is kinda an old post, but, it gets a lot of reviews. So let me just add another answer to the great answers here.

One solution would be to pass a variable by reference like PHP style. Example


Pseudo code:

The function

 //Notice the '&' before the variable name. 
function check_login($user, $pass, &$message) {
    if(!isset($user) || $user == '') {
        $message["status"] = false;  //fail
        $message["message"] ='Please enter a valid username';
    }
    elseif(!isset($pass) || $pass == '') {
           $message["status"] = false;  //fail   
           $message["message"]=  'Please enter a valid password';
    }
    elseif (isset($pass) || $pass != ''){
         $message["status"] = true; //success
         $message["message"]=  'Username and password are valid';
        return true;
    }

    return false;//you can return from within the if condition if you wish
}

The Call:

/* $message variable will be assigned and populated in the function check_login() */

$message = array();

    if(check_login($uname, $pword, $message) === true )
    {
       //Do your stuff here
      //@message array is avaialble 
       echo message["message"];
    }
    else
    {
     //means false
     echo message["message"];
    }

Answer:

You can use echo and return both:

function check_login($user, $pass) {
    if(!isset($user) || $user == '') {
    echo "Please enter a valid username";
        return false;
    }
    else if(!isset($pass) || $pass == '') {
    echo "Please enter a valid password";
        return false;
    }
    else {
        return true;
    }
}

Answer:

You can use variables instead of echo or return that is much more safer than echo – let’s say if you want to run this function in html header or even before that – what will you are going to see text that are generated even before website is loaded.

use variables instead !

    function check_login($user, $pass) {
            if(!isset($user) || $user == '') {
            $var = "Please enter a valid username";
$var = array();
    $var['msg'] = "Please enter a valid username";
    $var['error'] = "false";
    return $var;

            }
            else if(!isset($pass) || $pass == '') {
            $var = array();
    $var['msg'] = "Please enter a valid username";
    $var['error'] = "false";
    return $var;
            }
            else {
                return true;
            }
        }

that’s how you can use both at the same time now where ever you want to show the error use the variable and where ever you want to check the statement check it by true and false.

Where ever you want to use the $var variable with error msg use this –

echo $var['msg'];

and when you want to check false use

$var['error'] == 'false'