My PHP script is always connection (IRC Bot) but say the bot runs into an error and gets disconnected I want it to reconnect to the server.
Right now the bot is running local so I’m able to restart the bot using a bat file but if I host it somewhere how would I initiate a reconnection?
For example my code now is:
<?php
set_time_limit(0);
include 'config.php';
fputs($socket,"USER TFBot TFBot.PugBot TFBot :The TitanFall.Pug Bot\n");
fputs($socket,"NICK $bnick\n");
$commands = array (
"${cmdsym}commands",
"${cmdsym}add",
"${cmdsym}join",
"${cmdsym}last",
"${cmdsym}coms",
"${cmdsym}voip",
"${cmdsym}promote",
"${cmdsym}need",
"${cmdsym}list",
"${cmdsym}pick",
"${cmdsym}remove",
);
while (1) {
while($data=fgets($socket,128)) {
$get = explode(' ', $data);
if (stripos( $get[1], ':Closing' ) !== false) {
echo "Reconnecting in 10 seconds\n";
sleep(10);
passthru("Startbot.bat");
}
if (stripos( $get[1], 'NICK' ) !== false) {
$nick = explode(':',$get[0]);
$nick = explode('!',$nick[1]);
$nick = $nick[0]; //User who entered the command
$nuser = $nick;
$wnuser = preg_replace('/^\\:/','', $get[2]);
$tnuser = rtrim($wnuser);
if (chnickchange("tready.txt",$nuser)) {
fputs($socket,"CNOTICE $tnuser $jchan : Your name was updated from: $nuser to: $tnuser on the PUG List. - $chan.\n");
nickchange("tready.txt",$nuser,$tnuser);
nickchange("pready.txt",$nuser,$tnuser);
nickchange("sready.txt",$nuser,$tnuser);
nickchange("militia.txt",$nuser,$tnuser);
nickchange("imc.txt",$nuser,$tnuser);
nickchange("captains.txt",$nuser,$tnuser);
nickchange("pick.txt",$nuser,$tnuser);
}
}
if (stripos( $get[1], 'QUIT' ) !== false) {
$nick = explode(':',$get[0]);
$nick = explode('!',$nick[1]);
$nick = $nick[0]; //User who entered the command
$partuser = $nick;
$line = file("tready.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
if (array_search($partuser, $line) !== FALSE) {
fputs($socket,"PRIVMSG $chan : $nick was removed from the PUG List. - QUIT.\n");
$DELETE = $partuser;
$datap = file("tready.txt");
$out = array();
foreach($datap as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("tready.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
$datap = file("sready.txt");
$out = array();
foreach($datap as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("sready.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
sleep(1);
$listnp = file("tready.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$nplayers = $pugmax - count($listnp);
if ($nplayers !== 0) {
fputs($socket,"PRIVMSG $chan : ${afcolor}(${scolor}$nplayers needed to begin${afcolor})\n");
}
}
}
if ($get[0] == "PING") {
fputs ($socket, "PONG ".$get[1]."\n");
}
if (stripos( $data, 'Nickname is already in use.' ) !== false) {
$bnick = $bnick . "|2";
fputs($socket,"NICK $bnick\n");
}
if (stripos( $data, 'End of /MOTD command.' ) !== false) {
fputs($socket,"PRIVMSG Q#CServe.quakenet.org : AUTH $authname $authpass\n");
sleep(1);
fputs($socket,"MODE $bnick +x\n");
//Enter the channel you want to use your bot on.
sleep(2);
fputs($socket,"JOIN $jchan\n");
}
if (substr_count($get[2],"#")) {
$nick = explode(':',$get[0]);
$nick = explode('!',$nick[1]);
$nick = $nick[0]; //User who entered the command
$nhost = explode('!', $get[0]); //User Hostname for private commands
$nhost = $nhost[1];
$chan = $get[2]; //the channel the bot is in
$num = 3; //If you observe the array format, actually text starts from 3rd index.
if ($num == 3) {
$split = explode(':',$get[3],2);
$text = rtrim($split[1]); //trimming is important. never forget.
// Bot Public Commands
/* if (stripos( $get[1], 'PART' ) !== false) {
$partuser = $nick;
removeuser($partuser,"tready.txt","0");
removeuser($partuser,"pready.txt","1");
removeuser($partuser,"militia.txt","1");
removeuser($partuser,"imc.txt","1");
removeuser($partuser,"captains.txt","2");
removeuser($partuser,"pick.txt","2");
} */
if (stripos( $get[1], 'PART' ) !== false) {
$partuser = $nick;
$line = file("tready.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
if (array_search($partuser, $line) !== FALSE) {
fputs($socket,"NOTICE $partuser : You were removed from the PUG List. - $chan.\n");
fputs($socket,"PRIVMSG $chan : ${afcolor}$partuser ${scolor}was removed from the pug list${afcolor}. - ${scolor}Reason${afcolor}: PART.\n");
$DELETE = $partuser;
$datap = file("tready.txt");
$out = array();
foreach($datap as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("tready.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
$datap = file("sready.txt");
$out = array();
foreach($datap as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("sready.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
sleep(1);
$listnp = file("tready.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$nplayers = $pugmax - count($listnp);
if ($nplayers !== 0) {
fputs($socket,"PRIVMSG $chan : ${afcolor}(${scolor}$nplayers needed to begin${afcolor})\n");
}
}
}
Seems like you have passthru enabled.
A simple script would be:
<?PHP
passthru('c:/path/to/file/startbot.bat');
Which you're already doing. This will call the batch file, and restart the script.
Or,
<?PHP
passthru('c:/path/to/php/php c:/path/to/script/script.php');
Related
I have a code like this.
but the problem is why can't output ... please give suggestions, what is wrong with this code
<?php
function randLine($fileName) {
$fh = #fopen($fileName, "r");
while (true) {
$line = fgets($fh);
if ($line == null) {
break;
}
}
fclose($fh);
return $line;
}
$tes = randLine("list.txt");
$tes = str_replace(array("\n", "\r"), "", $tes);
echo $tes;
I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !
How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);
$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);
$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.
I've got this code that logs to a .txt file in a user folder. I need it to refresh in real time or 1 or 5 seconds.
The code basically logs a visitor that viewing the page, so it will say: Viewers: 1 and when the visitor exit the page it will go back to Viewers: 0
The script is working but I want it to refresh.
Any ideas?
Here the PHP Code:
require_once 'dbconfig.php';
if ($_GET[user] != ""){
$check_query = mysql_query("SELECT * FROM profiles WHERE username='$lowerusername'");
while ($display = mysql_fetch_array($check_query)) {
$username = $display['username'];
}}
$dataFile = "profile/$username/visitors.txt";
$sessionTime = 1; //this is the time in **minutes** to consider someone online before removing them from our file
//Please do not edit bellow this line
error_reporting(E_ERROR | E_PARSE);
if(!file_exists($dataFile)) {
$fp = fopen($dataFile, "w+");
fclose($fp);
}
$ip = $_SERVER['REMOTE_ADDR'];
$users = array();
$onusers = array();
//getting
$fp = fopen($dataFile, "r");
flock($fp, LOCK_SH);
while(!feof($fp)) {
$users[] = rtrim(fgets($fp, 32));
}
flock($fp, LOCK_UN);
fclose($fp);
//cleaning
$x = 0;
$alreadyIn = FALSE;
foreach($users as $key => $data) {
list( , $lastvisit) = explode("|", $data);
if(time() - $lastvisit >= $sessionTime * 10) {
$users[$x] = "";
} else {
if(strpos($data, $ip) !== FALSE) {
$alreadyIn = TRUE;
$users[$x] = "$ip|" . time(); //updating
}
}
$x++;
}
if($alreadyIn == FALSE) {
$users[] = "$ip|" . time();
}
//writing
$fp = fopen($dataFile, "w+");
flock($fp, LOCK_EX);
$i = 0;
foreach($users as $single) {
if($single != "") {
fwrite($fp, $single . "\r\n");
$i++;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if($uo_keepquiet != TRUE) {
echo '<strong>Viewers:</strong> ' . $i . '';
}
I have a text file with lots of text, and I want to display a part of it on the screen with PHP.
At a certain point there's string like ITEM DESCRIPTION:
What I want to get all content from this string (just after it) to the end of the file.
This is my code so far:
$file = "file.txt";
$f = fopen($file, "r");
while ($line = fgets($f, 1000))
echo $line;
:)
How about you use strstr() and file_get_contents() ?
$contents = strstr(file_get_contents('file.txt'), 'ITEM DESCRIPTION:');
# or if you don't want that string itself included:
$s = "ITEM DESCRIPTION:"; # think of newlines as well "\n", "\r\n", .. or just use trim()
$contents = substr(strstr(file_get_contents('file.txt'), $s), strlen($s));
$file = "file.txt";
$f = fopen($file, 'rb');
$found = false;
while ($line = fgets($f, 1000)) {
if ($found) {
echo $line;
continue;
}
if (strpos($line, "ITEM DESCRIPTION:") !== FALSE) {
$found = true;
}
}
What about
$file = "file.txt";
$f = fopen($file, "r");
$start = false;
while ($line = fgets($f, 1000)) {
if ($start) echo $line;
if ($line == 'ITEM DESCRIPTION') $start = true;
}
?
I'm guessing it's fgets, but I can't find the specific syntax. I'm trying to read out (in a string I'm thinking is easier) the last line added to a log file.
The simplest naive solution is simply:
$file = "/path/to/file";
$data = file($file);
$line = $data[count($data)-1];
Though, this WILL load the whole file into memory. Possibly a problem (or not). A better solution is this:
$file = escapeshellarg($file); // for the security concious (should be everyone!)
$line = `tail -n 1 $file`;
This looks like it is what you are looking for:
tekkie.flashbit.net: Tail functionality in PHP
It implements a function that uses fseek() with a negative index to roll up the file from the end. You can define how many lines you want to be returned.
The code also is available as a Gist on GitHub:
// full path to text file
define("TEXT_FILE", "/home/www/default-error.log");
// number of lines to read from the end of file
define("LINES_COUNT", 10);
function read_file($file, $lines) {
//global $fsize;
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
break;
}
$t = fgetc($handle);
$pos --;
}
$linecounter --;
if ($beginning) {
rewind($handle);
}
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
}
fclose ($handle);
return array_reverse($text);
}
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
echo "<strong>".TEXT_FILE."</strong>\n\n";
echo "File size is {$fsize} megabytes\n\n";
echo "Last ".LINES_COUNT." lines of the file:\n\n";
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
echo $line;
}
define('YOUR_EOL', "\n");
$fp = fopen('yourfile.txt', 'r');
$pos = -1; $line = ''; $c = '';
do {
$line = $c . $line;
fseek($fp, $pos--, SEEK_END);
$c = fgetc($fp);
} while ($c != YOUR_EOL);
echo $line;
fclose($fp);
This is better, since it does not load the complete file into memory...
Set YOUR_EOL to your correct line endings, if you use the same line endings as the default line endings of the OS where your script resides, you could use the constant PHP_EOL.
function seekLastLine($f) {
$pos = -2;
do {
fseek($f, $pos--, SEEK_END);
$ch = fgetc($f);
} while ($ch != "\n");
}
-2 because last char can be \n
You either have to read the file in line by line and save the last read line to get it.
Or if on unix/linux you might consider using the shell command tail
tail -n 1 filename
This one wont break for a 1 or 0 line file.
function readlastline($fileName)
{
$fp = #fopen($fileName, "r");
$begining = fseek($fp, 0);
$pos = -1;
$t = " ";
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
if(ftell($fp) == $begining){
break;
}
$t = fgetc($fp);
$pos = $pos - 1;
}
$t = fgets($fp);
fclose($fp);
return $t;
}
If you want to read a file line by line the file function reads the contents of a file, line by line and returns each line as an element of an array.
So you could do something simple like:
$lines = file('log.txt');
$lastLine = array_pop($lines);
...Why just read the last line?
function readLines($fp, $num) {
$line_count = 0; $line = ''; $pos = -1; $lines = array(); $c = '';
while($line_count < $num) {
$line = $c . $line;
fseek($fp, $pos--, SEEK_END);
$c = fgetc($fp);
if($c == "\n") { $line_count++; $lines[] = $line; $line = ''; $c = ''; }
}
return $lines;
}
$filename = "content.txt";
$fp = #fopen($filename, "r");
print_r(readLines($fp, 2));
fclose($fp);
#unique_stephen, your answer is flawed. PHP fseek returns 0 for success and -1 for failure. Storing the result in $begining (sic) and then later using it in a filter for ftell() isn't correct. If my reputation were higher I would have voted you down and left a comment. Here is a modified version of unique_stephen's function.
function readlastline($fileName)
{
$fp = #fopen($fileName, "r");
if (fseek($fp, 0) == -1)
exit('Cannot seek to beginning of the file');
$pos = -1;
$t = " ";
while ($t != "\n") {
if (fseek($fp, $pos, SEEK_END) == -1)
exit('Cannot seek to the end of the file');
if (ftell($fp) == 0) {
break;
}
$t = fgetc($fp);
$pos = $pos - 1;
}
$t = fgets($fp);
fclose($fp);
return $t;
}
NOTE: PHP's fseek cannot manage to seek to the end of files larger than PHP_MAX_INT which is 32bit signed even on 64bit binaries.
function readlastline($fileName)
{
$fp = #fopen($fileName, "r");
$begining = fseek($fp, 0);
$pos = -1;
$t = " ";
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
if(ftell($fp) == $begining){
break;
}
$t = fgetc($fp);
$pos = $pos - 1;
}
$t = fgets($fp);
fclose($fp);
return $t;
}