php get variables - php

I'm new to php and need some help with "GET" variables.
Here an extraction of my Code for index.php:
$array = array("section","view","sub","cat","point");
$i = 0;
$check = true;
foreach ($_GET as $position => $wert) {
if ($position != $array[$i]) {
//if GET doesnt exist in the array set check to false
$check = false;
break;
}
$i++;
}
//if GET variables exists
if ($check == true) {
if (isset($_GET['section'], $_GET['view'], $_GET['sub'], $_GET['cat'], $_GET['point'], $point[$_GET['point']])) {
$path = $path_dynamic.$_GET['section']."/".$_GET['view']."/".$_GET['sub']."/".$_GET['cat']."/".$point[$_GET['point']];
check($path);
} else if (isset($_GET['section'], $_GET['view'], $_GET['sub'], $_GET['cat'], $cat[$_GET['cat']])) {
$path = $path_dynamic.$_GET['section']."/".$_GET['view']."/".$_GET['sub']."/".$cat[$_GET['cat']];
check($path);
} else if (isset($_GET['section'], $_GET['view'], $_GET['sub'], $sub[$_GET['sub']])) {
$path = $path_dynamic.$_GET['section']."/".$_GET['view']."/".$sub[$_GET['sub']];
check($path);
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
$path = $path_dynamic.$_GET['section']."/".$view[$_GET['view']];
check($path);
} else if (isset($_GET['section'], $section[$_GET['section']])) {
$path = $path_dynamic.$section[$_GET['section']];
check($path);
//if section isn't set
} else if (!isset($_GET['section'])) {
include ($path_dynamic.$section['news']);
}
} else {
echo "GET doesn't exist";
include ($path_static.$section['error']);
}
//check if GET exists
function check($path) {
if (file_exists($path)) {
echo "File imported<br />";
include ($path);
} else {
echo "GET set correct but file doens't exist";
include ('include/static/fehler.html');
}
}
Example of section.php (view, sub, cat and point is the same):
$section = array();
$section['error'] = 'fehler.html';
My problem is that if i set this link:
index.php?section=verein&view=vorstande
"vorstande" doesn't exist in my view array. So the code checks for the section "verein" and include "verein". But it should give an error.
So it seems that this code
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
is ignored and it jumps to
} else if (isset($_GET['section'], $section[$_GET['section']])) {
Also if I change my url to this:
index.php?section=vereine&view=vorstande
nothing happens. I even don't know where the code is right now.
But if I change the url to this:
index.php?section=vereine&view=vorstand
everything works fine.
So "verein" and "vorstand" is defined by me. "vereine" and "vorstande" doens't exist.
Any suggestions? Sry for comments in german. The echo only gives me a hint where the code is right now!
Link to my HP:
Edit:
- translated comments for better conversation
- deleted all "$...[$_GET['...']]" structures to show the error I will get instead.

"vorstande" doesn't exist in my view array. So the code checks for the
section "verein" and include "verein". But it should give an error.
By "give an error" you mean $check = false;?
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
If in your $view the key vorstande does not exist, this the whole condition will evaluate to false and next condition will be checked:
} else if (isset($_GET['section'], $section[$_GET['section']])) {
Edit:
Your code:
else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
$path = $path_dynamic.$_GET['section']."/".$view[$_GET['view']];
check($path);
}
Your requirement:
if (!isset($view[$_GET['view']]))
check(/* something invalid to display fehler.html */ false);
What actually happens:
isset($_GET['section']) // true
isset($_GET['view']) // true
isset($view[$_GET['view']]) // FALSE
=> isset($_GET['section'], $_GET['view'], $view[$_GET['view']]) // FALSE
If the $_GET['view'] does not exist in $view, the block which would call check is not executed. If you want it to be executed regardless, simply remove the condition isset($view[$_GET['view']]):
else if (isset($_GET['section'], $_GET['view'])) {
$path = $path_dynamic.$_GET['section']."/".#$view[$_GET['view']]; // # to suppress errors from accessing
check($path);
}
If you don't like this approach, work on your cases. You have one case for section isset AND view isset AND view is valid. The next case ignores the view parameter. So if your view parameter is not valid, your code handles it like it was not set. The requirement though is to have a case for section isset AND view isset AND view is invalid:
else if (isset($_GET['section'], $_GET['view']) && !isset($view[$_GET['view']])) {
check(false);
}
This is of course pretty much redundant checking so just nest it to something like:
else if (isset($_GET['section'], $_GET['view']))
{
// section and view have been passed
if (isset($view[$_GET['view']])
// view is actually valid
$path = $path_dynamic.$_GET['section']."/".$view[$_GET['view']];
else
// view has been passed but is invalid. show fehler.html
$path = false;
check($path);
}
Alternate Example
If I understand you correctly, you have the following requirement: If the user passes a parameter section, view, sub, cat or point, you want that this value is also in your list of valid values. If it isn't, you want to display fehler.html.
We now first ensure that if the parameter is set, it is also valid:
foreach ($array as $param)
{
// example for $param == "view":
// !isset( $view[$_GET["view"]] )
if (!isset( ${$param}[$_GET[$param]] ))
{
$check = false;
break;
}
}
We then check all your combinations of parameters and build a $path
$path = false;
if ($check)
{
// your long if isset else if isset block where
// isset($_GET['view']) also implies isset($view[$_GET['view']])
// so you don't have to check for it.
// just set the $path variable with some string.
// we are going to check it later
}
If now the initial $check failed or we built an invalid $path, display fehler.html
if ($check === false || !file_exists($path))
{
// display fehler.html
}
else
include($path);

The problem is here:
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
Each parameter of isset must be true for the statement to return true. In your example, $_GET['section'] and $_GET['view'] are set, but $view[$_GET['view']] is not, so execution continues on the next else if line.
To fix the problem, either set $view[$_GET['view']] previously, or remove that parameter.

Related

PHP: How can i make so non valid users gets another zipfile?

I am really new at php and i came across this code.
Right now it checks for the hwid of a user and grants permission to a zip file if the hwid is in the valid users.
How can i make so the non valid users gets another zipfile to download?
Code:
`
$VALID_USERS = [
'BB12313-25DC-5132-BCEA-B23123123123',
''
];
$IS_REQUEST_ALLOWED = false;
if(!isset($_POST['hwid']) && !isset($_GET['hwid'])) { die(); }
$USER_HWID = '0';
if(isset($_POST['hwid'])) {
$USER_HWID = $_POST['hwid'];
} else {
$USER_HWID = $_GET['hwid'];
}
$USER_HWID = trim($USER_HWID);
$USER_HWID = strtoupper($USER_HWID);
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
`
Assuming other code functions properly, your if clause at the end should look like this:
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('OtherFile.zip'); die();
}
After you compare $HWID === $USER, offer a different file in the ELSE added below.
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
} else { //not a valid user
readfile("./invalid_file.zip");die();
}
}
Note that this will give "invalid_file.zip" to anyone who doesn't meet the criteria ($HWID===$USER) (maybe, see below).
Also, die() is rather a nasty way to exit (it doesn't even tell the user why it's leaving ...).
Please also take a look at your $VALID_USERS array. Surely you don't mean to have a null value in there?
Finally, what about the case of someone else who isn't null or "BB12313-25DC-5132-BCEA-B23123123123"?
You might wish to reconsider the use of this code.
Replace your entire foreach loop with this one if block. Since you are keeping your VALID_USERS in an array, you can use in_array() to quickly check if you user is there, the loop is unnecessary.
This:
foreach($VALID_USERS as $USER) {
$USER = strtolower($USER);
$HWID = strtolower($USER_HWID);
if($HWID === $USER) {
readfile('./ZIPFILE.zip'); die();
}
}
Becomes:
if (in_array($USER_HWID, $VALID_USERS, true)) {
readfile('./ZIPFILE.zip'); die();
} else {
readfile('./SomeOtherZIPFILE.zip'); die();
}
You will also notice that the 3rd paramter to in_array() has been set true in this example. This enables strict type comparison, to match the original codes '===' check.

