php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72019 stdin fgets substr
Submitted: 2016-04-13 17:04 UTC Modified: 2016-04-14 03:47 UTC
From: k6dg at outlook dot com Assigned:
Status: Not a bug Package: CGI/CLI related
PHP Version: 7.0.5 OS: windows7
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: k6dg at outlook dot com
New email:
PHP Version: OS:

 

 [2016-04-13 17:04 UTC] k6dg at outlook dot com
Description:
------------
it only appear in the ZTS version.

use php://stdin get a line with '\n'.
use substr cutoff last char and return it.

use php://stdout print the return value, and print something else.
the return value can not be seen.


Test script:
---------------
function stdin () {
	$stdin = fopen('php://stdin','r');
	$text = fgets($stdin); // This
	fclose($stdin);
	return substr($text, 0, -1); // and This couse the problem
}

function stdout(string $data) {
	$stdout = fopen('php://stdout','a');
	$length = fwrite($stdout, $data);
	fclose($stdout);
	// $length = file_put_contents ('php://stdout', $data, FILE_APPEND);
	return $length;
}
stdout(stdin());
stdout('hello');

Expected result:
----------------
input:
12

output:
hello

Actual result:
--------------
input:
12

output:
12hello

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-04-14 02:47 UTC] jhdxr@php.net
-Status: Open +Status: Not a bug
 [2016-04-14 02:47 UTC] jhdxr@php.net
first, I think you confused expected result and actual result. "12hello" should be the expected result while "hello" is printed.

In fact, php works as expected. When you type "12<enter> in windows, the string actually is "12\r\n", and result of `substr($test, 0, -1)` is "12\r". "\r" means moving cursor to the begining of the line, and if you continue print something, they will cover the origin display. you can try `stdout('a')` instead of `stdout('hello')` and you will see "a2", because "a" covers "1".

If you want to remove the line break in the output, `trim` or `substr($in, 0, -strlen(PHP_EOL))` may be a better choice.
 [2016-04-14 03:47 UTC] k6dg at outlook dot com
ZTS version and NTS version get difference result
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 09:01:34 2025 UTC