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.
Related
I'm trying to check does something exists in my database. Basicly I want to add device for user if it does not exists, and I'm trying to do it like so:
public static function checkDevice($userId, $tokenId){
$devices = UserDevices::where('user_id', $userId)->get();
$notExists = '';
foreach ($devices as $key => $d) {
if(!$d->ip_address === SecureAgent::getIP() && $d->mac_address === SecureAgent::getMAC() && $d->device === SecureAgent::getDevice() ){
$notExists = 'User device not found!';
}
}
}
So I need to check is does this IP, Mac and Device are already added in database, if any of them is not similar like any else I will need them to add in database like:
if($notExists === 'User device not found'){
self::addDevice() // I'm calling another function to do that job
}
Any suggestions?
I did it like so:
try {
UserDevices::where('user_id', $userId)->where('ip_address', SecureAgent::getIP())->where('mac_address', SecureAgent::getMac())->where('browser', SecureAgent::getSurfer())->firstOrFail();
} catch (\Exception $e) {
self::addDevice($userId, $tokenId);
}
I am trying to check whether a generated string is in my database table or not.
If there is no duplicate I want to return and save it.
If there is a duplicate I want to generate a new string and save it
currently this function does not return me the generated token:
public function checkForHashDuplicate($string)
{
$newToken = '';
$inquiries = DB::table('inquiries')->get();
foreach($inquiries as $inquiryKey => $inquiryValue)
{
while($inquiryValue->android_device_token == $string)
{
$newToken = generateAlphanumericString();
if($newToken != $inquiryValue->android_device_token)
{
return $newToken;
}
}
}
}
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
A simplified version of your code is:
public function checkForHashDuplicate($string)
{
do {
// generate token
$newToken = generateAlphanumericString();
// find token in a DB
$duplicate = DB::table('inquiries')
->where('android_device_token', '=', $newToken)->first();
// if token is FOUND `$duplicate` has truthy value
// and `do-while` keeps running
// else `$duplicate` is falsy and `do-while` breaks
} while ($duplicate);
return $newToken;
}
Instead of using:
$inquiries = DB::table('inquiries')->get();
and loop, use where like:
$inquiries = DB::table('inquiries')->where('android_device_token', '=', $string)->get();
if( count($inquiries ) == 1 )
{
// found
}
else
{
// Not found, generate new one
}
You can check like this:
public function checkDuplicate($string){
$count = DB::table('inquiries')->where('android_device_token',$string)->count();
if($count==0){
// $string exists
return generateAlphanumericString();
}else{
// $string doesn't exists
return $string;
}
}
Now, use this function to assign value of $string or new token as
$inquiry->android_device_token = $this->checkForHashDuplicate($hash);
Hope you understand.
I'd created an if statement "if ($user_roles == 3) " and this $user_roles has a value of "3" the condition is supposed to be true but the result is always false.
here is my code below:
public function ViewSponsorInfo($sponsor_id)
{
$id = $sponsor_id;
$user_id = User::where('id','=',$id)->get();
$user_roles = [];
foreach ($user_id as $id) {
array_push($user_roles, $id->role);
}/*
dd($user_roles);*/
if ($user_roles == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
$user_rolesis not 3 and can never be. it's an array.
its contents, however, can be three.
try:
if(in_array(3, $user_roles)) { ...}
for reference: in_array
$user_roles is an array. So your if statement is always false.
I think, try this one.
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role['role'] == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
or
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role->role == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
Please said something upon it after tried this one.
Judging from what you show your function ViewSponsorInfo() by its very name is only interested in detecting if this user has the sole role '3' in your db.
I mean the outcome is binary isn't it? Either they are a 3 or they are not, no need to go looping thru results.
$user_id = User::where('id','=',$id)->get();
if($user_id[0] !== 3 ) { //***
doSponsorLink();
}else{
doNonSponsorLink();
}
I'm not familiar with Laravel or the db layer your are using, so maybe that is even simply if($user_id).
untested, and here I am assuming user can only have 1 single role, and we do not seem to be making allowances for the user not existing in the db.
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}
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.