Loop through array values - php

I have a small problem:
I need to repeat this
do {
$QUERY = "/member?id=".$counter."&action=refresh";
$URL = $HTTP.$HTTPUSER.":".$HTTPPASS."#".$HTTPSERVER.":".$HTTPPORT.$QUERY;
$xml = file_get_contents($URL);
$data = new SimpleXMLElement($xml);
$test_ip = (string)$data->c1;
$dnsip = explode('<br>', $test_ip);
$ext_ip = strip_tags($dnsip[1]);
if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {
$dns = strip_tags($dnsip[0]);
echo "$dns $ext_ip <br>";
}
$counter +=1;
} while (!empty($data));
as many times as there are values inside an array, so i tried to add this
$ports = array('2001','2002','2003');
foreach ($ports as $HTTPPORT) {
echo "$HTTPPORT<br>";
$counter = 1;
do {
$QUERY = "/member?id=".$counter."&action=refresh";
$URL = $HTTP.$HTTPUSER.":".$HTTPPASS."#".$HTTPSERVER.":".$HTTPPORT.$QUERY;
$xml = file_get_contents($URL);
$data = new SimpleXMLElement($xml);
$test_ip = (string)$data->c1;
$dnsip = explode('<br>', $test_ip);
$ext_ip = strip_tags($dnsip[1]);
if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {
$dns = strip_tags($dnsip[0]);
echo "$dns $ext_ip <br>";
}
$counter +=1;
} while (!empty($data)); }
The problem is that it executes the script with only first port number (2001), and i can't discover why.
Any Ideas?

You could be getting an exception inside your 'do .. while' loop that is causing bother.
I have added a 'try .. catch' block and some 'echo' statements to ensure it always loops round all the 'ports' now. Changed 'catch' to mark $data as empty then continue.
here is tested code:
<?php
$ports = array('2001','2002','2003');
$counter = 0; // total count of documents
foreach($ports as $HTTPPORT) {
echo $HTTPPORT, ' start of process port loop<br/>';
try { // catch any error -- report it and loop round again
do {
$QUERY = "/member?id=".$counter."&action=refresh";
$URL = ''; // $HTTP.$HTTPUSER.":".$HTTPPASS."#".$HTTPSERVER.":".$HTTPPORT.$QUERY;
try {
$xml = file_get_contents($URL);
$data = new SimpleXMLElement($xml);
}
catch (Exception $e) { // ignore any errors
echo 'SimpleXMLElement : oops :', $e->getMessage(), '<br />';
$data = ''; // mark as empty
}
if (!empty($data)) { // process data
$test_ip = (string)$data->c1;
$dnsip = explode('<br>', $test_ip);
$ext_ip = strip_tags($dnsip[1]);
if ($ext_ip != "127.0.0.1" && $ext_ip != "localhost") {
$dns = strip_tags($dnsip[0]);
echo "$dns $ext_ip <br>";
}
}
$counter +=1;
} while (!empty($data));
} // end of try to get and process a document...
catch (Exception $e) { // catch all errors for now
echo 'Processing List of Ports: oops! :', $e->getMessage(), '<br />';
}
} // end of foreach port

Related

How to correctly write a foreach for $clientList in TS3AntiVPN application?

