PHP: How to get keyless URL parameters - php

I would like to get the parameter in a key such as http://link.com/?parameter
I read somewhere that the key is NULL and the value would be parameter.
I tried $_GET[NULL] but it didn't seem to work.
Here is my code:
if ($_GET[NULL] == "parameter") {
echo 'Invoked parameter.';
} else {
echo '..';
}
It just prints out .. so that means I'm not doing it right. Can someone please show me the right way.

There are no such things as keyless URL parameters in PHP. ?parameter is the equivalent of $_GET['parameter'] being set to an empty string.
Try doing var_dump($_GET) with a url like http://link.com/?parameter and see what you get.
It should look something like this:
array (size=1)
'parameter' => string '' (length=0)
Thus, you can test it in a couple of ways depending on your application needs:
if (isset($_GET['parameter'])) {
// do something
} else {
// do something else
}
or
// Only recommended if you're 100% sure that 'parameter' will always be in the URL.
// Otherwise this will throw an undefined index error. isset() is a more reliable test.
if ($_GET['parameter'] === '') {
// do something
} else {
// do something else
}

$_GET is a super global assoc array, that contains parameter=>it's value pairs. So, parameter is a key of the array.
For example, if your url is something like this: myweb.com/?page=load&do=magic than you $_GET is:
$_GET(
[page] => load
[do] => magic
)
If you want just to test, if parameter is in you URL as a param, you should do something like this:
if (isset($_GET['parameter'])
echo "Here I am!";

You can also get the entire request_url like this
echo $_SERVER['REQUEST_URI'];
To get the part after ?:
echo explode('?', $_SERVER['REQUEST_URI'])[1];

You can get the part of the URL beginning with ? with
$_SERVER['QUERY_STRING']

You could via array_keys():
$param = array_keys($_GET)[0];
Which would give you the name of the first querystring parameter, whether it has a value or not.
You could also get all of the parameters without a value like so:
$empty = [];
foreach($_GET as $key => $value)
if(strlen($value) === 0) $empty[] = $key;
print_r($empty);

Related

Easiest way to check if multiple POST parameters are set?

Hi so I want to know the easiest way to check if multiple POST parameters are set. Instead of doing a long if check with multiple "isset($_POST['example'])" linked together by "&&", I wanted to know if there was a cleaner way of doing it.
What I ended up doing was making an array and looping over it:
$params_needed = ["song_name", "artist_name", "song_release_date",
"song_genre", "song_medium"];
I would then call the function below, passing in $params_needed to check if the parameter names above are set:
function all_params_valid($params_needed) {
foreach ($params_needed as $param) {
if (!isset($_POST[$param])) {
error("Missing the " . $param . " variable in POST request.");
return false;
}
}
return true;
}
if (all_params_valid($params_needed)) {
$song_name = $_POST["song_name"];
$artist_name = $_POST["artist_name"];
$song_release_date = $_POST["song_release_date"];
$song_genre = $_POST["song_genre"];
$song_medium = $_POST["song_medium"];
...
}
However when I do this, it gets stuck on the first index and says "Missing the song_name variable..." despite actually including it in the POST request, and I'm not sure why this is happening. The expected behavior would be for it to move on and tell me the next parameter "artist_name" is not set, but this doesn't happen.
I personally like using array_diff for this issue.
PHP array_diff documentation
What you care about is your expected input is the same as the given input.
So you can use array_diff like this:
$params_needed = ["song_name", "artist_name", "song_release_date",
"song_genre", "song_medium"];
$given_params = array_keys($_POST);
$missing_params = array_diff($params_needed, $given_params);
if(!empty($missing_params)) {
// uh oh, someone didn't complete the form completely...
}
How I approach this is by using array_map() so I can return all the values in the array whilst checking if it isset()
PHP 5.6 >
$args = array_map(function($key) {
return isset($_POST[$key]) ? array($key => $_POST[$key]) : someErrorMethod($key);
}, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]);
PHP 7+
$args = array_map(function($key) {
return array($key => $_POST[$key] ?? someErrorMethod($key));
}, ["song_name", "artist_name", "song_release_date", "song_genre", "song_medium"]);
Your error method could look something like this:
function someErrorMethod($key) { die("$key cannot be empty."); }
Inside of your $args variable, you will have an array of key => value. For example,
echo $args['song_name'];

Put $_GET parameter in php variable

