Search code examples
phptext-filesstdinfopenfwrite

fgets(STDIN) automatic line break?


I noticed something with fgets(STDIN) in php

I have this code :

if($fd = fopen($filename, "a")){

    $message = fgets(STDIN);
    $message = $message.":";
    echo $message;
    //fwrite($fd, $message);
    fclose($fd);
}

I try for exemple to insert at the end of my text-file :

helloWorld

But i always have :

helloWorld
:

not :

helloWorld:

Is stdin makes a automatic line feed ? How to remove this automatic jump ?


Solution

  • Use stream_get_line instead of fgets:

    if($fd = fopen($filename, "a")){
        $message = stream_get_line(STDIN, 1024);
        $message = $message.":";
        echo $message;
        //fwrite($fd, $message);
        fclose($fd);
    }
    

    Or you can use rtrim function to remove line endings:

    if($fd = fopen($filename, "a")){
    
        $message = fgets(STDIN);
        $message = rtrim($message, "\n\r") . ":";
        echo $message;
        //fwrite($fd, $message);
        fclose($fd);
    }