Search code examples
phpstdintailtee

Why does fgets(STDIN, 1024) not work anymore?


Question 1

I used to use that line for my PHP parser file for a game server, but it does not work anymore. I know there is the fopen("php://stdin") thing but that's now 3 lines of code instead of just one, why would PHP do this?

Question 2

Also, when I use that method I keep getting this output which is causing my script to not read the commands the parser outputs, how can I stop it?

X-Powered-By: PHP/5.2.12
Content-type: text/html

I tried setting Content-Type to text/plain and it didn't do anything...
Here's the base code:

#!/usr/bin/php
<?php

while (1):
    $line = rtrim(fgets(STDIN, 1024));
    $line = explode(" ", $line);
    switch ($line[0]):
        // NEW_ROUND <date> <time>
        // PLAYER_ENTERED <nice_name> <ip> <real_name>
        case "PLAYER_ENTERED":
            print "PLAYER_MESSAGE {$line[1]} WELCOME TO TRONNERS!\n";
            break;
        // PLAYER_LEFT <nice_name> <ip>
        // RACE_DONE
        case "RACE_DONE":
            print "CONSOLE_MESSAGE RACING TIMEKEEPER COMING SOON!\n";
            break;
        // ROUND_COMMENCING <round> <max_rounds>
        case "ROUND_COMMENCING":
            print "CENTER_MESSAGE What's the name of this map?\n";
            break;
    endswitch;
endwhile;

?>

I'm using a tail to keep lines being posted to a file going into the PHP parser and then the output from the parsed is being sent to another commands file via tee.


Solution

  • You are using the *-cgi binary from the command line, which I wouldn't recommend. Use the CLI one if available. See where the symbolic link in /usr/bin/php actually goes.

    edit: aha, here it is in the manual, only valid for CLI:

    http://www.php.net/manual/en/features.commandline.io-streams.php

    $ echo  '<?php echo fread(STDIN,123); ?>' > r.php
    $ echo 'bla' | php5-cgi -q -d html_errors=off r.php 
    Warning: fread() expects parameter 1 to be resource, string given in /tmp/r.php on line 1
    Call Stack:
        0.0002     330080   1. {main}() /tmp/r.php:0
        0.0002     330260   2. fread() /tmp/r.php:1
    
    $ echo 'bla' | php r.php 
    bla
    

    Under debian it could likely be fixed by the following (don't know about other *nix flavors):

    update-alternatives --config php
    

    For building from source the manual explains what happens: http://nl.php.net/manual/en/features.commandline.introduction.php