I download a TS3AntiVPN but it shoes an error. I use a Linux Server running Debian 9 Plesk installed.
PHP Warning: Invalid argument supplied for foreach() in
/var/www/vhosts/suspectgaming.de/tsweb.suspectgaming.de/antivpn/bot.php
on line 29
How do I solve this problem?
<?php
require("ts3admin.class.php");
$ignore_groups = array('1',); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if(!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while(true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
foreach($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups'] );
if(is_array($ignore_groups)){
foreach($ignore_groups as $ig){
if(in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
}else{
if(in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip='.$val['connection_client_ip'].'');
$file = json_decode($file, true);
if($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
}
?>
You might be missing data in your first array. You may add an if statement to check if there is data in your $clientList['data'] var:
if (is_array($clientList['data'])) {
}
Or you might also check if sizeof(); of your array is larger than a number, you may desire.
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
}
Code
require "ts3admin.class.php";
$ignore_groups = array('1'); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if (!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while (true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
foreach ($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups']);
if (is_array($ignore_groups)) {
foreach ($ignore_groups as $ig) {
if (in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
} else {
if (in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip=' . $val['connection_client_ip'] . '');
$file = json_decode($file, true);
if ($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
} else {
echo "There might be no data in Client List";
}
}

PHP if statment on array length not working

here is my code :
elseif (is_dir($dir)) {
$scanning = scandir($dir);
$okdir;
// $response["scan"] = $scanning;
foreach ($scanning as $key=> $value) {
$splitscan = explode("_",$scanning[$key]);
if ($splitscan[0] == $searchvalue ){
$okdir[] = $scanning[$key];
if (count($okdir)>1){
$response["okdir"] = $okdir;
$response["result"] = "more";
}
else {
$okdir = $okdir[0];
}
}
}
when the function goes on the else statment i get no problem, but when the conditions need to verify the if statment if(count($okdir>1)) i get PHP internal error. What does it mean? That the if statment is never true? What i'm doing wrong?
Thank you for any help provided
Here is the error log answer:
PHP Fatal error: Uncaught Error: [] operator not supported for strings
Here is the whole function:
private function pdf(){
$response;
$dir = "../Pdf/";
$searchvalue = $this->params["utentericercato"];
if (!isset($_COOKIE["idutente"])){
$response["result"] = "nosession";
$utente->setUteLogged(false);
}
// Open a known directory, and proceed to read its contents
elseif (is_dir($dir)) {
$scanning = scandir($dir);
$okdir = array();
// $response["scan"] = $scanning;
foreach ($scanning as $key=> $value) {
$splitscan = explode("_",$scanning[$key]);
if ($splitscan[0] == $searchvalue ){
$okdir[] = $scanning[$key];
if (count($okdir)>1){
$response["okdir"] = $okdir;
$response["result"] = "more";
}
else {
$okdir = $okdir[0];
}
}
}
if (empty($okdir)){
$response["result"]= "noutente";
}
else {
$newdir = $dir.$okdir;
$nomeutente = preg_replace("/[^a-zA-Z\s]/", "", $okdir);
$response["dir"] = $newdir;
$response["nomeutente"] = $nomeutente;
if (is_dir($newdir)){
$dh = array_diff(scandir($newdir),array(".",".."));
$arr = is_array($dh);
$x = 0;
while($x < sizeof($dh)){
foreach($dh as $key=>$value){
if ($key[$value] != "." && $key[$value] != ".."){
$response["files"][$key] = $value;
$response["result"] = "success";
}
$x = $x + 1;
}
}
}
}
}
else {
$response["result"] = "nodirectory";
}
Responder::giveResponse($response);
}
Your first iteration sets the variable as a string. Any subsequent iteration will attempt to "push" data into the string like it is an array.
Demo: https://3v4l.org/GOdgs
$scanning[0] = "b";
$okdir = "a"; // just add [] after $okdir
$okdir[] = $scanning[0];
var_export($okdir);
I suppose I recommend that you just remove:
else {
$okdir = $okdir[0];
}
It only causes trouble.
And...
if (count($okdir)>1){
$response["okdir"] = $okdir;
$response["result"] = "more";
}
Should be positioned after your loop so that it is executed only once.
If this were my project, I'd be doing something like chdir($dir); then glob("{$searchvalue}_*") <-- grab and filter in the same step.
I did not test it yet, however, this much cleaner approach should work. At least it should give you an idea how to do the task in a structured way.
private function pdf()
{
$response = [];
$dir = "../Pdf/";
$searchvalue = $this->params["utentericercato"];
if (is_dir($dir))
{
chdir($dir);
$okdir = glob("{$searchvalue}_*", GLOB_ONLYDIR);
switch (count($okdir))
{
case 0:
$response['result'] = 'noutente';
break;
case 1:
$nomeutente = preg_replace("/[^a-z\s]/i", "", $okdir[0]);
$response["dir"] = $dir . $okdir[0];
$response["nomeutente"] = $nomeutente;
chdir($okdir[0]);
$response["files"] = glob('*');
if(!empty($response["files"]))
{
$response["result"] = "success";
}
break;
default:
$response["okdir"] = $okdir; // or $okdir[0] if you do not want an array but the first item
$response["result"] = "more";
}
}
else
{
$response["result"] = "nodirectory";
}
Responder::giveResponse($response);
}
Here is the error log answer: PHP Fatal error: Uncaught Error: [] operator not supported for strings
To fix the error above, define $okdir as array.
Line no 3 should be changed from $okdir; to $okdir = array();
I've found the solution, old code not working:
elseif (is_dir($dir)) {
$scanning = scandir($dir);
$okdir = array();
// $response["scan"] = $scanning;
foreach ($scanning as $key=> $value) {
$splitscan = explode("_",$scanning[$key]);
if ($splitscan[0] == $searchvalue ){
$okdir[] = $scanning[$key];
if (count($okdir)>1){
$response["okdir"] = $okdir;
$response["result"] = "more";
}
else {
$okdir = $okdir[0];
}
}
}
if (empty($okdir)){
$response["result"]= "noutente";
}
new working code :
elseif (is_dir($dir)) {
$scanning = scandir($dir);
$okdir = array();
// $response["scan"] = $scanning;
foreach ($scanning as $key=> $value) {
$splitscan = explode("_",$scanning[$key]);
if ($splitscan[0] == $searchvalue ){
$okdir[] = $scanning[$key];
}
}
if (count($okdir)>1){
$response["okdir"] = $okdir;
$response["result"] = "more";
Responder::giveResponse($response);
exit;
}
if (empty($okdir)){
$response["result"]= "noutente";
}

Output result not correct

I am using text area to search the number that user can key in 10 mobile numbers maximum on 1 time. When I try to test with 2 numbers, if I key in 1st number which is have its profile in our db the output is correct. But if I key in 1st value with number that not have its profile in our db the output become incorrect and it does not looping the 2nd value. I got an error illegal offset string. Can anyone help me on this case? Thank you in advance
if (isset($_POST['search']) && $_POST['search'] == 'Search') {
$police = new police();
$user = $_SESSION['username'];
$searchuser = $_POST['searchby'];
$_SESSION['searchby'] = $_POST['searchby'];
$param = explode("\n", trim($_POST['info']));
for ($i = 0; $i < count($param); $i++) {
$param[$i] = str_replace(array("\r", "\n", "\r\n"), "", $param[$i]);
}
try {
if ($_POST['searchby'] == 'select') {
throw new Exception("Please select your identity search");
}
} catch (Exception $ex) {
$errmsg = $ex->getMessage();
$tbs->VarRef['searchFail'] = 'true';
$tbs->VarRef['searchFailMsg'] = $errmsg;
$user = $_SESSION['username'];
}
if (isset($param) && $_POST['searchby'] == 'msisdn') {
$ptrnmsisdn = "/^(\+?6?01)[0|1|2|3|4|6|7|8|9]\-*[0-9]{7,8}$/";
for ($i = 0; $i < count($param); $i++) {
$param[$i] = preg_replace("/^(6)(\d+)/", "$2", $param[$i]);
}
try {
if (empty($param)) {
throw new Exception("Please enter your search");
} else {
foreach ($param as $item) {
if (!preg_match($ptrnmsisdn, $item)) {
throw new Exception("Please enter correct mobile number");
}
}
}
$tbs->LoadTemplate('msisdnprofile1.html');
//$_SESSION["msisdnlist"] = $police->getSubsInfo($param[0],$searchmsisdn);
try {
$searchResult = array();
foreach ($param as $paramValue) {
$search = "NRIC";
$msisdnList = $police->getSubsInfo($paramValue, $search);
$searchResult[$paramValue] = $msisdnList;
}
} catch (Exception $ex) {
$searchResult[$paramValue] = $ex->getMessage();
}
$listMsisdn = "";
$arryTemp = array();
foreach ($searchResult as $searchValue => $subValue) {
array_push($arryTemp, $searchValue);
$listMsisdn .= '<div>
<h3>' . $searchValue . '</h3>
<table>
<thead>
<tr>
<th width="300">Mobile Number</th>
<th width="300">Status</th>
<th width="300">View</th>
</tr>
</thead>
<tbody>
';
$listMsisdn .= '<tr>
' . $subValue['msisdn'] . '
' . $subValue['Reg_Status'] . '
';
$listMsisdn .= ' </tbody>
</table>
';
}
$_SESSION['$searchValue'] = $searchValue;
$_SESSION['$listMsisdn'] = $listMsisdn;
$_SESSION['$listOfSearchValue'] = $arryTemp;
$tbs->Show();
die();
} catch (Exception $ex) {
$user = $_SESSION['username'];
$errmsg = $ex->getMessage();
$tbs->VarRef['searchFail'] = 'true';
$tbs->VarRef['searchFailMsg'] = $errmsg;
}
}
}
You have your try/catch around the whole foreach loop. So if there's an error in any of the parameters, the loop will stop at that point. You need to put it just around the call to getSubsInfo() so you can continue the loop with the rest of the $param array.
$searchResult = array();
$search = "NRIC";
foreach ($param as $paramValue) {
try {
$msisdnList = $police->getSubsInfo($paramValue, $search);
$searchResult[$paramValue] = $msisdnList;
} catch (Exception $ex) {
$searchResult[$paramValue] = $ex->getMessage();
}
}

Undefined variable: error in adding field into db

I'm getting error:Undefined variable: error
in my code:
public function add(){
$this->polls_model->rules = Pf::event()->trigger("filter","polls-adding-validation-rule",$this->polls_model->rules);
$template = null;
$template = Pf::event()->trigger("filter","polls-add-template",$template);
if ($this->request->is_post()){
$data = array();
$data["polls_question"] = $this->post->{"polls_question"};
$data["polls_pubdate"] = str_to_mysqldate($this->post->{"polls_pubdate"},$this->polls_model->elements_value["polls_pubdate"],"Y-m-d H:i:s");
$data["polls_unpubdate"] = str_to_mysqldate($this->post->{"polls_unpubdate"},$this->polls_model->elements_value["polls_unpubdate"],"Y-m-d H:i:s");
if (is_array($this->post->{"polls_status"})){
$data["polls_status"] = implode(",",$this->post->{"polls_status"});
}else{
$data["polls_status"] = $this->post->{"polls_status"};
}
$port_answer = isset($this->post->{"answer"}) ? $this->post->{"answer"} : array();
$data = Pf::event()->trigger("filter","polls-post-data",$data);
$data = Pf::event()->trigger("filter","polls-adding-post-data",$data);
$var = array();
$pollq_multiple_yes = intval($this->post->{'pollq_multiple_yes'});
$data['polls_multiple'] = 0;
if ($pollq_multiple_yes == 1) {
if(intval($this->post->{'pollq_multiple'}) > count($port_answer)){
$data['polls_multiple'] = 1;
}else{
$data['polls_multiple'] = intval($this->post->{'pollq_multiple'});
}
} else {
$data['polls_multiple'] = 1;
}
//debug($data);
Pf::database()->query('START TRANSACTION');
$inserted = $this->polls_model->insert($data);
if($inserted === false){
Pf::database()->query('ROLLBACK');
}else{
$new_id = $this->polls_model->insert_id();
$insert_meta = true;
if(count($port_answer) > 0){
$custom = array();
$int = count($port_answer);
for ($i = 0; $i < $int ; $i++) {
if(!empty($port_answer[$i])){
$custom = array(
'pollsa_qid' => $new_id,
'pollsa_answers' => e($port_answer[$i]),
);
}
$insert_meta = $this->answers_model->insert($custom);
}
if($insert_meta === false){
Pf::database()->query('ROLLBACK');
}else{
Pf::database()->query('COMMIT');
}
}
Pf::database()->query('COMMIT');
}
$errors = Pf::validator()->get_readable_errors(false);
foreach ($errors as $key => $value) {
$error[$key][0] = $errors[$key][0];
}
$this->view->errors = $error; // error here!
$var['content'] = $this->view->fetch($template);
if (count($error) > 0){// and here!!!
$var['error'] = 1;
}else{
Pf::event()->trigger("action","polls-add-successfully",$this->polls_model->insert_id(),$data);
$var['error'] = 0;
$var['url'] = admin_url($this->action.'=index&ajax=&id=&token=');
}
echo json_encode($var);
}else{
$this->view->render($template);
}
}
I edited code, added function code.
This is my add function, if I want add poll with answers.
It gives me this error to my log.
I found this tutorial Undefined Variable error in View
I've googled it but didnt find anything special what helps me out.
Initiate the variable as an array.
because if the $error is empty the compiler will see it as an array.
if not it will get an error.
$error = [];
$errors = Pf::validator()->get_readable_errors(false);
foreach ($errors as $key => $value) {
// $error[$key][0] = $errors[$key][0];
// the right way is below
// i actually dont know what you want to do but this is the right way
// but providing [0] will make it some how constant.
$error[$key] = $errors[$key]
}
$this->view->errors = $error; // error showing here!
$var['content'] = $this->view->fetch($template);
if (count($error) > 0){ // and here???
$var['error'] = 1;
}else{
Pf::event()->trigger("action","polls-add-successfully",$this->polls_model->insert_id(),$data);
$var['error'] = 0;
$var['url'] = admin_url($this->action.'=index&ajax=&id=&token=');
}

Pinterest style / PHP Image Scraper Crashing Server

I must have a memory leak or something that is just eating memory on my server somewhere in this class. For example if I file_get_contents(http://www.theknot.com) it will not be able to connect to the server tho its not down, or mysql closes the connection, or in extreme situations completed knock out the server for a mount of time that we can not even get a ping. I know its somewhere within the preg_match_all if block, but I dont know what would get run away to what I can only assume is a lot of processing on the regex match due to whatever is within the content that is fetched from the remote site. Any ideas?
<?php
class Utils_Linkpreview extends Zend_Db_table
{
public function getPreviews($url) {
$link = $url;
$width = 200;
$height = 200;
$regex = '/<img[^\/]+src="([^"]+\.(jpe?g|gif|png))/';
/// $regex = '/<img[^\/]+src="([^"]+)/';
$thumbs = false;
try {
$data = file_get_contents($link);
} catch (Exception $e) {
print "Caught exception when attempting to find images: ". $e->getMessage(). "\n";
}
if (($data) && preg_match_all($regex, $data, $m, PREG_PATTERN_ORDER)) {
if (isset($m[1]) && is_array($m[1])) {
$thumbs = array();
foreach (array_unique($m[1]) as $url) {
if (
($url = $this->rel2abs($url, $link)) &&
($i = #getimagesize($url)) &&
$i[0] >= ($width-10) &&
$i[1] >= ($height-10)
) {
$thumbs[] = $url;
}
}
}
}
return $thumbs;
}
private function rel2abs($url, $host) {
if (substr($url, 0, 4) == 'http') {
return $url;
} else {
$hparts = explode('/', $host);
if ($url[0] == '/') {
return implode('/', array_slice($hparts, 0, 3)) . $url;
} else if ($url[0] != '.') {
array_pop($hparts);
return implode('/', $hparts) . '/' . $url;
}
}
}
}
?>
EDIT - Amal Murali's comment pointed me in a better direction using PHP's DomDocument. Thanks bud!
Here is the result:
public function getPreviews($url) {
$link = $url;
$thumbs = false;
try {
$html = file_get_contents($link);
} catch (Exception $e) {
print "Caught exception when attempting to find images: ". $e->getMessage(). "\n";
}
$dom = new DOMDocument();
#$dom->loadHTML($html);
$x = new DOMXPath($dom);
foreach($x->query("//img[#width > 200 or substring-before(#width, 'px') > 200 or #height > 200 or substring-before(#height, 'px') > 200]") as $node)
{
$url = $node->getAttribute("src");
$thumbs[] = $this->rel2abs($url, $link);
}
return $thumbs;
}
EDIT - Amal Murali's comment pointed me in a better direction using PHP's DomDocument. Thanks bud!
Here is the result:
public function getPreviews($url) {
$link = $url;
$thumbs = false;
try {
$html = file_get_contents($link);
} catch (Exception $e) {
print "Caught exception when attempting to find images: ". $e->getMessage(). "\n";
}
$dom = new DOMDocument();
#$dom->loadHTML($html);
$x = new DOMXPath($dom);
foreach($x->query("//img[#width > 200 or substring-before(#width, 'px') > 200 or #height > 200 or substring-before(#height, 'px') > 200]") as $node)
{
$url = $node->getAttribute("src");
$thumbs[] = $this->rel2abs($url, $link);
}
return $thumbs;
}

Categories