if statement not returning proper result

I have created a function that checks if the image is empty or image variable has no value or the image is not found then it returns default image, but on some products it gives results but not on all of them..
function image_check($image)
{
$no_image = "noimagefound.jpg";
if(isset($image) || !empty($image) || $image != " ")
{
if(file_exists('uploads/store/products/'.$image))
{
return 'uploads/store/products/'.$image;
}
else
{
return 'uploads/web_service/'.$no_image;
}
}
else
{
return 'uploads/web_service/'.$no_image;
}
}
Can anyone make it work properly? What am I missing?
function image_check($image)
{
$no_image = "noimagefound.jpg";
if( !empty($image) && file_exists('uploads/store/products/'.$image) )
{
return 'uploads/store/products/'.$image;
}
return 'uploads/web_service/'.$no_image;
}
As they pointed out in the comments, your condition failed because you were checking if it was empty, not if it wasn't empty. isset() and !empty() are redundant in this case.
You also don't need all of those else checks. Be careful complicating your code more than you need to. You only need one check, if that fails, then return your $no_image.

GeoIP function returning 0

I'm working on implementing some geoIP functionality to redirect a user away from my .com site to the relevant country domain (.fr, .es, .co.uk ...etc).
I've the following in my index.php to check the users IP:
ini_set('display_errors', 1);
require_once("geoip.inc");
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
if($country_code == 'ES')
{
header('Location: https://www.testsite.es');
}
elseif($country_code == 'GB')
{
header('Location: https://www.testsite.co.uk');
}
elseif($country_code == 'FR')
{
header('Location: https://www.testsite.fr');
}
else {
header('Location: https://www.testsite.com/home');
}
When I check the $country_code variable it is an empty String and as a result the above fails and I always hit https://www.testsite.com/home...
I started delving into the code and noticed that first I call this method:
function geoip_country_code_by_addr($gi, $addr) {
if ($gi->databaseType == GEOIP_CITY_EDITION_REV1) {
$record = geoip_record_by_addr($gi, $addr);
if ($record !== false) {
return $record->country_code;
}
} else {
$country_id = geoip_country_id_by_addr($gi, $addr);
if ($country_id !== false) {
return $gi->GEOIP_COUNTRY_CODES[$country_id];
}
}
return false;
}
which calls:
function geoip_country_id_by_addr($gi, $addr) {
$ipnum = ip2long($addr);
return _geoip_seek_country($gi, $ipnum) - GEOIP_COUNTRY_BEGIN;
}
I can't figure out why it keeps failing and returning a '0'? I am using Maxminds geoip.inc php to check the country code.
I've checked that mbstring is enabled within my php.ini file and it is. For some reason it just doesn't find the Country code based on the IP I pass to it. Does anyone have any help in terms of what might be causing this?
just wanted to say that I've resolved the issue. A mistake on my part and probably a sign that I need a break!
Within geoip.inc.php supplied by Maxmind I was initially getting these errors:
Cannot redeclare geoip_country_code_by_name() in geoip.inc on line 438
In order to fix this I simply check if the method is defined and if not I use it as follows:
if (!function_exists('geoip_country_code_by_name')) {
function geoip_country_code_by_name($gi, $name) {
$country_id = geoip_country_id_by_name($gi, $name);
if ($country_id !== false) {
return $gi->GEOIP_COUNTRY_CODES[$country_id];
}
return false;
}
}
I unfortunately had a minor typo in the above code which prevented the code from executing properly hence returing 0 each and every time.

