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.
Related
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';
}
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);
At the moment i'm calling the following via GET
$RimWidth = $_GET['RimWidth'];
$TyreWidth = $_GET['TyreWidth'];
$Aspect = $_GET['Aspect'];
$TyreDia = $_GET['TyreDia'];
$TyreMan = $_GET['TyreMan'];
However in my paginiation, after page 1 it looses the variables and doesn't work. I understand i need to store them in the session. How do i do this as i've seen a few way of doing it and can't get it to work and how do i place them onto the end of the pagination links which look like this
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
thanks
If you want to just repeat the $_GET values, you can make a function to do that:
//A function to get and repeat arguments in every link
function repeatvars(){
if(isset($_GET) && empty($_GET) == false){
$variables = "?";
$arraycount = count($_GET) - 1;
$count = 0;
foreach ($_GET as $var => $value){
if(empty($value) == true){
$variables .= $var;
}else{
$variables .= $var."=".$value;
}
if ($count !== $arraycount){
$variables .= "&";
}
$count++;
}
return $variables;
}}
//Example
echo 'Next Page (Link: nextpage.php'.repeatvars().')';
You need this at the top of your PHP pages if using sessions:
session_start();
Then, you should really do this for each one:
$RimWidth = isset($_GET['RimWidth']) ? trim(strip_tags($_GET['RimWidth'])) : null;
$_SESSION['RimWidth'] = $RimWidth;
// and so on
trim() and strip_tags() removes any unwanted white-space and removes any malicious script tags being sent to your page. Never trust any POST, GET or SESSION data. They can all be compromised by hackers. If RimWidth always returns an integer, then put (int) before, like this:
(int) $RimWidth = isset($_GET['RimWidth']).............
You shouldn't need to add the session variables to the end of your pagination links, they're session variables and will be available on the next page, or any other page.
To call them on another page, do this:
echo $_SESSION['RimWidth'];
I am making a simple if and else statement to get value from a requested link my code is
if($_REQUEST['f_id']=='')
{
$friend_id=0;
}
else
{
$friend_id=$_REQUEST['f_id'];
}
and suppose the link is www.example.com/profile.php?f_id=3
now its simple as if the f_id is empty or with value either of the above if and else statement would run. but what is a user is just playing around with link and he removes the whole ?f_id=3 with link left to be opened with www.example.com/profile.php then how to detect that f_id dosen't exist and in that case redirect to a error page ?
if ( isset( $_REQUEST['f_id'] ) ) {
if($_REQUEST['f_id']=='') {
$friend_id=0;
} else {
$friend_id=$_REQUEST['f_id'];
}
} else {
REDIRECT TO ERROR PAGE
}
UPDATE Since your URLS-s look like www.example.com/profile.php?f_id=3 you should use $_GET instead of $_REQUEST
you can use the isset() php function to test that:
if(!isset($_REQUEST) || $_REQUEST['f_id']=='')
{
$friend_id=0;
}
else
{
$friend_id=$_REQUEST['f_id'];
}
Late answer, but here's an "elegant" solution that I always use. I start with this code for all the variables I'm interested in and go from there. There are a number of other things you can do with the extracted variables as well shown in the PHP EXTRACT documentation.
// Set the variables that I'm allowing in the script (and optionally their defaults)
$f_id = null // Default if not supplied, will be null if not in querystring
//$f_id = 0 // Default if not supplied, will be false if not in querystring
//$f_id = 'NotFound' // Default if not supplied, will be 'NotFound' if not in querystring
// Choose where the variable is coming from
extract($_REQUEST, EXTR_IF_EXISTS); // Data from GET or POST
//extract($_GET, EXTR_IF_EXISTS); // Data must be in GET
//extract($_POST, EXTR_IF_EXISTS); // Data must be in POST
if(!$f_id) {
die("f_id not supplied...do redirect here");
}
You could use empty to combine the 2x isset into 1 statement (unless you actually have a friend_id of 0 which would result in empty being true)
if(empty($_REQUEST['f_id'])) {
$friend_id=0;
} else {
$friend_id=$_REQUEST['f_id'];
}
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!