With this script, change the order of the lines in a text file, but I'd like to save the file as a new file. How can I do that?
<?php
$file = "menu2.txt";
$righe = file($file);
$numrighe = count($righe);
$portieri = array();
$difensori = array();
$aladestra = array();
$alasinistra = array();
$attaccante = array();
for($i=0; $i < $numrighe;$i++) {
$riga = $righe[$i];
list($giocatore, $ruolo) = preg_split("[>]", $riga);
if(strcmp($ruolo,"Portiere")) { array_push($portieri, $giocatore); }
else if(strcmp($ruolo,"Difensore")) { array_push($difensori, $giocatore); }
else if(strcmp($ruolo,"Ala destra")) { array_push($aladestra, $giocatore); }
else if(strcmp($ruolo,"Ala sinistra")) { array_push($alasinistra, $giocatore); }
else if(strcmp($ruolo,"Attaccante")) { array_push($attaccante, $giocatore); }
}
?>
Excuse me but probably because of google translator or because they are prevented, but you probably will not understand it, I did it:
<?php
$file = "menu2.txt";
$righe = file($file);
$numrighe = count($righe);
$portieri = array();
$difensori = array();
$aladestra = array();
$alasinistra = array();
$attaccante = array();
for($i=0; $i < $numrighe;$i++) {
$riga = $righe[$i];
list($giocatore, $ruolo) = preg_split("[>]", $riga);
if(strcmp($ruolo,"Portiere")) { array_push($portieri, $giocatore); }
else if(strcmp($ruolo,"Difensore")) { array_push($difensori, $giocatore); }
else if(strcmp($ruolo,"Ala destra")) { array_push($aladestra, $giocatore); }
else if(strcmp($ruolo,"Ala sinistra")) { array_push($alasinistra, $giocatore); }
else if(strcmp($ruolo,"Attaccante")) { array_push($attaccante, $giocatore); }
}
// open your new file
$newFile = fopen('newmenu2.txt', 'w');
// write to your file using $newFile file handler,
// with the imploded data you want to write into your file
fwrite($newFile, implode("\n", $data));
// close your file handler
fclose($newFile);
?>
Notice: Undefined variable: data on line 29
Warning: implode(): Invalid arguments passed on line 29
Related
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";
}
}
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";
}
Am trying to read multiple file and display the last line of each file but my code is not working very fine i don't know what am doing wrong.
<?php
if(isset($_GET['fid'], $_GET['timestamp']) && !empty($_GET['fid'])){
$lastmodif = isset( $_GET['timestamp']) ? $_GET['timestamp']: 0 ;
$fl_session = preg_replace("/[^0-9=]+/", "", $_GET['fid']);
if(strpos($fl_session, '==') !== false) {
$fl_session = explode('==', $fl_session);
foreach($fl_session as $fn){
$filename = dirname(__FILE__).'/logs/foo_'.$fn.'.txt';
$currentmodif = filemtime($filename);
while($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
if(file_exists($filename)){
$myfile = fopen($filename, "r") or die("Unable to load readme file!");
if($myfile){
$log = fread($myfile, filesize($filename));
fclose($myfile);
}
$log = explode("\n", trim($log));
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|', $log[$i]);
}
foreach ($log as $logline) {
$response['id'] = trim($logline['0']);
$response['type'] = trim($logline['3']);
}
}
$response[$fn]['timestamp'] = $currentmodif;
//$response['timestamp'] = $currentmodif;
//var_export($response);
echo json_encode($response);
}
}
}
In my GET['fid'] parameter it contain something like this 12345==09765==87765, so i will explode it and loop on every id to locate the file name foo_12345.txt, foo_09765.txt, foo_87765.txt. This current code returned something like this from one txt file and ignored other files.
{ "id":"58287469", "type":"client", "8942180223":{
"timestamp":1505409432 } } { "id":"53094615", "type":"client",
"8942180223":{ "timestamp":1505409432 }, "4582422934":{
"timestamp":1505409420 } }
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=');
}
I'm writing a script for download from FTP..
In the form I need to show files and folders..
With ftp_nlist, they come all togethers but I want to know who's who ..
I can't find an easy way to do this:
$contents = ftp_nlist($connection, $rep);
$dossiers =array();
$fichiers = array();
foreach($contents as $content){
//if folder
if (is_folder($content)) $dossiers[] = $content;
//si file
if(is_filex($content)) $fichiers[] = $content;
}
Of course is_file and is_dir don't work with distant files...
I've find something with ftp_rawlist and the size of each result..
like this:
if($result['size']== 0){ //is dir }
But in case of an empty file???
So what id the way to know what is a folder and what is a file??
Thanks!
I've had the same problem and this was my solution:
$conn = ftp_connect('my_ftp_host');
ftp_login($conn, 'my_user', 'my_password');
$path = '/';
// Get lists
$nlist = ftp_nlist($conn, $path);
$rawlist = ftp_rawlist($conn, $path);
$ftp_dirs = array();
for ($i = 0; $i < count($nlist) - 1; $i++)
{
if($rawlist[$i][0] == 'd')
{
$ftp_dirs[] = $nlist[$i];
}
}
I know the above code could be optimised and do just one FTP request instead of two but for my purposes this did the work.
For anyone looking for a cleaner solution, I've found a script to parse ftp_rawlist in this LINK:
Function
function parse_ftp_rawlist($List, $Win = FALSE)
{
$Output = array();
$i = 0;
if ($Win) {
foreach ($List as $Current) {
ereg('([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)', $Current, $Split);
if (is_array($Split)) {
if ($Split[3] < 70) {
$Split[3] += 2000;
}
else {
$Split[3] += 1900;
}
$Output[$i]['isdir'] = ($Split[7] == '');
$Output[$i]['size'] = $Split[7];
$Output[$i]['month'] = $Split[1];
$Output[$i]['day'] = $Split[2];
$Output[$i]['time/year'] = $Split[3];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : false;
}
else {
foreach ($List as $Current) {
$Split = preg_split('[ ]', $Current, 9, PREG_SPLIT_NO_EMPTY);
if ($Split[0] != 'total') {
$Output[$i]['isdir'] = ($Split[0] {0} === 'd');
$Output[$i]['perms'] = $Split[0];
$Output[$i]['number'] = $Split[1];
$Output[$i]['owner'] = $Split[2];
$Output[$i]['group'] = $Split[3];
$Output[$i]['size'] = $Split[4];
$Output[$i]['month'] = $Split[5];
$Output[$i]['day'] = $Split[6];
$Output[$i]['time/year'] = $Split[7];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : FALSE;
}
}
Usage
// connect to ftp server
$res_ftp_stream = ftp_connect('my_server_ip');
// login with username/password
$login_result = ftp_login($res_ftp_stream, 'my_user_name', 'my_password');
// get the file list for curent directory
$buff = ftp_rawlist($res_ftp_stream, '/');
// parse ftp_rawlist output
$result = parse_ftp_rawlist($buff, false);
// dump result
var_dump($result);
// close ftp connection
ftp_close($res_ftp_stream);