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'];
}
Related
I keep trying to find how to do this online and I am unable to find it.
I have the following:
if (isset($_GET['the_country']))
I have a selection box in an html form for "the_country" and "the_city". I want to have an if statement for if the_country is set, the_city is set, and if the_country and the_city are set. How would I make the if statements read if I want them to run like this. I see the issue coming where even if both are set, it would take my first if statements also because they are each set on their own. How would I basically convert this into the following:
If(the_country is set and the the_city not set)
If(the_city is set and the the_country not set)
If(the_country is set and the the_city is set)
With the current input structure, you can divide the conditions into 4 blocks:
$isCountry = isset($_GET['the_country']);
$isCity = isset($_GET['the_city']);
if ($isCountry && $isCity) {
// both set
} elseif ($isCountry && !$isCity) {
// only country set
} elseif (!$isCountry && $isCity) {
// only city set
} else {
// none set
}
Method 1:
It can be done in many ways. But a more straightforward approach is writing the if-else directly.
if (isset($_GET['the_country']) && if (isset($_GET['the_city'])) {
// both the country and the city are set
} else if (isset($_GET['the_country']) && !isset($_GET['the_city'])) {
// country is set city is not set
} else if (!isset($_GET['the_country']) && isset($_GET['the_city'])) {
// country is not set the city is set
} else {
// both country and city are not set
}
isset checks if the variable is set. It will return true even if the variable is assigned a null value.
<?php
$a='';
var_dump(isset($a));// true
var_dump(isset($b));// false
If you need to check if the_city and the_country have a valid input, use empty() instead of isset().
Method 2:
Obviously, it will become more complicated as the number of inputs increases. You will be having a lengthy if-else-if ladder in your code.
To avoid that you can write a validation logic as shown below:
$inputFields = [
'the_city' => null,
'the_country' => null,
];
$userInput = array_merge($inputFields, $_GET);
$validated = array_filter($userInput, function($val) {
return $val !== null;
});
$errors = array_diff_key($userInput, $validated);
if (! empty($errors)) {
echo 'The fields ' . implode(',', array_keys($errors)) . ' are empty';
}
Also, you can consider writing a validation class with the same logic for code reuse.
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'm trying to pass a value between 2 pages through a $_SESSION variable then empty it as follows:
I'm assigning the session variable with a value on one PHP page:
$_SESSION["elementName"]="a_373";
And trying to store it in a variable on another page as follows:
if (!empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
The value of $elemName is always empty when I print it out. However, I get the correct printout when I remove the $_SESSION["elementName"]=""; line from the above code.
Edit: I'm printing $elemName and not $_SESSION["elementName"] - print($elemName);
I'm on a shared hosting account with PHP 5.3.2 and register_globals set to off (as per phpinfo();).
I need to reset/empty the session variable once I get the value it has, but it's not working and this has been baffling me for the last couple of days. Any ideas why? Thanks!
EDIT:
Additional clues: I tested with the session's var_dump before the if statement and set another value for $elemName in the else section as follows:
var_dump($_SESSION["elementName"]);
$elemName="x";
if (isset($_SESSION["elementName"]) && !empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="None";
}
print("<br />".$elemName);
I got this result:
string(5) "a_373"
None
Try using isset($_SESSION["elementName"]) and unset($_SESSION["elementName"]) instead.
Check the Below code and test it
if (isset($_SESSION["elementName"]) && $_SESSION["elementName"]!="") {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
Empty only check value is empty or not, But by isset we can check varaible exit and does not content empty value
Are you printing out $elemName? If yes than there shouldn't be any blank output unless and until your else condition returns true, but if you are printing $_SESSION["elementName"] than you'll get no output as you are making it blank
$_SESSION["elementName"]="";
Correct way to remove a session var completely is to use unset($_SESSION["elementName"])
Though if you want to make it empty, == '' is enough
Also be cautious while using unset() because after you unset the session and later use that index to print, it will show you undefined index error.
Update(As #nvanesch Commented)
I guess your else condition is getting satisfied, because you are
using $elemName=""; in your else, thus you are not returned with any
output
Also if (!empty($_SESSION["elementName"])) { will return false if you are not using session_start() at the very top of your page
I once created this class in order to be able to have this ability, and it works wonderfully:
<?php
class Flash {
public function set($key, $message) {
$_SESSION["flash_$key"] = $message;
}
public function get($key) {
$message = $_SESSION["flash_$key"];
unset($_SESSION["flash_$key"]);
return $message;
}
public function has($key) {
return isset($_SESSION["flash_$key"]);
}
}
It's pretty similar to what you're trying to do, so I'm not sure why it's not working for you, but you may want to give it a try. You obviously need to have the session already started.
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.
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!