fsocketopen() Not connecting to server? - php

I've been trying to connect to a Twitch chat via IRC. I've added an echo function to test where I had connected or not as that page was blank and an account didn't join the IRC.
Here is my code:
<?php
set_time_limit(0);
ini_set('display_errors', 'on');
$datatwitch= array(
'server' => 'irc.twitch.tv',
'port' => 6667,
'nick' => 'greatbritishbgbot',
'name' => 'greatbritishbgbot',
'pass' => 'oauth:HERE',
);
?>
<?php
//The server host is the IP or DNS of the IRC server.
$server_host = $datatwitch['server'];
//Server Port, this is the port that the irc server is running on. Deafult: 6667
$server_port = $datatwitch['port'];
//Server Chanel, After connecting to the IRC server this is the channel it will join.
$server_chan = "#greatbritishbg";
//login password
$nickname = $datatwitch['name'];
$nickname_pass = $datatwitch['pass'];
//Ok, We have a nickname, now lets connect.
$server = array(); //we will use an array to store all the server data.
//Open the socket connection to the IRC server
$server['SOCKET'] = #fsockopen($server_host, $server_port, $errno, $errstr, 2);
if($server['SOCKET'])
{
//Ok, we have connected to the server, now we have to send the login commands.
echo "connected";
SendCommand("PASS $nickname_pass \n\r"); //Sends the password not needed for most servers
SendCommand("NICK $nickname\n\r"); //sends the nickname
SendCommand("USER $nickname USING PHP IRC\n\r"); //sends the user must have 4 paramters
while(!feof($server['SOCKET'])) //while we are connected to the server
{
$server['READ_BUFFER'] = fgets($server['SOCKET'], 1024); //get a line of data from the server
echo "[RECIVE] ".$server['READ_BUFFER']."<br>\n\r"; //display the recived data from the server
/*
IRC Sends a "PING" command to the client which must be anwsered with a "PONG"
Or the client gets Disconnected
*/
//Now lets check to see if we have joined the server
if(strpos($server['READ_BUFFER'], "422")) //422 is the message number of the MOTD for the server (The last thing displayed after a successful connection)
{
//If we have joined the server
SendCommand("JOIN $server_chan\n\r"); //Join the chanel
}
if(substr($server['READ_BUFFER'], 0, 6) == "PING :") //If the server has sent the ping command
{
SendCommand("PONG :".substr($server['READ_BUFFER'], 6)."\n\r"); //Reply with pong
//As you can see i dont have it reply with just "PONG"
//It sends PONG and the data recived after the "PING" text on that recived line
//Reason being is some irc servers have a "No Spoof" feature that sends a key after the PING
//Command that must be replied with PONG and the same key sent.
}
flush(); //This flushes the output buffer forcing the text in the while loop to be displayed "On demand"
}
} else {
echo "connection failed";
}
function SendCommand ($cmd)
{
global $server; //Extends our $server array to this function
#fwrite($server['SOCKET'], $cmd, strlen($cmd)); //sends the command to the server
echo "[SEND] $cmd <br>"; //displays it on the screen
}
?>
It appears I can't Get passed if($server['SOCKET']). Is there anyway I can diagnose this? As I have directly connect with the details in hexChat.

The server had actually been preventing me to use fsocket. After contacting my host and moving away from a shared host it started to work.

Please take a look at this answer: https://stackoverflow.com/a/24835967/1163786
Especially:
$socket = fsockopen($bot["Host"], $bot["Port"], $error1, $error2);
if(!$socket) {
echo 'Crap! fsockopen failed. Details: ' . $error1 . ': ' . $error2;
}
To get the details about the socket error = reason for socket not connecting.
Currently, you have $errno, $errstr on fsockopen, but echo only "connection failed".

Related

phpMQTT non-blocking publish & recieve

I am writing a program connecting a web service in PHP to an MQTT broker. The broker is running Mosquitto on a Raspberry Pi.
The idea is to have the web service send a request (a form is submitted) and then send a publish to the MQTT broker and then wait for a reply.
However, the problem is that the loop seems to cause a PHP fatal error due to the fact that it is an endless loop.
I've tried adding the quitstop() function to quit the loop after a message is received, but the program crashes before it reaches that point.
MQTT is still very new to me, but I need to send the request and then keep the loop open until I receive the answer in order to proceed with my program.
This is the code to handle the form submit:
require("phpMQTT.php");
$server = "xxx.xxx.xxx.xx"; // change if necessary
$port = 1883; // change if necessary
$username = "username"; // set your username
$password = "password"; // set your password
$client_id = "phpMQTT-request-1234"; // make sure this is unique for connecting to sever - you could use uniqid()
$mqtt = new phpMQTT($server, $port, $client_id);
$msg = $_POST['box'];
if (!empty($msg)) {
if ($mqtt->connect(true, null, $username, $password)) {
$mqtt->publish("dev/test", $msg, 0);
$mqtt->close();
}
subscribeToTopic($mqtt);
}
function subscribeToTopic($mqtt)
{
$topics['dev/test'] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
while ($mqtt->proc()) {
}
$mqtt->close();
}
function procmsg($topic, $msg)
{
global $mqtt;
echo $msg;
quitstop($mqtt);
}
function quitstop($mqtt)
{
$mqtt->close();
}

