Using PHP to keep authenticated user logged into IRC

I am using the PHP script below to log an authenticated user into a chat channel. The problem is that the page needs to continuously load to keep the user logged in. I make this happen by using a while loop that stops running when $timer reaches 10 million (enough time in microseconds for successful login). This limit is to prevent an infinite loop. If I leave out this while loop, the user will never be logged in.

How do I allow the page to stop loading after a normal time and keep the user logged in? I just don’t know where to go from here.

$chatServer = [];
ChatLogin('asdfghost_', 'test_channel');

function ChatLogin($user, $target_ch) {

    set_time_limit(0);

    function IRC($name, $channel) {
        $config = array(
                'server'  => 'irc.twitch.tv', 
                'port'    => 6667, 
                'channel' => '#'.$channel,
                'name'    => $name,
                'nick'    => $name,
                'pass'    => 'oauth:'.$GLOBALS['theToken']
        );

        $GLOBALS['chatServer']['connect'] = fsockopen($config['server'], $config['port']);

        if ($GLOBALS['chatServer']['connect']) {
            SendData("PASS " . $config['pass'] . "\n\r");
            SendData("NICK " . $config['nick'] . "\n\r");
            SendData("USER " . $config['nick'] . "\n\r");
            SendData("JOIN " . $config['channel'] . "\n\r");

            $timer = 0; // load time

            while (!feof($GLOBALS['chatServer']['connect']) && $timer <= 10000000) {
        	    ++$timer;
            }

            echo "Now connected to " . $channel . "’s channel!";
        
        } else {
    	    echo "Could not connect to channel. Try again.";
        }
    }

    function SendData($cmd) {
        fwrite($GLOBALS['chatServer']['connect'], $cmd, strlen($cmd));
    }

    IRC($user, $target_ch);
}

I’m going to only chime in on this exactly one time -

Please don’t use PHP to try and persist connections. That’s not what it’s for. PHP is not a stateful language, and is not intended for long running sockets. The amount of hackery you will be out of control.

Use javascript, use web sockets, use actual normal sockets, use any language that’s actually intended to maintain persisted connections.

PHP can be used for persistent connections, but it should be done in a command line script, not in a script executed by a web server.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.