Best way to handle errors on a php page?

后端 未结 8 742
傲寒
傲寒 2020-11-30 22:10

Right now my pages look something like this:

if($_GET[\'something\'] == \'somevalue\')
{
    $output .= \'somecode\';

    // make a DB query, fetch a row
           


        
8条回答
  •  鱼传尺愫
    2020-11-30 22:40

    If you're searching for a code structure which will look pretty and will work - you could use the whitelist method I always use. For example - validating a $_GET variable:

    $error = false;
    
    if(!isset($_GET['var'])) 
    {
        $error = 'Please enter var\'s value';
    }
    elseif(empty($_GET['var'])) 
    {
        $error = 'Var shouldn\'t be empty';
    }
    elseif(!ctype_alnum($_GET['var'])) 
    {
        $error = 'Var should be alphanumeric';
    }
    
    //if we have no errors -> proceed to db part
    if(!$error) 
    {
        //inserting var into database table
    }
    

    So, this is it , just 2 if/elseif blocks, without nesting

提交回复
热议问题