Is it possible to take $_GET parameter from the url and put it in php variable without using foreach?
If I do:
var_dump($_GET);
I will get the result:
array(1) { ["block_simple_clock"]=> string(0) "" }
I need to put that value block_simple_clock in a string variable, and I can do that with a foreach:
foreach($_GET as $key => $value) {
var_dump($key);
}
But I would really like to take that value without a foreach if it is possible. I hate using foreach for such a trivial problem :)
Sorry for confusion, that block_simple_clock is a variable, and it can be a different value, I am sending this value with this code:
foreach ($pluginlist->plugins as $key => $plugin) {
if (empty($plugin->component)) {
continue;
}
if (in_array($plugin->component, $arr)) {
if (!in_array($plugin->component, $contribs)) {
$target_url = new moodle_url('redirect.php');
$mform->addElement('advcheckbox', $plugin->component, "<a href={$target_url}?$plugin->component target='_blank'>" . $plugin->name . "</a>", '', array(0, 1));
}
}
$requestedPluginIdCounter++;
}
As you can see the $plugin->component is the value that I am sending via $_GET.
$variable = $_GET['block_simple_clock'];
OR
$variable = $_REQUEST['block_simple_clock'];
If you know exactly which ones you need, you can use
$var = $_GET['name-in-get'];
You mays want to use the function
extract( $_GET );
Which creates global variables with the name of the key :
//suppose GET = $_GET['name']
extract( $_GET );
echo $name; //will echo $_GET['name']
Remember to ALWAYS filter gets and posts values, since they are user input (obviously it depends what you do with them, but especially if they're used for database purposes, it is extremely important)
For more information, see filter_input function
You can do this :
$t = array_keys($_GET);
echo $t[0];
Thank you guys, I have added a name=$plugin->component, and was able to extract the variable with that $_GET["name"] :)

Is there a php function which returns whether the query string is empty?