How to determine if file text search returns no matches?

I have created a piece of code that checks files for a user-submitted string within a set of files. The code searches a directory, returns the file, then searches for the string in the file. The user will input the custom string through an input field and then clicking a submit button.
I have successfully been able to create a condition where, if the user does not enter any information, the output will say, "Your search produced no results". However, I have not been able to figure out how to create a condition where, if the user enters a string that isn't found within the files, that the output will also be, "Your search produced no results".
The code for the existing conditional I have as of now is this:
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results";
}
The code that searches for the files and also searches for the string is found here (this is the entire PHP file, actually, and it includes the conditional I posted above.) I need help on how to create another conditional that throws a message if the user-input isn't found in any of the files.
If this seems unclear, I apologize and will clarify any information you need if you think it will help.
Calling Code
$query = $_POST['query'];
if ((isset($query)) && (empty($query))) {
echo "Your search produced no results.";
}
else {
find_files('.');
}
find_files()
function find_files($seed)
{
if (! is_dir($seed))
return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if (is_dir($path)) {
$dirs[] = $path;
}
else {
if (preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
}
closedir($dh);
}
}
check_files()
function check_files($this_file)
{
$query = $_POST['query'];
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) {
echo("Could not check $this_file");
}
else {
if (stristr($content, $str_to_find)) {
echo("$this_file -> contains $str_to_find");
}
}
unset($content);
}
If the query is not empty the find_files function is simply executed with no instructions of doing something if it returns false, hence you need to evaluate the result of calling find_files. For example you could do:
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
elseif (!find_files('.'))
{
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
with the condition that you update you find_files function to return false for all cases that fail.
or you could update the find_files function to return a string in case of errors and a string empty for succesful execution
if ((isset($query)) && (empty($query))) {
echo "<p style=\"color:darkgray; font-family:arial\">Your search produced no results</p>";
}
else
{
$result = find_files('.');
if (!empty($result))
{
echo "<p style=\"color:darkgray; font-family:arial\">".$result."</p>";
}
}
A couple of notes regarding your code that will improve the readability and code quality:
proper indentation will save a lot of time spent in maintenance;
when using if else imbrications ALWAYS use curly braces even if it is only one instructions. Improves readability and avoids errors.
when accessing a variable declared outside a function (in procedural code) use global keyword. For example for accessing the query variable inside the check_files function use global $query; instead of retrieving the variable again from the post.
use $_REQUEST instead of $_POST or $_GET unless there is a special reason for doing otherwise. Unifies code, makes for more readable code and changing from GET to POST or vice-versa can be done without changing code.
You may make your find_files function to return a boolean value: true if at least one matching file was found, false otherwise. Then update your if condition:
if ((isset($query)) && (empty($query)) && !find_files('.')) {
echo "<p style=\"color:darkgray...";
}
Because && is lazily evaluated, find_files will be called only if $query isn't empty.

Need help checking if else statement for { }

Somewhere along the line I'm adding or leaving out a { } but I just can't figure out where
<?php
if (file_exists('config.php')) {
require_once('config.php');
{
if ( $EDITED_CONFIG == false )
{
header("Location: welcome.php");
}
}
}
else (file_exists('default-config-new.php')) {
require_once('default-config-new.php');
{
if ( $EDITED_CONFIG == false )
{
header("Location: welcome.php");
}
}
}
?>
If file exists require it and if edited = false redirect, if true end script.
else
If file exists require it and if edited = false redirect, if true end script.
So if the first file doesn't exist it mustn't require it or look for edited, it must skip to the second file and if that exists it must checked edited and then if is false then redirect. If the first file is true it must end script and load page. So it mustn't check second file if first file is true.
Also is this the lightest way to do this?
Thanks
If you indent your code properly, your error will become evident.
A few links that may be useful:
Wikipedia: Indent style
How to indent code
PHP Coding standard: Indentation
You're not closing your if statements: Should be something like:
<?php
if (file_exists('config.php')) {
require_once('config.php');
if ($EDITED_CONFIG == false) {
header("Location: welcome.php");
}
}
else{
require_once('default-config-new.php');
if ($EDITED_CONFIG == false) {
header("Location: welcome.php");
}
}
?>
Edited. Also, you need to close brackets around all code to be executed for that statement, before you can use another elseif or else statement:
if ($x == 1) {
echo "X is 1!";
}
else if ($x == 0) {
echo "X is 0!";
}
else {
echo "Not 1 or 0!";
}
You are missing the { after the else to enclose what you want inside the "else" block i believe
You need to write
else if (conditions...)
You have got
else (conditions...)

Categories