I have a php page like this
if($_GET){
if($_GET['name'] && $_GET['number']){
$name = $_GET['name'];
$number = (int) $_GET['number'];
echo "Got it!";
} else {
echo "Please give input!";
}
} else {
echo "Please give input!";
}
Now it works fine when there is no input is given. But if i give one input like page.php?name=Something&number=0 it gives error Undefined index: number
And the value of number also can be 0.
This error doesn't look good. Now how can I get rid from this? Please help!
use isset to check
also check it explicitly like $_GET['name']!='' and dont print or store whatever you get from get and post etc.. if you are storing to database using mysli_real_escape_string. and if you are outputting to browser use htmlspecialchars
if(isset($_GET)){
if(isset($_GET['name']) && $_GET['name']!='' && isset($_GET['number']) && $_GET['number']!=''){
$name = $_GET['name'];
$number = (int) $_GET['number'];
echo "Got it!";
} else {
echo "Please give input!";
}
} else {
echo "Please give input!";
Related
I want to compare if a get variable is a specific text. But I cannot get into the if-statemeant. The echo "invalid user" is not written.
code:
<?php
if ($_GET['status'] && $_GET['status'] == "login_fail") {
echo "invalid user";
}
?>
when I check the variable status before (ando also after) the if-statemeant with:
echo $_GET['status'];
or with
print_r($_GET['status']);
the result is in both
login_fail
So the variable status is there and has "login_fail".
But "invalid user" is not written!
I tried it also with === or with ' instead " and much much more.
Use isset().
`
<?php
if (isset($_GET['status']) && $_GET['status'] == "login_fail") {
echo "invalid useenter code herer";
}
`
Try this :
<?php
if (!empty($_GET['status']) && $_GET['status'] == "login_fail") {
echo "invalid user";
}
?>
I think your code don't have any problem.
if your facing a problem till now you can add this line
before your if condition script.
$_GET['status'] = trim($_GET['status']);
In order to avoid errors when $_GET has nothing, use this:
if (!empty($_GET['status']) && ($_GET['status'] == "login_fail")) {
echo "invalid user";
}
Change to test if 'status' is set in the $_GET variable first and then check its value.
if (isset($_GET['status']) && $_GET['status'] == "login_fail")
{
echo "invalid user";
}
That way you will not run into any problems if it's not set.
You should use isset() function to check whether a variable has any value:
if(isset($_GET['status']) && $_GET['status'] == 'login_fail')
{
echo "invalid user";
}
very short simple quiz app. browser keeps returning Correct as a response, even though it is not correct.
<?php
$answer = (isset($_POST['answer']));`
if ($answer == "Dagny Taggart")`
{
echo "Correct";
} else {
echo "wrong";
}
?>
Try this. You're currently setting $answer to isset($_POST['answer'], meaning as long as $_POST['answer'] is set, you're $answer is going to be TRUE. I would check if it's set and then set it to the $_POST value.
<?php
if(isset($_POST['answer'])) {
$answer = $_POST['answer'];
if ($answer == "Dagny Taggart")
{
echo "Correct";
} else {
echo "wrong";
}
} else {
// Do something?
}
?>
isset returns a boolean (true or false) value. So your test will always fail because true != 'Dagny Taggart'
Add this ternary and it will work
$answer = (isset($_POST['answer'])) ? $_POST['answer'] : '';
Now I want to check if this text box contains one word or two, for example
if ($_POST['mytext'] == two words){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
and I tried
if ($_POST['mytext'] > 1){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
and it didn't work
that what I mean so how to make it?
Hope to find a way to do that.
Thanks
If you define two words as "some characters followed by one space followed by some characters" then you can do something like:
$mytext = $_POST["mytext"];
$parts = explode(" ", $mytext);
if (count($parts) !== 2) {
throw new Exception("too many or too little!");
}
if (strlen($parts[0]) === 0 || strlen($parts[1]) === 0) {
throw new Exception("not enough characters!");
}
Keep in mind that this allows a string like "# !"
Use str_word_count():
if (str_word_count($_POST['mytext']) > 1){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
you could use the
`substr_count('some text', ' ');
it will return the number of space,.
try this
$text= preg_split(" ",$_POST['mytext']);
if (count($text) > 1){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
I have 2 textboxes one is for maximum marks and the other for the obtained marks..
The value to be entered in the second box must be restricted in such a way that it is less than or equal to the maximum marks.. Only numbers must be entered into those boxes..
Maximum Marks<input type=text name=maxmarks maxlength='2' >
Obtained marks<input type='text' maxlength='2' name='obtmarks'>
Please help me with this.. Thank you in advance..
Well if you want to do it client side, you will have to use Javascript. If you want to do it server-side, why don't you send them back the page with an error message if the second number exceeds the first. You might also might want to look into HTML5 input options if that is an available option for you. Those will automatically do the number validation.
You could try something like this...
$response_array = array();
if($obtained > $max){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained to big</div>';
}
if(!is_numeric($obtained){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained not a number</div>';
}
echo json_encode($response_array);
This is pseudo code, obviously you will need to tweak it for your purpose.
First you have to make checks in your php script that you submit the form, you can use javascript after to make it more user friendly but if someone change the source code or just turn javascript off he will be able to submit anyting.
In your process_form.php:
session_start();
$errors = array();
if (!isset($_POST['maxmarks']) || empty($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field is required.';
}
else {
if (!is_int($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field must be an integer.';
}
else {
$maxmarks= (int) trim($_POST['maxmarks']);
}
}
if (!isset($_POST['obtmarks']) || empty($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field is required.';
}
else {
if (!is_int($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field must be an integer.';
}
else {
$obtmarks= (int) trim($_POST['obtmarks']);
}
}
if (!empty($errors)) {
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else if ($obtmarks > $maxmarks){
$errors[] = 'The Obtained Marks must be less or equal to Maximum Marks.';
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else {
//process data
}
In your_form.php now:
session_start();
if (isset($_SESSION['form_errors']) && !empty($_SESSION['form_errors'])) {
$errors = $_SESSION['form_errors'];
unset($_SESSION['form_errors']);
}
echo '<ul>';
if (isset($errors)) {
foreach($errors as $error) {
echo '<li>' . $error . '</li>';
}
}
echo '</ul>';
//your form here
I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>