How to force/ close a socket connection in php - php

I have an issue with a project, I'm connecting to a remote server using telnet , i'm able to retrieve the console text and store it in a array and the to a database, all that fine, the problem is the telnet server keeps the session opened for 1:30 minutes so i get the output until 1:30 minutes, i want to retrieve the console text and force the php telnet connection but i don't know how, i tried everything and the sessions keeps opened.
Any help would be appreciated
<?php
$ip= $argv[1];
$da = fsockopen($ip, 23, $errno, $errstr, $timeout=3);
if (!$da){
echo "$errstr ($errno)<br />\n";
} else {
$output = "\data\r\n";
fwrite($da, $output);
while (!feof($da))
{
$str = fgets($da, 1024);
$a = explode(" ", $str);
$myJSON = json_encode($a,JSON_FORCE_OBJECT);
print var_dump($a);
print_r($a);
}
stream_set_timeout($da, 1);
fclose($da);
}
?>
Thanks

Related

PHP - Trying to make a chatbot for my game server

Alright, so first of all, i'm still kind of a newbie in PHP.
I'm trying to make a chatbot that responds to the keyword "shut up" from people that tell that to the bot in my game server, but I can't seem to find a way how...
Here's the bot's original code...
<?php
$choosechar = "#43CC#1#35#ItsJustABot#%";
$fh = fopen('badtimetim.txt','r');
$word_array = array(fgets($fh));
$word = rand(0,58);
$lines = file("badtimetim.txt");
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
// echo($line);
// Connect to the AO Server
if (!($fp = fsockopen("127.0.0.1", "27017", $errno, $errstr, 15))) {
die("Failed to connect. Doesn't seem like the server is up anyway?");
}
// Set timeout to 1 second
if (!stream_set_timeout($fp, 1)) die("Could not set timeout.");
// Fetch first line of response and echo it
echo fgets($fp);
// Say line and repeat
fwrite($fp, $choosechar);
fwrite($fp, "#4D90#chat#(a)dolannormal#Dolan#dolannormal#".$lines[array_rand($lines)]."#jud#1#1#0#0#0#0#35#0#1#%");
sleep(120);
// Stuff
echo fgets($fp);
}
fclose($fh);
What i'm exactly trying to achieve here is when the bot detects this (asterisks should be wildcards or something):
#4D90#chat#*#*#*#shut up#*#*#*#*#*#*#*#*#*#*#%
I want the bot to send this data to the server in response using fwrite:
#4D90#chat#(a)dolanangry#Dolan#dolanangry#no#jud#1#1#0#0#0#0#35#0#1#%
How do I do this? Any help is appreciated, thanks.
EDIT: Forgot to mention, i'm using a .bat file to run PHP and the PHP code and not a website.
EDIT2: Made question more specific
$input_string_with_shut_up=$_POST['chat_msg']
$output=str_replace('%shut up%','#4D90#chat#(a)dolanangry#Dolan#dolanangry#no#jud#1#1#0#0#0#0#35#0#1#%',$input_string_with_shut_up)
echo $output;
This might do

localhost (at custom port) returns empty data after POST request

I am trying to use a PHP to read data from the local server localhost, but it seems no data is returned from it. Here is my full script.
<?php
$address = "localhost";
echo "Attempting to open the socket at ".$address."...\n";
$fp = fsockopen($address, 49801, $errno, $errstr, 10);
echo "Error number is "; echo $errno; echo ".\n";
echo "Error string is ".$errstr.".\n";
echo "Attempt complete.\n";
if ($fp) {
print "Socket in now open.\n";
syslog(LOG_INFO, "socket.php: Reaching the specified address...");
print "Writing requests...\n"; //Hangs for about 1-2 minutes
fwrite($fp, "POST / HTTP/1.0\r\nUser-Agent: PHP XMLRPC 1.0\r\nHost: ".$address."Content-Type: text/xml\r\nContent-Length: ".strlen($payload)."\r\n\r\n");
$msg = "";
while($data = fread($fp, 32768)) {
$msg= $msg.$data;
}
if (strlen($msg) != 0) {
print "Final message: ***".$msg."***\n";
} else {
print "There is no data received from '".$address."'\n";
}
fclose($fp);
} else {
print "Error\n";
}
?>
Here is the output I am getting in the terminal:
Attempting to open the socket at localhost...
Error number is 0.
Error string is .
Attempt complete.
Socket in now open.
Writing requests...
There is no data received from 'localhost'
As mentioned in the script above, the second last line Writing requests... hangs for about 1 or 2 minutes, then an empty string is appended.
I think it is rather curious because this script works well on HTTP's port 80 or on SSH's port 22. I have restricted access to localhost:49801's configuration, and thus am not able to make any changes to the server's config.
I was however wondering if something was wrong with the server's config so that I don't have to tear out my hair for another day.
By the way, I am running PHP 5.4 on CentOS 7.
Edit
The '111' in "Content-Length: 111" is an arbitrary number that depends on the payload's string length.
Thanks your your help!
You got no reply from your server because he is waiting 111 bytes of data from you.
if you send the right amount of data to your server he will respond accordingly.
Below is working example where I change the Content-Length to 9
and then I send the 9 bites of data using fwrite:
<?php
$address = "localhost";
$payload = "Some data";
echo "Attempting to open the socket at ".$address."...\n";
$fp = fsockopen($address, 49801, $errno, $errstr, 10);
echo "Error number is "; echo $errno; echo ".\n";
echo "Error string is ".$errstr.".\n";
echo "Attempt complete.\n";
if ($fp) {
print "Socket in now open.\n";
syslog(LOG_INFO, "socket.php: Reaching the specified address...");
print "Writing requests...\n";
fwrite($fp, "POST / HTTP/1.0\r\nUser-Agent: PHP XMLRPC 1.0\r\nHost: ".$address.
"\r\nContent-Type: text/xml\r\nContent-Length: ". strlen($payload) ."\r\n\r\n");
//We send the data to the server
fwrite($fp, $payload);
$msg = "";
while($data = fread($fp, 32768)) {
$msg= $msg.$data;
}
if (strlen($msg) != 0) {
print "Final message: ***".$msg."***\n";
} else {
print "There is no data received from '".$address."'\n";
}
fclose($fp);
} else {
print "Error\n";
}
?>

