isset won't identify parameters in url - php

I have the following code in my file.php file:
if (isset($_POST["activate"])){
$confirmed = true;
$result = execute_query("UPDATE tributes SET t_confirm = 1 WHERE t_id=".$_POST["tid"]." AND t_activation='".$_POST["activate"]."'");
if($result){
}
}else{
print "NO";
}
I call this file throught he following url:
http://localhost/ccmta/tribute.php?tid=55&activate=QiScE8W76whfQD0Twd15enG31yDEf1iVGLL0SHEB9doqI16bd8kskOPXu6bGZE65o7XPp9EXUBCJS7IbcjNZ98hA8vR11b0Ve0Qm
but the isset function won't recognize the activate variable that's in parameter in the URL and falls into the else bracket. I've also called print_r to see what is in the $_POST variable and it's an empty array. Any idea why?

Yes - $_POST is the array of POST, not GET (query string/URL) data. If you want both, use $_REQUEST, otherwise, use $_GET.

Related

Handle a PHP error message when a second node doesn't exist?

Hope someone can help with this
I'm using this to grab the first part of my URL
$page_url = perch_page_url(['include-domain' => false,], true); //
Output the URL of the current page, minus https
$url_parts = explode("/", $page_url); // Split a string by a string
I'm using this technique to grab the first and second nodes of the URL
$first_node = $url_parts[1]; // First part of string
$second_node = $url_parts[2]; // Second part of string
On my homepage, there isn't a second node, so I get an undefined offset message.
Is there a way to check if the $second_node exists?
I've tried using
if (isset($second_node)) {
echo "$second_node is set so I will print.";
}
and
if (!empty($second_node)) {
echo '$second_node is either 0, empty, or not set at all';
}
Both if statements only echo after the $second_node has been set? So I still get the error message.
You can do something like this:
$second_node = isset($url_parts[2]) ? $url_parts[2] : FALSE;
if ($second_node)
{
echo "Second node: {$second_node}";
}
This checks if the third index (0-based) of the $url_parts array is set. If yes, it will assign its value to $second_node. If not, it will assign FALSE so you can handle that further down in the code if you need to check it later (again).
That is because the error is thrown at the initialization of your $second_node variable.
Check if the node exists first, and then declare the variable:
$second_node = ""; // Or whatever
if (isset($url_parts[2]) {
$second_node = $url_parts[2];
}
Check it here: https://3v4l.org/fRJ7L
Please use it directly in the if condition and avoid assigning to a variable or assign after checking it in if condition
if (isset($url_parts[2])) { // remove this line $second_node = $url_parts[2];
echo "$second_node is set so I will print.";
}

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';
}

How to Print a variable in a function in PHP

I have a form, with post="ModelSelector", when submitted, we go through these codes.
Issue I'm facing is, I want to check the value of $_POST, I know it is getting set by calling "isset()".
I just want to Print/alert/pushout the variable $productselection
function selectProduct() {
// save the post in a variable
$ProductSelections = $_POST['ModelSelector'];
// I want to print $ProductSelection to check its value
$frmVars['ProductSelections'] = $ProductSelections;
$frmVars['WindowSize'] = $WindowSize;
$frmVars['PageNum'] = 1;
saveFormValues(0,'RunDefMgr', $frmVars);
// Clear the checkboxes
$sel = array();
deleteRunDef(0,"*","RUN_DEF_EDIT","*");
}
if(isset($_POST['ModelSelector'])) {
selectProduct();
}
I have tried ECHO, for some reason it is not printing the value in HTML.
Thanks in advance.
I want to check the value of $_POST
$_POST will be an array.
Use print_r($_POST) or var_dump($_POST) to view its contents.
Your form method should be method="POST", You can use the following edit to see if it works , as you have to pass $_POST (array) to the function to use it inside function. function expects an parameter else , $_POST does not exists.
And also enable the errors inside your file to check which type of errors you are getting by using : ini_set('display_errors',1); or error_reporting(E_ALL);
function selectProduct($_POST) { // create parameter $_POST which we get from isset condition.
// save the post in a variable
$ProductSelections = $_POST['ModelSelector'];
print_r($ProductSelections); // print the value.
// I want to print $ProductSelection to check its value
$frmVars['ProductSelections'] = $ProductSelections;
$frmVars['WindowSize'] = $WindowSize;
$frmVars['PageNum'] = 1;
saveFormValues(0,'RunDefMgr', $frmVars);
// Clear the checkboxes
$sel = array();
deleteRunDef(0,"*","RUN_DEF_EDIT","*");
}
if(isset($_POST['ModelSelector'])) {
selectProduct($_POST); // pass the $_POST array to the selectProduct function.
}

"if else statement" when no $_REQUEST exist

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'];
}

Php pages dependent on query string but what if there's no parameter?

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!

Categories