问题
Trying to learn PHP with test and try method I am struggling with isset(). Here is the code I have:
<form action="validate.php" method="POST">
<label title="User Input"> Custom Header Name</label>
<input type="text" name="user_input">
<button type="submit" id="pageName">Submit</button>
</form>
and PHP file is as
<?php
if(isset($_POST['user_input']))
{
echo "Input Is Set";
} else{
echo "Not Yet Set";
}
?>
I both cases(empty or filled input) I am getting the first message "Input Is Set" as result! Can you please let me know why this is happening?
回答1:
This is because user_input
have isset
once form is submitted also if it is not filled, to avoid the error simply add an !empty
check
if(isset(($_POST['user_input'])) && (!empty($_POST['user_input'])))
回答2:
Instead of isset, you can do this:
<?php
if(isset($_POST['user_input']))
{
if (!empty($_POST['user_input'])) {
echo "Input Is Set";
} else {
echo "Input is empty!";
}
} else{
echo "Not Yet Set";
}
?>
More info: http://php.net/manual/en/function.empty.php
回答3:
You can try something like
<?php
if($_POST['user_input'] != '')
{
echo "Input Is Set";
} else{
echo "Not Yet Set";
}
?>
Or else use if (!empty($_POST['user_input'])
Check to see if it holds any value. That should work
回答4:
You check if it's set but you should check also if it's empty.
Short version:
<?php
echo isset($_POST['user_input']) && !empty($_POST['user_input'] ? "Input is set" : "not set";
?>
回答5:
I recommed you to work with strlen() for 2 reasons:
if (strlen($_POST['user_input']) > 0 && strlen($_POST['user_input']) < 80)
{ ... }
- you can be sure the variable is not just set, but also it does actually contain data
- you should cap strings from POST and GET to avoid long injected queries for example.
best is to make your own wrapper for security and isset checks in a little helper function.
来源:https://stackoverflow.com/questions/16781384/issue-with-isset-function