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 traditional 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
}
?>
Related
passing data between pages in php have ways like $_GET, $_POST, $_REQUEST etc. But if we are to send data without any variable in php, there is a way which I seem to have forgotten.
For example , let a sample url be : www.mysite.com?123
Is it possible to catch the value 123 from the corresponding php page ?
any use of $_SERVER here?
You can get it using:
$_SERVER["QUERY_STRING"]
This url: www.mysite.com?123 will provide 123 into $_SERVER["QUERY_STRING"].
But be careful, if your url is likewww.mysite.com?123&re=789, $_SERVER["QUERY_STRING"] will be 123&re=789. It catch every thingg after the ?.
easy one, don't forget the $_GET is an array....
so a url like
www.mysite.com?123
$getArrayKeys = array_keys($_GET);
$firstValue = $getArrayKeys[0]; //work with the first param.
var_dump($getArrayKeys); //display all
OUTPUT
array(1) { [0]=> string(6) "123" }
however you're limiting yourself to a single param here... what happens when you need to pass a second param and they are not in the same order?
Try out with:
$_SERVER["QUERY_STRING"]
I believe that browsers default to HTTP GET, so the variables would be accessible by $_GET.
If you are trying to get "123", then key($_GET) should suffice. However if there are more parameters, consider looping through the keys of the $_GET array.
echo 'First $_GET variable: ' . key($_GET);
echo "All the $_GET variables:";
print_r( array_keys($_GET) );
for example the link is:
http://www.test.com/abc.php?config.scp
Is it possible to get the value "config.scp" in the php program? Thanks!
That data is contained in $_SERVER['QUERY_STRING']
If you want a simple string, use $_SERVER['QUERY_STRING'].
If you still need an array with rest of the variables, use $_GET. If you var_dump( $_GET ) on link you provided, you should get:
array(1) {
["config_scp"]=>
string(0) ""
}
You can easily parse it now.
There's one gotcha with dot in that particular query string tho. PHP variables cannot contain dots, so it's changed into _.
Yes... in that case data is field name but be aware that dot is not allowed in $_GET array index.
Also, you can explode $_SERVER['QUERY_STRING'] with & character and look into resulting array for element's value you need.
Hy
See this example:
$url = 'http://www.test.com/abc.php?config.scp';
$p_url = end(explode('?', $url));
echo $p_url;
I am working on a function that takes a string as an argument, which I need to use to get the value of a variable of the same name.
For example
If the string $foo = "$_POST['email']"; is passed I need to retrieve the value of $_POST['email'] and store it as $example, so that $_POST['email'] == $example would return true. There is no feasable way of passing the value directly to function (the variable has to be dynamic to make the function worthwhile).
I did think of using variable variables but they don't work with super globals which will be the primary source of the values I need.
Basically is there a way to get the value of a variable (usually in a superglobal array) with the needed variable as a string?
Let me know if more detail is needed.
Thanks
Variable variables would be the answer, but if you're after fetching values from $_POST array, why not pass just a key to a function?
Note: ths function is provided just for example, my actual recommendation is below.
function fetchFromPost($key) {
if(isset($_POST[$key]) {
return $_POST[$key];
} else {
return null; //or do whatever you want to do in case key is not found
}
}
In fact filter_input(), which allows you to chose an input array, a key and a sanitaion filter to be used, is already there for you
It is possible, although I seriously doubt you should use this. It allows for PHP injection and makes your source code very vulnerable if you don't know where the string came from:
<?
function eval_expression($expression)
{
eval("\$temp = $expression;");
return $temp;
}
// Usage:
echo eval_expression("\$_GET['plop']");
I'm using the SimpleViewer flash image gallery on a site, and it uses an XML file for information about the images it displays.
For the site, I need to dynamically generate the XML, so I'm using a PHP file with a text/xml Content-type declared. However, for some reason when I access one of the GET variables in the $_GET array SimpleViewer tells me that there are no images in the gallery, even though when I view the source it looks the exact same and is well-formed.
Here's the code:
$photos = array(
"1" => array("house1_1.JPG")
);
foreach($photos[$_GET["hid"]] as $p){
echo '';
}
If I replace $_GET["hid"] with "1" then it works fine, but when I make the reference to $_GET it returns the error.
Is there some reason as to why accessing a GET variable would cause scripts linking to the XML (the SimpleViewer flash) to malfunction, and is there a way to get around this?
*Note: The "hid" GET variable is 100% sure set to "1", and there is no PHP error.
Also, the output looks exactly the same for when I use $_GET["hid"] versus "1", the only difference is the SimpleViewer script refuses to see that the images are there.
Also, the stuff in the empty quotes is some XML, but I don't know how to get it to appear in the tags...
Var dump of $photos and $_GET, respectively:
array(1) {
[1]=>
array(1) {
[0]=>
string(12) "house1_1.JPG"
}
}
array(1) {
["hid"]=>
string(1) "1"
}
I would first check and make sure $_GET["hid"] is returning "1". If it's possible that it is not returning "1" then it should throw an error accessing a bad index of $photos.
Is the $_GET hid variable set in your request? If not this will trigger a PHP warning.
var_dump($_GET['hid']); to see the value of the $_GET variable and ensure it as you expect.
Also please ensure that you have error reporting set to at least E_ALL and display errors is set to yes/true to make your debugging easier.
I think you're probably having an issue with the difference between "1" and 1. When you use a get with something like ?hid=1, it's not coming through as a string, that's being converted to a number, whereas your actual array is using the string "1" as the key.
Either change your key to 1 instead of "1" or cast the hid to string.
Issue was never resolved -- I ended up having to just move on and go for a longer and less elegant solution. Oh well.
I'm maintaining a PHP library that is responsible for fetching and storing incoming data (POST, GET, command line arguments, etc). I've just fixed a bug that would not allow it to fetch array variables from POST and GET and I'm wondering whether this is also applicable to the part that deals with the command line.
Can you pass an array as a command line argument to PHP?
Directly not, all arguments passed in command line are strings, but you can use query string as one argument to pass all variables with their names:
php myscript.php a[]=1&a[]=2.2&a[b]=c
<?php
parse_str($argv[1]);
var_dump($a);
?>
/*
array(3) {
[0]=> string(1) "1"
[1]=> string(3) "2.2"
["b"]=>string(1) "c"
}
*/
Strictly speaking, no. However you could pass a serialized (either using PHP's serialize() and unserialize() or using json) array as an argument, so long as the script deserializes it.
something like
php MyScript.php "{'colors':{'red','blue','yellow'},'fruits':{'apple','pear','banana'}}"
I dont think this is ideal however, I'd suggest you think of a different way of tackling whatever problem you're trying to address.
As it was said you can use serialize to pass arrays and other data to command line.
shell_exec('php myScript.php '.escapeshellarg(serialize($myArray)));
And in myScript.php:
$myArray = unserialize($argv[1]);
In case, if you are executing command line script with arguments through code then the best thing is to base encode it -
base64_encode(json_encode($arr));
while sending and decode it while receiving in other script.
json_decode(base64_decode($argv[1]));
That will also solve the issue of json receiving without quotes around the keys and values. Because without quotes, it is considered to be as bad json and you will not be able to decode that.
The following code block will do it passing the array as a set of comma separated values:
<?php
$i_array = explode(',',$argv[1]);
var_dump($i_array);
?>
OUTPUT:
php ./array_play.php 1,2,3
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
You need to figure out some way of encoding your array as a string. Then you can pass this string to PHP CLI as a command line argument and later decode that string.
After following the set of instructions below you can make a call like this:
phpcl yourscript.php _GET='{ "key1": "val1", "key2": "val2" }'
To get this working you need code to execute before the script being called. I use a bash shell on linux and in my .bashrc file I set the command line interface to make the php ini flag auto_prepend_file load my command line bootstrap file (this file should be found somewhere in your php_include_path):
alias phpcl='php -d auto_prepend_file="system/bootstrap/command_line.php"'
This means that each call from the command line will execute this file before running the script that you call. auto_prepend_file is a great way to bootstrap your system, I use it in my standard php.ini to set my final exception and error handlers at a system level. Setting this command line auto_prepend_file overrides my normal setting and I choose to just handle command line arguments so that I can set $_GET or $_POST. Here is the file I prepend:
<?php
// Parse the variables given to a command line script as Query Strings of JSON.
// Variables can be passed as separate arguments or as part of a query string:
// _GET='{ "key1": "val1", "key2": "val2" }' foo='"bar"'
// OR
// _GET='{ "key1": "val1", "key2": "val2" }'\&foo='"bar"'
if ($argc > 1)
{
$parsedArgs = array();
for ($i = 1; $i < $argc; $i++)
{
parse_str($argv[$i], $parsedArgs[$i]);
}
foreach ($parsedArgs as $arg)
{
foreach ($arg as $key => $val)
{
// Set the global variable of name $key to the json decoded value.
$$key = json_decode($val, true);
}
}
unset($parsedArgs);
}
?>
It loops through all arguments passed and sets global variables using variable variables (note the $$). The manual page does say that variable variables doesn't work with superglobals, but it seems to work for me with $_GET (I'm guessing it works with POST too). I choose to pass the values in as JSON. The return value of json_decode will be NULL on error, you should do error checking on the decode if you need it.
Sort of.
If you pass something like this:
$php script.php --opt1={'element1':'value1','element2':'value2'}
You get this in the opt1 argument:
Array(
[0] => 'element1:value1'
[1] => 'element2:value2'
)
so you can convert that using this snippet:
foreach($opt1 as $element){
$element = explode(':', $element);
$real_opt1[$element[0]] = $element[1];
}
which turns it into this:
Array(
[element1] => 'value1'
[element2] => 'value2'
)
So if a CLI is as such
php path\to\script.php param1=no+array param2[]=is+array param2[]=of+two
Then the function thats reads this can be
function getArguments($args){
unset($args[0]); //remove the path to script variable
$string = implode('&',$args);
parse_str($string, $params);
return $params;
}
This would give you
Array
(
[param1] => no array
[param2] => Array
(
[0] => is array
[1] => of two
)
)