简体   繁体   中英

What's wrong PHP field check function

I have that function but it's not working.

function Checkfields($fields){
    $ret = false;
    foreach($fields as $field) {
        if ($_POST[$field] == "" || !isset($_POST[$field])) {
            $ret = true;
        }
    }
    if ($ret) {
        $ret = "All fields are required.";
        header('Location: ?erro='. $erro);
    }
}

and i use like that:

Checkfields(array("username","password"));

UPDATED: I already tried to change to:

function Checkfields($fields){
    $ret = false;
    foreach($fields as $field) {
        if ($_POST[$field] == "" || !isset($_POST[$field])) {
            $ret = true;
        }
    }
    if ($ret) {
        $erro = "All fields are required.";
        header('Location: ?erro='. $erro);
    }
}

and nothing happens.

function Checkfields($fields){
        $ret = false;
        foreach($fields as $field) {
            if (!isset($_POST[$field])) {
                $ret = true;
            }
        }
        if ($ret) {
            $error = "All fields are required.";
            header('Location: ?erro='. $error);
        }
}

Exist two bugs in your code validation in variable POST.. if element don't exist appears error

And when $ret == true

header you put

$ret = "All fields are required.";
        header('Location: ?erro='. $erro);

When redirect to other page don't send response error

Why your code is not redirecting , is probably because of the header function call

you may have to call like

header("Location:http://www.example.com/page.php?erro=$err")

replace example.com/page.php to the page you want it to redirect to. As the location basically creates a 302 redirection and the browser will get redirected to the new url. So you should supply absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM