just wondering. i've seen sites with this kind of url http://www.something.com/?somedata with the 'somedata' is the value of some 'unmentioned' variable
how can i do something like that? all I know is the traditi开发者_Python百科onal http://www.something.com/index.php?arg=somedata
thanks a lot
This is just a variable without value. You can get that string using list($value) = array_keys($_GET);
- assuming you have ensured there is exactly one value in the $_GET
array (count($_GET) === 1
), otherwise you will get an error (if $count === 0
) or unwanted behavior (if $count > 1
).
You can usually access the full query string using $_SERVER["QUERY_STRING"]
.
I think every main-stream web server provides that variable, I'm 100% sure about Apache and pretty sure about IIS.
It is simply a shortcut for a boolean value.
somedata is equivalent to somedata=1 or somedata=true
When it's checked server side, the presence itself of the variable is enough to write a condition.
if ( isset($_GET['somedata']) ) {
//do something
}
What you see as "the value of some 'unmentioned' variable" is more generally considered as a query string parameter without a value. So for foo=bar&baz
, foo
has the value bar
and baz
has no value (in PHP its value will be an empty string).
Since the other answers are providing different methods of accessing that parameter name, here are my two cents. You can get the first key of the $_GET
array by using the key
function. If no key is available, key
will return NULL.
Visiting ?somedata=somevalue
var_dump(key($_GET), $_GET);
/*
string(8) "somedata"
array(1) {
["somedata"]=>
string(9) "somevalue"
}
*/
Visiting ?somedata
var_dump(key($_GET), $_GET);
/*
string(8) "somedata"
array(1) {
["somedata"]=>
string(0) ""
}
*/
Visiting ?
var_dump(key($_GET), $_GET);
/*
NULL
array(0) {
}
*/
They probably use some kind of URL rewriting (see Apache mod_rewrite) where the url is transformed from http://www.something.com/?somedata to http://www.something.com/index.php?arg=somedata
For your given URL you can just iterate over the $_GET array:
foreach ($_GET as $key => $value) {
if ($key == 'somedata') {
//do something
}
}
You'll find the parameter in the keys of $_GET.
You also could extract the keys from $_GET with array_keys($_GET)
.
Most web servers, since the beginning of the web, allow to define a default file name to be delivered for directories. So if you load http://example.com/ it serves such file (typically index.html
). In PHP enabled systems, you normally use index.php
for such purposes, although the exact name can be changed. In Apache:
http://httpd.apache.org/docs/2.2/en/mod/mod_dir.html#directoryindex
As about ?somedata
, it's just a variable without a value (or, more exactly, its value is an empty string). You can use it if you only need to know whether the variable is set or not:
<?php
if( isset($_GET['somedata']) ){
// Do some stuff
}
?>
精彩评论