Page 1 of 1

reading from STDIN

Posted: Thu Jan 01, 2004 3:31 pm
by Fredix
Hi,
I'm trying to use PHP as a shell scripting language...
What I need to do is read from the shell - but how?
C has scanf,
in PERL you do $var = <STDIN>;

but what about PHP?
I could not find a satisfying solution yet!

Posted: Thu Jan 01, 2004 3:38 pm
by JAM
Not sure, but; getinput(lenght) perhaps (?)

Posted: Sat Jan 03, 2004 5:33 am
by Fredix
Sorry, but I could not find the function you are talking about?!

I came across the following solution:

Code: Select all

<?php
define('STDIN',fopen("php://stdin","r"));
$stdin = fgets(STDIN, 1024);
?>
but this is not satisfying because............well look at the following script:

Code: Select all

#!/usr/bin/php -f
<?php
	echo "Say something!\n";
	define('STDIN',fopen("php://stdin","r"));
	$stdin = fgets(STDIN, 1024);
	echo "You said ".$stdin;
?>
What should it do?
It should tell you to make some input, then read your input and finally print it.

WHAT IT DOES
Waits for input, then tells you type something and then directly prints what you've typed at the beginning.
bash-2.05b$ ./shebang.php
blabla
Say something!
You said blabla
bash-2.05b$
I also heard about the function readline() but to use it I need to recompile my php... so I could not test it yet. But I even doubt it would help because as far as I know it is just the synonym for what I have so probably it would produce the same unsatisfying result....

Has anyone made the same/different experiences?

Posted: Sat Jan 03, 2004 8:48 am
by JAM
Actually, getinput() was a user-function that I used, rather than a inbuildt one, so sorry. Of course that wouldn't help you. Didn't know where i picked that up, so I found this while searching.

Not a very interesting page, but might give you more info as a function is used in this case.

http://www.zend.com/zend/spotlight/shellscriptingp1.php

Posted: Sat Jan 03, 2004 12:39 pm
by Weirdan
hmm... It works pretty well for me:

Code: Select all

weirdan@office:~$ ./q.php
Say something!
asd
You said asd
weirdan@office:~$ php --version
PHP 4.3.3 (cli) (built: Oct 23 2003 14:55:11)
Copyright (c) 1997-2003 The PHP Group
also in CLI version STDIN is a predefined constant.

Posted: Sat Jan 03, 2004 1:08 pm
by Fredix
@Weirdan
bash-2.05b$ php -v
PHP 4.3.3 (cgi-fcgi) (built: Sep 12 2003 00:18:31)
Copyright (c) 1997-2003 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2003 Zend Technologies
It seems to be the cgi version though the man page is for the CLI version!

@JAM
am reading.... though it looks like it is the same, hmm gonna try anyway