Usage of "isset" function - php

Although I visit php documentation , I didn't understand usage of "isset" function .
1 - for example in a php tutorial book author wrote a text with this context : when we create a form in a first.html and we want to use from form information in second.php , we must use these 2 pieces of code :
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
$key = $_GET['q'];
if($key == "")
die("The Search key word must be entered !!!");
but I don't understand what is difference between these 2 codes ?
2 - for another example I saw this code for checking that a bottom is clicked or not :
if(isset($_POST['login_btn']))
{
....
}
but I don't understand why does it check that a bottom is clicked or not ?

$key="";
isset($key) //This evaluates to true.
The string is empty, but the variable is defined. The isset() function returns true, even for an empty string.
Perhaps you would like to use empty() instead, which has a broader range of conditions that evaluate to false.

isset checks to see if a given variable or index exists. If you assume that a variable exists and it doesn't, PHP generates a notice. All you're doing by using isset is suppressing possible notices -- which is good practice.

The difference is, in one instance the form was not submitted, in the second instance, the form was submitted, but with a blank value.
You wouldn't want to process a form on your page if the form has not been submitted yet.
There may also be multiple forms on one page, so you might check the button value to find out which form was submitted.

This function is quite simple
As on php.net:
Determine if a variable is set and is not NULL.
In your case, the isset function checks of your post variable is empty or not

$key == ""; // Is $key an empty string
isset($key); // Has the $key variable been defined and not null
And just for reference, here are a few others that may be useful
empty($key); // Is $key and empty value (0, false, null, "", array())
$key == false // Is $key a falsey value (0, false, null, "", "0", array())
$key === false // Is $key a false boolean (false)

I'm just going to dissect your code a little bit..
isset
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
Would typically be used to see if a variable in a URL is set so something like this:
http://mysite.com/index.php?q=1
Would have $_GET['q'] set and isset($_GET['q']) would come back true
$key==""
$key = $_GET['q'];
if($key == "")
Would check to see if $key is empty. Using my previous example URL, $key would not be empty or blank, it would be 1.
Why check for a button press
The script that processes your form needs to know that it is being accessed after the form that way it does not error out. This is where you would want to make sure that the form submit button was pressed. As this is confusing, here is an example:
Say you want to insert a tag for your blogging system into a database you might have code that looks like this:
AddTag.php
<form name="addtag" method="process.php" action="post">
<input type="text" name="tagname" />
<input type="submit" name="submittag" />
</form>
process.php
<?php
if ($_POST['submittag']) {
//INSERT query
}
?>
As you can see, if process.php is accessed without the AddTag form being accessed first, the script would not try to insert your tag.

Everyone here has already explained to you what the isset() function checks for (that being if a variable is set or not), but I think what you're really asking about is how $_GET[] and $_POST[] work. You're going to need to look more at the form that feeds this code. Read about what $_GET[] and $_POST[] variables are and I think this code will make a lot more sense to you.
For instance, your second example checks to see if the value named login_btn was sent via post method. If it was, then it runs the ... code block.

Related

Best way to check if form was submitted (php)

