Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php stdin from bash pipe and heredoc

Tags:

bash

php

Can I receive input from both a pipe, and a heredoc, and use them both from within php on the command line.

I want to do something like this:

bash$ ls -l | php <<'code'
<?php
   echo $piped;
?>
code

Which should return the result of ls -l

Also, can I use php -R with heredoc input for php script?

like image 672
Billy Moon Avatar asked Dec 27 '11 20:12

Billy Moon


2 Answers

Piping

ls -l | php -r 'print_r(file("php://stdin"));'


Heredoc

$ php <<CODE
<?php
echo "Hello World\n";
?>
CODE
Hello World

Combined

$ ls -l | php <<'CODE'
<?php
$f = file("php://stdin");
foreach($f as $k=>$v){
echo "[$k]=>$v";
}
?>
Program Finished
CODE

[0]=><?php
[1]=>$f = file("php://stdin");
[2]=>foreach($f as $k=>$v){
[3]=>echo "[$k]=>$v";
[4]=>}
[5]=>?>
[6]=>Program Finished
Program Finished

Note: When you use Here Documents for php command the newly added php codes overrides the previous stdin

like image 69
Shiplu Mokaddim Avatar answered Oct 08 '22 03:10

Shiplu Mokaddim


Regarding the -R part of the question:

-R / --process-code

PHP code to execute for every input line. Added in PHP 5.

There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number. Docs

If I understood your question right, you're looking for the $argn variable. Heredoc should be support by your bash.

Edit: Err, just invoke with the value over multiple lines:

$ ls -l | php -R '
printf("#%02d: %s\n", $argi, $argn);
'

(I think it's easier to use the single quote for the switch)

like image 20
hakre Avatar answered Oct 08 '22 03:10

hakre