PHP - proper check if $_POST['variable'] is posted - php

I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true.
Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you

isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn't just check whether the $_POST array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that's what empty is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.

Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}

As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.
$submit = $_POST['submit'] ?? '';
If submit key does not exist or is NULL the value of the $submit variable will be an empty string.
This method is not limited to $_POST. It will work for any variable. For example:
echo $my_message ?? 'No message found';
If message was not initialized or is NULL, the statement above will output No message found
There's even more that you can do with a null coalesce operator, documentation link below.
Documentation here

$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}

As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST.

Related

Error occurs when no checkbox is checked (in PHP)

I have a php code where data from my database are fetched in an array with checkbox corresponding each data . I already have the codes enabling updates to my table (for each data checked):
<?php
include("connect.php");
$user=$_SESSION['username'];
$updated = FALSE;
$submit=FALSE;
if(count($_POST) > 0){
$library = $_POST['library'];
array_map('intval',$library);
$library = implode(',',$library);
mysql_query("UPDATE ES_Students SET library=0") or trigger_error(mysql_error
(),E_USER_ERROR);
mysql_query("UPDATE ES_Students SET library=1 WHERE StudentNO IN ($library)") or trigger_error
(mysql_error(),E_USER_ERROR);
$submit=TRUE;
$updated=TRUE;
}
?>
My problem is, whenever no checkbox is checked, an error will occur that the library index is undefined and all. I know it's got something to do with the $count($_POST)>0 but I don't actually know how to fix this. I tried putting an else-clause to redirect it to another page but it will result to same error. Can anyone tell me what to do??
Use an isset around your post. PHP link
if( isset($_POST) && count($_POST) > 0){
....
If any data is sent at all, even a blank form, isset($_POST) will return true, but with a count($_POST) of 0. So, you could also test for the exact items of the array you're looking for to be sure it is infact in the $_POST :
if( isset($_POST) && count($_POST) > 0 && isset($_POST['library'])){
....
you should check if $_POST['library'] contains any items, because if it's empty, then the implode function returns an empty string and your query looks like ... IN () which is not valid sql syntax.

php: if($some_var != '') vs. isset / empty

So I am fairly new to php, but before I really had a solid understanding I picked up this habit. When checking for whether or not a $_SESSION / $_POST / $_GET variable was set I use this:
if($_SESSION['username'] != '' {
//allow access
header('Location: welcomefriend.php')
}
else {
//get out
header('Location: getoutofhereyournotwelcome.php')
}
I have used this in login scripts for checking if the session is set to allow access, etc. So now I know about isset / empty but I always seem to run into problems with those.
So my question is will I ever encounter a problem when using if($some_far != '') to check if a variable is set?
That would show notice if the variable doesnot exist, so do:
if( !empty($_SESSION["username"]) ) {
...
Yes - it'll throw a notice if the index doesn't exist in the array.
Yes, if a form is submitted, but not filled out, $_POST["value"]=="" will give you a different result from isset($_POST["value"]). Also, $_POST["value"]=="" will give you an error on some servers when it is not set.
Checking if $_SESSION['username'] is empty without checking whether there actually is a username entry in the $_SESSION array will throw notices. It's good practice to code around them. One way to do this is something like if (isset($_SESSION['username']) && $_SESSION['username'] != '')
As for empty() vs != "", that's personal preference. One problem you might run into is that empty() does not accept values, only references, so you cannot do empty(somefunction($_SESSION['username'])).
Use empty() if( !empty( $some_far ) ) { to check if a $_POST variable is set and not empty.
If the variable can also be empty but must be set use if( isset( $some_far ) ) {
With isset() the variable also must not be NULL to return true.
You also won't get a notice if the variable is not set as Martin already mentioned in his post.
I always do the following:
if (isset($_SESSION['username']) && $_SESSION['username'] != '') {
//allow access
header('Location: welcomefriend.php')
}
else {
//get out
header('Location: getoutofhereyournotwelcome.php')
}
Testing if the index 'username' exists in the $_SESSION variable first in the if statement will mean that if the index doesn't exist then we won't continue with $_SESSION['username'] != '' thus never causing an error.
Considering
An associative array containing session variables available to the current script
Why not use the predefined function available? array_key_exists
if(array_key_exists('username', $_SESSION) ) {
header('Location: welcomefriend.php');
} else {
header('Location: getoutofhereyournotwelcome.php');
}

Php pages dependent on query string but what if there's no parameter?

I am creating pages that are dependent on a query in the url (eg europe.php?country=france). I am aware that it will be useful to re-write theses as europe.php/france with htaccess for SEO etc but what if that page is accessed without the query string?
I am using php to $_GET the query, so if I access the page without the query I get 'var=;' ie, it is empty (and retrieves an error). I'm trying to use an if statement to check if the $_GET retrieves nothing but am unsure if this is the right thing to do.
So: how do I check for an un-retrieved var so I can set a default?
Or: am I going about this the wrong way?
If you know the index into $_GET, use isset():
$country = 'default';
if( isset( $_GET['country'])) {
$country = $_GET['country'];
}
This will only test if the country parameter was passed, but it could have been set to an empty string. If this is invalid input, you can combine the check using empty():
$country = 'default';
if( isset( $_GET['country']) && !empty( $_GET['country'])) {
$country = $_GET['country'];
}
You can condense this into one line and save the result to a variable $country using the ternary operator, like so:
$country = (isset( $_GET['country']) && !empty( $_GET['country'])) ? $_GET['country'] : 'default';
Finally, you can check if you got absolutely no $_GET parameters by calling count() on $_GET:
if( count( $_GET) == 0) {
die( "No parameters - Invalid input!");
}
since isset() really tests for "NOT NULL", you should use empty() to test if an empty string was given:
if (empty($_GET['country'])) {
$_GET['country'] = "default";
}
that is, unless you expect 0 to be a valid input, in that case, you'd have to check with isset and make sure the string has at least one character:
if (!isset($_GET['country']) || !strlen($_GET['country'])) {
$_GET['country'] = "default";
}
which can be optimized into
if (!isset($_GET['country']) || !isset($_GET['country'][0])) {
$_GET['country'] = "default";
}
try using something like this:
$var = ( isset($_GET['var']) ? $_GET['var'] : 'default value' )
Try doing this
if(isset($_GET['your_variable'])) {
$variable = $_GET['your_variable'];
} else {
$variable = "not set";
}
That will set the variable if it is set in your URL - or it can set your variable to some other value if it is not set in the URL
Running a check at the start of the page to see if var is set is fine to do. If it's empty, you can redirect using something like:
header("HTTP/1.0 404 Not Found");
header('Location:YOUR PAGE NOT FOUND PAGE');
exit();
On a side note, if you're using data from $_GET, you need to make sure that this data is validated & cleaned to prevent against all sorts of security intrusions, such as XSS and, if you use a database, MYSQL injection. Running a test at the start of the page to check if it's empty can be just the start - you can also make sure that the data is something you'd expect (say, check it's alphanumeric). After, with $_GET data, anyone could fill the URL bar with whatever they like and potentially damage your website.
Hope this has helped!

Check if form element sent but empty with PHP

I'd like to separate two things.
If a $_POST["something"] was sent, BUT empty.
OR
If a $_POST["something"] was not sent.
Is there a way?
You might be tempted to use empty(), but it blows up in your face if your possible values include a 0. Best to use something like:
if (isset($_POST['something'])) {
// the form field was sent ...
if ($_POST['something'] === '') {
// the form field was sent, but is empty
}
}
This works, as ALL data coming out of the _GET/_POST/_REQUEST superglobals is a string, regardless of whether it's a number or not.
You'll want to use isset()
if (isset($_POST["something"])){
echo "The Post Variable 'something' was posted";
if (strlen($_POST["something"])==0)
echo "The Post Variable is blank";
else
echo "The Post Variable Contains ".$_POST['something'];
}
look towards isset and empty.
http://php.net/manual/fr/function.isset.php
http://php.net/manual/fr/function.empty.php
Edit : The comments below are true. Empty should be used for empty strings, not numeric values, float values or a zero in a string​​. However, here's a function if you need to accept these as valid values:
function is_blank($value) {
return empty($value) && !is_numeric($value);
}
i use the php function isset() to check if a POST was sent or not
http://php.net/manual/en/function.isset.php
if ($_POST["something"])
will return true if there is such field
if $_POST["something"] == ""
will do the rest

Why do I need the isset() function in php?

I am trying to understand the difference between this:
if (isset($_POST['Submit'])) {
//do something
}
and
if ($_POST['Submit']) {
//do something
}
It seems to me that if the $_POST['Submit'] variable is true, then it is set. Why would I need the isset() function in this case?
Because
$a = array("x" => "0");
if ($a["x"])
echo "This branch is not executed";
if (isset($a["x"]))
echo "But this will";
(See also http://hk.php.net/manual/en/function.isset.php and http://hk.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting)
isset will return TRUE if it exists and is not NULL otherwise it is FALSE.
You basically want to check if the $_POST[] variable has been submitted at all, regardless of value. If you do not use isset(), certain submissions like submit=0 will fail.
In your 2nd example, PHP will issue a notice (on E_NOTICE or stricter) if that key is not set for $_POST.
Also see this question on Stack Overflow.
The code
if($_POST['Submit'])
{
//some code
}
will not work in WAMP (works on xampp)
on WAMP you will have to use
if (isset($_POST['Submit'])) {
//do something
}
try it. :)
if user do not enter a value so $_post[] return NULL that we say in the description of isset:"
isset will return TRUE if it exists and is not NULL otherwise it is FALSE.,but in here isset return the true
"

Categories