I'm learning PHP and specifically how to secure php forms.
I'm reading an article entitled "Sanitize and Validate Data with PHP Filters" wherein the author checks if the form was submitted using the following code:
if (isset($_POST['Submit'])) {
// do something...
}
Which does work, but I've read that its best to use input filters (i.e. filter_input).
Secondly, using filter_input would also stop netbeans from nagging me about not "accessing the superglobal $_POST Array directly"
So I wrote the following:
function is_form_submit() {
$request = filter_input(INPUT_SERVER, "REQUEST_METHOD");
return $request === 'POST' ? true : false;
}
Which could be used like so:
if ( is_form_submit() ) {
// do something...
}
So my question is: doesn't my code achieve the same thing? If not, why not. Please advise.
While your code would achieve the same result in most cases, it is not the same as the isset call.
What your code does is checks if the REQUEST_METHOD is POST. That is, it checks if the user made a POST request to access the current page.
What the isset does is checks if something with the name of Submit was sent via POST. This usually happens when your submit button is <input name="Submit" type="submit" value="Submit" />, as clicking that (or hitting enter in a text field and it's the first submit button) will result in $_POST['Submit'] being set.
To see the different behaviours, compare the results of curl -X POST your-url.com/page.php with curl -F Submit=submit your-url.com/page.php.
filter_input is untouched user input.
Some scripts add/modify $_POST and $_GET directly. Fine if your code is fail-safe, but if something goes wrong with the manipulated keys/values, there could be errors.
filter_input( INPUT_POST, 'requiredID' )
Would not be affected by the type of coding below
$_POST['requiredID'] = brokenFunction( $_POST['requiredID'] );

how to print error message in HTML/PHP?

I am checking if the particular parameter is passed and if a folder exists for that parameter. ex
if ((! isset($_GET["name"])) or (! is_dir($_GET["name"]))) {
print "----------------USER NOT FOUND-----------------" ;
}
and in my URL if have name=Erik and if that folder does not exist in that name, I want to print the Error message.
Also I would like to check if the parameter'name' is passed into URL using isset.
Somehow the above does not work and I am unable to figure out why.
Any input will help.
Thanks
or has a different use. It's for whenever something you are trying to do does not work, then it executes the other bit. Typical deprecated example would be when you try to do some database interaction, you'd write back then $STH = mysql_query('SELECT * FROM users') or die();. For your case, you should use the || operator instead, as explained in the documentation
Besides, you are not checking if someone submitted something. This will never print anything if a form is submitted with nothing in it. Both errors fixed, your code should look something like this:
if (empty($_GET["name"]) || !is_dir($_GET["name"])) {
print "----------------USER NOT FOUND-----------------" ;
}
Because, if someone submits the form, the url will be example.com/index.php?name=, which makes $_GET['name'] to be set while it's empty. I assume you want to say User not found in that situation.

PHP form checkbox always returning value

Even when the checkbox is unselected it is still returning the Value. I am passing the form through an Ajax request and printing the returned value, but it is the same result checked or unchecked. Isset not working properly either.
<input type="checkbox" value="Agree" id="siteAgreement">
if(!isset($siteAgreement) || !$siteAgreement || $siteAgreement != "Agree"){
//////Unchecked
}
Change
siteAgreement = $("#siteAgreement").value;
to something like this:
siteAgreement = $("#siteAgreement").is(':checked') ? $("#siteAgreement").val() : null;
But you should also add the name attribute so browsers with javascript turned off can also use your site.
Also you can use some code that generates request automatically from form (something like jquery.form), so you don't have to update javascript whenever you change the form.
Example here: http://jsfiddle.net/RhasK/
Here try this:
if(!isset($_POST['siteAgreement']) || !$_POST['siteAgreement'] || $_POST['siteAgreement'] != "Agree"){
//////Unchecked
}
Unless you're extracting the variable before, $siteAgreement won't be set. You can use $_POST['nameofelement'] to access the data.
if($_POST["siteAgreement"] !== "Agree") {
//not checked
}
will work fine
you should only need to check if it is set or not.
if(!isset($_POST['siteAgreement'])){
//then it is unchecked
}
Also, you didn't give your input a name. You need to put...
<input type="checkbox" name="siteAgreement" value="Agree" id="siteAgreement">
You need a name to access it in PHP.

Remember me cookie with code igniter

I'm trying to figure out how to add in a remember me functionality into my script with code igniter. Here's what I"m attempting to do with the checkbox. I'm getting a syntax error for the if statment. Am I not using it correctly?
<?php echo form_label(form_checkbox( 'remember', 1, if (isset($this->input->cookie('xtrcook'))) { TRUE } ) . ' Auto-login in future.', 'remember' ); ?>
You have a syntax error because you're trying to pass this as an argument:
if (isset($this->input->cookie('xtrcook'))) { TRUE }
That's not how expressions work in PHP. You want this to be TRUE is the xtrcook cookie is set, so just pass in this:
isset($this->input->cookie('xtrcook'))
Actually, $this->input->cookie() returns either the cookie value or FALSE, and both are always "set" so isset() is not appropriate here, you can use ! empty() or !== FALSE instead:
$this->input->cookie('xtrcook') !== FALSE // evals to TRUE if the cookie exists
The whole thing:
<?php echo form_label(form_checkbox('remember', 1, $this->input->cookie('xtrcook') !== FALSE).' Auto-login in future.', 'remember'); ?>
It is a bit complicated still, might be easier to pass on the form_label() function and just write this:
<label>
<?php echo form_checkbox('remember', 1, $this->input->cookie('xtrcook') !== FALSE); ?>
Auto-login in future
</label>
I don't think so, this looks like a view, and PHP is a server-side language, meaning that once it renders the page, it's done - it won't respond to any clicks on checkboxes... You could make an AJAX call to maintain your structure, but I suggest is to check for your remember variable on the page you submit the form to, and then set the cookie if needed.

PHP undefined index error when clicking a url and invoking a php script

I have a call to a PHP script from my home page which I do like this:
echo 'Delete';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}

Categories