What could cause a PHP socket request to be blocked?

I'm using this PHP library to query a Minecraft server and get some information about it (players online, max players, etc.). It connects to the server via a socket and sends a request for the information, the server sends data back. When I was hosting the code on XAMPP on my personal computer, everything worked perfectly. Then I got a web host (Bluehost) and uploaded all the code and now the request times out every single time. I've used command prompt to ping the server address to ensure that it's up and responding, and it is.
Here's my code:
function pingPlayers($ip) {
try {
$Query = new MinecraftPing($ip);
$response = $Query->Query();
$players = $response['players']['online'];
$maxPlayers = $response['players']['max'];
$online = true;
}
catch(MinecraftPingException $e) {
$players = "0";
$maxPlayers = "0";
$online = false;
var_dump($e);
} finally {
$Query->Close();
}
return array("players" => $players, "maxPlayers" => $maxPlayers, "status" => $online);
}
The MinecraftPing class and all of it's functions can be found here.
I am getting a MinecraftPingException returned, and it says "Failed to connect or create a socket: 110 (Connection timed out)". My first guess was that the host is blocking outgoing requests, but I contacted them and they said nothing is being blocked. I'm not getting any other errors besides the MinecraftPingException.

cannot log into server via telnet PHP

I'm using a [PHP Telnet Class][1] to connect to server via telnet to send commands. It connects to the server successfully but it fails to login in..
require_once "PHPTelnet.php";
$telnet = new PHPTelnet();
// if the first argument to Connect is blank,
// PHPTelnet will connect to the local host via 127.0.0.1
$result = $telnet->Connect('172.20.66.100','username','password');
if ($result == 0) {
$telnet->DoCommand('another command', $result);
echo $result;
$telnet->Disconnect();}
===============================================================================
UPDATE:
My script is working, there was some conflict going on with my virtual machine......
Try this:
$url = 'tcp://ADDRESS_HERE:PORT_HERE';
$fp = stream_socket_client($url, $errno, $errstr, 10);
if (!$fp) {
echo ("$errstr ($errno)<br />\n");
exit;
} else {
$command = 'execute_command_line' . PHP_EOL;
fwrite($fp, $out);
stream_set_blocking($fp, true);
while (!feof($fp)) {
$output = stream_get_contents($fp);
}
fclose($fp);
echo output;
}
According to the documentation in the PHPTelnet website you have the parameters to the constructor in the wrong order.
In the library's documentation there is the following example:
$result = $telnet->Connect('www.somewhere.com','login name','password');
Therefore, you should have:
$result = $telnet->Connect('172.20.66.100','username','password');
Source: PHPTelnet Documentation
EDIT
You mentioned that you get erro nÂș 3. In the source code, error 3 has the following description: Connect failed: Login Failed
Which points to the following URL:
Information about Error 3
Which lists the possible causes as:
You misspelled your username or password (i.e. Your credentials are wrong)
Telnet service is not available for your username and password (i.e. Your user does not have permissions to access the Telnet service)

Query if Shoutcast Server is Offline or Online with PHP

