php - fgets(STDIN) automatic line break?

477

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 ?

353

Answer

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);
}

People are also looking for solutions to the problem: php - How to display my own errors instead of default errors using pdo connection?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.