简体   繁体   中英

How to determine if something is not a string and if something is just empty?

In my php I have 2 optional inputs. input1= and input2= . Both are optional inputs. My question is how do I determine if an input was just not provided or if the input provided was not a string?

I only want people to put an actual string. Not different types of data structures.

Examples

Valid: www.example.com/myfile.php?input1=hello&input2=bye

Valid: www.example.com/myfile.php?input1=hello

Valid: www.example.com/myfile.php?input2=hello

Valid: www.example.com/myfile.php

Invalid: www.example.com/myfile.php?input1[]


<?php

function check_valid($string) {
    if (!is_string($string)) {
        echo "This is a not string. We tested: ".$string."<br>";
    } else {
        echo "This is is string. We tested: ".$string."<br>";
    }
}

$input1 = check_valid($_GET['input1']);
$input2 = check_valid($_GET['input2']);
?>

You should use the isset() method to check if $input1 or $input2 are provided or not.

function check_valid($test) {
    if (isset($test) && is_string($test)) {
        echo "Valid";
        return;
    }
    echo "Not Valid";
}

You can check if the value exists, containts empty or null.

<?php

function check_valid($string) {
    if (trim($string) == NULL OR trim($string) == "") { //Will check if value without a space is null or empty         
        return "valid";

    } 
} 
$input1 = check_valid($_GET['input1']);
$input2 = check_valid($_GET['input2']);
?>

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