I'm trying to use a script to query if a Shoutcast Server is online or offline. The code below is what I'm using at the moment.
$vt_ip = "ip";
$vt_port = "port";
$output = #fsockopen($vt_ip, $vt_port, $errno, $errstr, 2);
if (!$output) {
echo "<FONT CLASS=f1 COLOR=#DD0000><B>OFFLINE</B></FONT>";
} else {
echo "<FONT CLASS=f1 COLOR=#00DD00><B>ONLINE</B></FONT>";
}
#fclose($output);
But it doesn't update, it is stuck on Offline status.
Any help would be greatly appreciated.
$vt_ip = "ip";
$vt_port = "port";
$conn = fsockopen($vt_ip, $vt_port, $errno, $errstr, 2);
if(!$conn){
echo $errno;
}else{
fwrite($conn, "\n");
$output = fread($conn, 1024);
fclose($conn);
if ($output == "") {
echo "<FONT CLASS=f1 COLOR=#DD0000><B>OFFLINE</B></FONT>";
} else {
echo "<FONT CLASS=f1 COLOR=#00DD00><B>ONLINE</B></FONT>";
}
}
It isn't enough to simply make a TCP connection to a SHOUTcast server to determine if the stream is working. In fact, a SHOUTcast server that is running will always accept yourTCP connection, even if there is no stream for playback.
You must connect, request the stream, and then check the return status code. Once connected, send this data:
GET /; HTTP/1.0
Follow that by a \r\n\r\n. Now, read data back from the stream until you get the \r\n\r\n. Then, you can disconnect. Check the status code from the first response line and see if it's 200. If it is, you've got an active stream.

Why is my PHP Socket Server hanging?

I created a PHP Socket Server with PHP_NORMAL_READ mode. So, a message to the server is read when it ends with \n or \r. I tried it by connecting to the server with multiple telnet instances, and it works great.
However, when I connect to the server with 1 flash application and 1 telnet application (I first start the flash one), the flash one seems to make the server hang - the server is getting stuck somewhere and no longer receiving data from eg. the telnet client.
Because anyone can code a flash client, this has to be fixed server side. The server's code:
<?php
// config
$timelimit = 60; // amount of seconds the server should run for, 0 = run indefintely
$port = 9000; // the port to listen on
$address = $_SERVER['SERVER_ADDR']; // the server's external IP
$backlog = SOMAXCONN; // the maximum of backlog incoming connections that will be queued for processing
// configure custom PHP settings
error_reporting(1); // report all errors
ini_set('display_errors', 1); // display all errors
set_time_limit($timelimit); // timeout after x seconds
ob_implicit_flush(); // results in a flush operation after every output call
//create master IPv4 based TCP socket
if (!($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) die("Could not create master socket, error: ".socket_strerror(socket_last_error()));
// set socket options (local addresses can be reused)
if (!socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1)) die("Could not set socket options, error: ".socket_strerror(socket_last_error()));
// bind to socket server
if (!socket_bind($master, $address, $port)) die("Could not bind to socket server, error: ".socket_strerror(socket_last_error()));
// start listening
if (!socket_listen($master, $backlog)) die("Could not start listening to socket, error: ".socket_strerror(socket_last_error()));
//display startup information
echo "[".date('Y-m-d H:i:s')."] SERVER CREATED (MAXCONN: ".SOMAXCONN.").\n"; //max connections is a kernel variable and can be adjusted with sysctl
echo "[".date('Y-m-d H:i:s')."] Listening on ".$address.":".$port.".\n";
$time = time(); //set startup timestamp
// init read sockets array
$read_sockets = array($master);
// continuously handle incoming socket messages, or close if time limit has been reached
while ((!$timelimit) or (time() - $time < $timelimit)) {
$changed_sockets = $read_sockets;
socket_select($changed_sockets, $write = null, $except = null, null);
foreach($changed_sockets as $socket) {
if ($socket == $master) {
if (($client = socket_accept($master)) < 0) {
continue;
} else {
array_push($read_sockets, $client);
}
} else {
$data = #socket_read($socket, 1024, PHP_NORMAL_READ); //read a maximum of 1024 bytes until a new line has been sent
if ($data === false) { //the client disconnected
$index = array_search($socket, $read_sockets);
unset($read_sockets[$index]);
socket_close($socket);
} elseif ($data = trim($data)) { //remove whitespace and continue only if the message is not empty
echo "we received: ".$data."\n\n";
//handleData($data, $socket);
}
}
}
}
socket_close($master); //close the socket
echo "[".date('Y-m-d H:i:s')."] SERVER CLOSED.\n";
//function to write to the flash client
function flash_write($socket, $msg) {
socket_write($socket, $msg.chr(0x0));
}
?>
Does anyone know what may cause this? I tried changing the timeout on the socket_select from none to 0 (instant return), but that didn't seem to change anything.
Could you post the source of the flash client? That would show what the problem is?
Are you sure the last thing you send from the flash client is a \n ?
Otherwise the server would block on socket_read() as the flash client socket can be read without blocking (triggered socket_select()), but doesn't send the ending \n.
One thing to help you debug: error_reporting(1) does not enable the display of all errors. Look at the documentation at http://us3.php.net/manual/en/function.error-reporting.php. You need something like error_reporting(E_ALL).

Categories