I'm designing a semi-basic tool in php, I have more experience server side, and not in php.
My tool contains 10-15 pages, and I am doing the navigation between them with the $_GET parameter.
I would like to check if the query string is empty (to know if I'm in the home page). Is there any php function for this ? Of course I can do it manually, but still?
EDIT: My question is if there is a function that replaces
if(! isset("param1") && .....&& ! isset("paramN")){
...
}
Try below
if(isset($_GET['YOUR_VARIABLE_NAME']) && !empty($_GET['YOUR_VARIABLE_NAME'])) {
}
isset() is used to check whether there is any such variable or not
empty() to check whether the variable is not empty or not
As per your comment, assume your URL as below
http://192.168.100.68/stack/php/get.php?id=&name=&action=delete&type=category
And your PHP script as below
<?php
$qs = $_GET;
$result = '';
foreach($qs as $key=>$val){
if(empty($val)){
$result .= 'Query String \''.$key.'\' is empty. <br />';
}
}
echo '<pre>'; print_r($result);
?>
In my above URL I passed id and name as empty.
Hence, Result will be like below
id is empty.
name is empty.
but I dont think its standard way.
If you want to process something only if all parameters are having some values, they you can move those process inside a if as below
if(empty($result)) {
// YOUR PROCESS CODE GOES HERE
} else {
echo 'Some Required Parameters are missing. Check again';
}

working with 3 $_GET values

I have a problem with $_GET array. On my page a value comes from URL like this.
http://localhost/search.php?subject=Mathematics
I check this $_GET value something like this..
// Check for a valid keyword from search input:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
foreach ( $_GET AS $key => $subject) {
$searchKey = $key;
$searchKeyword = '%'.$subject.'%';
}
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Now its working for me. But my problem is I am using another two variables to pass through URL on same page to filter my database values.
echo '<li>Tutor</li>
<li>Institute</li>';
This two links I used to filter my database values (clicking on this link).
$tutor = isset($_GET['institute']) ? '0' : '1';
$institute = isset($_GET['tutor']) ? '0' : '1';
My problem is when I am trying filter database result clicking on the above link its always going this code instead of displaying filtered result.
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Can anybody tell me how I use this 3 $_GET values.
Why not just add a clause in the else:
elseif(!isset($_GET['institute']) && !isset($_GET['tutor']))
{
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
You need to make sure the url looks like this:
http://localhost/search.php?subject=Mathematics&tutor=tutorName&institute=instituteName
A ? denotes the beginning of the URL parameters, an & marks the separation between url parameters
Your problem doesn't seem to be, that you're running into the else loop (or better said: not the only problem). It looks like your first parameter gets lost with the second link. I think, the second link should react like some kind of extended search filter, that shoud be applied to the recently displayed content, or am I totally wrong at understanding you?
Perhaps this could solve your problem for creating the follow-up URLs.
$params = array();
foreach($_GET as $key => $value) {
$params[] = '&'.$key.'='.$value;
}
$url1 = '?tutor=link'.implode('', $params);
$url2 = '?institute=link'.implode('', $params);
And when you output the links:
echo '<li>Tutor</li>
<li>Institute</li>';
Your problem is that you are only checking the $_GET['subject'] variable, which is no being passed in. You could do this in a few ways, all resulting in changing:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
1) include all variables in the conditional string:
if ( ((isset($_GET['subject'])) && (is_string ($_GET['subject']))) || ((isset($_GET['institute'])) && (is_string ($_GET['institute']))) || ((isset($_GET['tutor'])) && (is_string ($_GET['tutor']))) ) {
2) Pass in searchKey=1 or something in all your links and use:
if ( isset($_GET['searchKey']) ) { // From SESSION
Revised links:
echo '<li>Tutor</li>
<li>Institute</li>';
If you are looking to pass in more than one variable at once, you will need to put the search keys into an array.

Get URL query string parameters

What is the "less code needed" way to get parameters from a URL query string which is formatted like the following?
www.mysite.com/category/subcategory?myqueryhash
Output should be: myqueryhash
I am aware of this approach:
www.mysite.com/category/subcategory?q=myquery
<?php
echo $_GET['q']; //Output: myquery
?>
$_SERVER['QUERY_STRING'] contains the data that you are looking for.
DOCUMENTATION
php.net: $_SERVER - Manual
The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.
Example:
$url = 'www.mysite.com/category/subcategory?myqueryhash';
echo parse_url($url, PHP_URL_QUERY); # output "myqueryhash"
Full documentation here
The function parse_str() automatically reads all query parameters into an array.
For example, if the URL is http://www.example.com/page.php?x=100&y=200, the code
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
will store parameter values into the $queries array ($queries['x']=100, $queries['y']=200).
Look at documentation of parse_str
EDIT
According to the PHP documentation, parse_str() should only be used with a second parameter (array). Using parse_str($_SERVER['QUERY_STRING']) on this URL will create variables $x and $y, which makes the code vulnerable to attacks such as http://www.example.com/page.php?authenticated=1.
If you want the whole query string:
$_SERVER["QUERY_STRING"]
I will recommend the best answer as:
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered http://example.com/?name=Hannes
The above example will output:
Hello Hannes!
Programming Language: PHP
// Inintialize a URL to the variable
$url = 'https://www.youtube.com/watch?v=qnMxsGeDz90';
// Use parse_url() function to parse the URL
// and return an associative array which contains its various components
$url_components = parse_url($url);
// Use the parse_str() function to parse the
// string passed via the URL
parse_str($url_components['query'], $params);
// Display result
echo 'v parameter value is ' . $params['v'];
This worked for me.
Also if you are looking for current file name along with the query string, you will just need following
basename($_SERVER['REQUEST_URI'])
It would provide you info like following example
file.php?arg1=val&arg2=val
And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing
$_SERVER['REQUEST_URI']
This code and notation is not mine. Evan K solves a multi value same name query with a custom function ;)
is taken from:
http://php.net/manual/en/function.parse-str.php#76792
Credits go to Evan K.
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');
# the above produces:
$foo = array('foo' => '3');
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');
# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>
This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function:
<?php
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
Here is my function to rebuild parts of the REFERRER's query string.
If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET vars (e.g. a page number).
Example: Referrer's query string was ?foo=1&bar=2&baz=3 calling refererQueryString( 'foo' , 'baz' ) returns foo=1&baz=3":
function refererQueryString(/* var args */) {
//Return empty string if no referer or no $_GET vars in referer available:
if (!isset($_SERVER['HTTP_REFERER']) ||
empty( $_SERVER['HTTP_REFERER']) ||
empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {
return '';
}
//Get URL query of referer (something like "threadID=7&page=8")
$refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);
//Which values do you want to extract? (You passed their names as variables.)
$args = func_get_args();
//Get '[key=name]' strings out of referer's URL:
$pairs = explode('&',$refererQueryString);
//String you will return later:
$return = '';
//Analyze retrieved strings and look for the ones of interest:
foreach ($pairs as $pair) {
$keyVal = explode('=',$pair);
$key = &$keyVal[0];
$val = urlencode($keyVal[1]);
//If you passed the name as arg, attach current pair to return string:
if(in_array($key,$args)) {
$return .= '&'. $key . '=' .$val;
}
}
//Here are your returned 'key=value' pairs glued together with "&":
return ltrim($return,'&');
}
//If your referer was 'page.php?foo=1&bar=2&baz=3'
//and you want to header() back to 'page.php?foo=1&baz=3'
//(no 'bar', only foo and baz), then apply:
header('Location: page.php?'.refererQueryString('foo','baz'));
Thanks to #K. Shahzad.
This helps when you want the rewritten query string without any rewrite additions. Let’s say you rewrite the /test/?x=y to index.php?q=test&x=y and you only want the query string.
function get_query_string(){
$arr = explode("?", $_SERVER['REQUEST_URI']);
if (count($arr) == 2){
return "";
}
else{
return "?" . end($arr) . "<br>";
}
}
$query_string = get_query_string();
For getting each node in the URI, you can use function explode() for $_SERVER['REQUEST_URI']. If you want to get strings without knowing if they are passed or not, you may use the function I defined myself to get query parameters from $_REQUEST (as it works both for POST and GET parameters).
function getv($key, $default = '', $data_type = '')
{
$param = (isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default);
if (!is_array($param) && $data_type == 'int') {
$param = intval($param);
}
return $param;
}
There might be some cases when we want to get query parameters converted into Integer type, so I added the third parameter to this function.

Categories