Getting atomic time in PHP

I need to get the atomic time in php.
$fp = #fsockopen( "time-a.nist.gov", 37, $errno, $errstr, 10 );
if ( !$fp )
{
echo $errstr;
}
else
{
fputs($fp, "\n");
$time_info = fread($fp, 49);
fclose($fp);
}
/*** create the timestamp ***/
$atomic_time = (abs(hexdec('7fffffff') - hexdec(bin2hex($time_info)) - hexdec('7fffffff')) - 2208988800);
echo $errstr;`
But I only get connection timeouts with every server I try to connect.
I have tested different server, but all with the same error. Now I am wondering what is wrong with my code.
Is there a better way to ensure atomic time? My boss doesnt want us to use servertime.

PHP Printing to Remote Printer

I have a remote POS printer it uses the ESC/POS protocol.
I have a PHP app running that prints messages:
$texttoprint = "Samuel is a legend \nHello. \nTest123";
$texttoprint = stripslashes($texttoprint);
$fp = fsockopen("10.1.1.100", 9100, $errno, $errstr, 10);
if (!$fp) {
debug("$errstr ($errno)<br />\n");
} else {
fwrite($fp, "\033\100");
$out = $texttoprint . "\r\n";
fwrite($fp, $out);
fwrite($fp, "\012\012\012\012\012\012\012\012\012\033\151\010\004\001");
fclose($fp);
}
It works but only sometimes, if i run the code it works around 1 in 10 times but it is not hitting the error so I don't know why its only printing sometimes.
Using only one fwrite() fixed this issue.
Thank you #user113215.
If anyone knows why I would love to know.

Reading data from fsockopen using fgets/fread hangs

Here is the code that I am using:
if (!($fp = fsockopen('ssl://imap.gmail.com', '993', $errno, $errstr, 15)))
echo "Could not connect to host";
$server_response = fread($fp, 256);
echo $server_response;
fwrite($fp, "C01 CAPABILITY"."\r\n");
while (!feof($fp)) {
echo fgets($fp, 256);
}
I get the first response:
OK Gimap ready for requests from xx.xx.xx.xx v3if9968808ibd.15
but then the page times out. I have searched through stream_set_blocking, stream_set_timeout, stream_select, fread, etc. but could not get it to work. I need to read all the data that the server sends and then proceed with other commands (I would be retrieving emails using imap).
Thanks
Your script is hanging in the while loop at the end. This is because you have used !feof() as the condition for the loop, and the server is not closing the connection. This means the feof() will always return false and the loop will continue forever.
This will not be problem when your write a full implementation, as you will be looking for response codes and can break out of the loop accordingly, for example:
<?php
// Open a socket
if (!($fp = fsockopen('ssl://imap.gmail.com', 993, $errno, $errstr, 15))) {
die("Could not connect to host");
}
// Set timout to 1 second
if (!stream_set_timeout($fp, 1)) die("Could not set timeout");
// Fetch first line of response and echo it
echo fgets($fp);
// Send data to server
echo "Writing data...";
fwrite($fp, "C01 CAPABILITY\r\n");
echo " Done\r\n";
// Keep fetching lines until response code is correct
while ($line = fgets($fp)) {
echo $line;
$line = preg_split('/\s+/', $line, 0, PREG_SPLIT_NO_EMPTY);
$code = $line[0];
if (strtoupper($code) == 'C01') {
break;
}
}
echo "I've finished!";
Your script should be working. In fact, it is working.
See the results below on my pc when I ran your code:
* OK Gimap ready for requests from xx.xx.xx.xx l5if4585958ebb.20
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH
C01 OK Thats all she wrote! l5if4585958ebb.20
Since gmail doesn't disconnect you. No end of file occurs. And the page loading simply times out.
In other words: Your script will just keep waiting and waiting until gmail does disconnect, which unfortunately happens after your page load has already timed out.

Categories