So I have this PHP code which is pretty simple.
$string = exec("ls foo");
In foo I have 4 files
foo
bar
hi
bye
But echo $string returns bye
How can I make it return all of the files? Is it not working because ls separates by tabs?
From the manual: http://php.net/manual/en/function.exec.php
Return Values
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the ˋpassthru()ˋ function.
Please do not use exec for file operations. PHP has a full set of functions for that purpose. You can start with dir:
http://php.net/manual/en/function.dir.php
Boris' suggestion is good, but it's a bit complicated to figure it out.
Simply use this
passthru ('ls');
or this to 'prettify' it
echo "<pre>";
passthru ('ls');
echo "</pre>";
I have a script that need to run from a terminal or a command prompt. I'm using PHP. GetOpt is the function that I use to get data or a parameter that the user input in the terminal.
This is my script.
<?php
$opt = getopt("f:");
$input = $opt['f'];
$u = fopen($input, 'r');
echo "\n\n$input\n\n";
I tried to run it like this:
$ php myscript.php -f http://myurl.com/file.csv?city=london&status=3
My url is http://myurl.com/file.csv?city=london&status=3, but it only outputs http://myurl.com/file.csv?city=london. The status parameter is lost from the full URL.
How can I get this to work?
it's because you have to wrap your link around into quotes:
$ php myscript.php -f "http://myurl.com/file.csv?city=london&status=3"
I'll go ahead and assume you are running your script in Bash, and & in Bash might be interpreted as bitwise AND in your case:
$ echo $(( 98 & 7 ))
2
I want to use php's strip tags in a bash script. I figured I could just cat the html file I want to use and use that input and pipe it into php and then pipe that into something else (sed). Is that possible? I'm not sure exactly how to pipe the output of file.html into the strip_tag function...maybe put it all in a variable? I want the following to keep just the anchor tags...in the following I put in dummy text for strip_tags string because I didn't know how to pipe file.html in:
cat file.html | php strip_tags("<p><a href='#'>hi</a></p>",'<a>') > removed_tags.html
You can read from STDIN in PHP using the stream URI php://stdin. As for executing it, you'll also need to quote the PHP code and use the -r option, as well as echoing the result. So here's the fixed script:
cat file.html | php -r "echo strip_tags(file_get_contents('php://stdin'), '<a>');" > removed_tags.html
Reading from stdin in PHP and writing a php script without a file are possible, but it's way more trouble than just writing a file like
<?php echo strip_tags(file_get_contents($argv[1]), '<a>');
...
$ php that-file.php file.html > removed_tags.html
It is possible to pipe data using unix pipes into a command-line php script? I've tried
$> data | php script.php
But the expected data did not show up in $argv. Is there a way to do this?
PHP can read from standard input, and also provides a nice shortcut for it: STDIN.
With it, you can use things like stream_get_contents and others to do things like:
$data = stream_get_contents(STDIN);
This will just dump all the piped data into $data.
If you want to start processing before all data is read, or the input size is too big to fit into a variable, you can use:
while(!feof(STDIN)){
$line = fgets(STDIN);
}
STDIN is just a shortcut of $fh = fopen("php://stdin", "r");.
The same methods can be applied to reading and writing files, and tcp streams.
As I understand it, $argv will show the arguments of the program, in other words:
php script.php arg1 arg2 arg3
But if you pipe data into PHP, you will have to read it from standard input. I've never tried this, but I think it's something like this:
$fp = readfile("php://stdin");
// read $fp as if it were a file
If your data is on one like, you can also use either the -F or -R flag (-F reads & executes the file following it, -R executes it literally) If you use these flags the string that has been piped in will appear in the (regular) global variable $argn
Simple example:
echo "hello world" | php -R 'echo str_replace("world","stackoverflow", $argn);'
You can pipe data in, yes. But it won't appear in $argv. It'll go to stdin. You can read this several ways, including fopen('php://stdin','r')
There are good examples in the manual
This worked for me:
stream_get_contents(fopen("php://stdin", "r"));
Came upon this post looking to make a script that behaves like a shell script, executing another command for each line of the input... ex:
ls -ln | awk '{print $9}'
If you're looking to make a php script that behaves in a similar way, this worked for me:
#!/usr/bin/php
<?php
$input = stream_get_contents(fopen("php://stdin", "r"));
$lines = explode("\n", $input);
foreach($lines as $line) {
$command = "php next_script.php '" . $line . "'";
$output = shell_exec($command);
echo $output;
}
If you want it to show up in $argv, try this:
echo "Whatever you want" | xargs php script.php
That would covert whatever goes into standard input into command line arguments.
Best option is to use -r option and take the data from the stdin. Ie I use it to easily decode JSON using PHP.
This way you don't have to create physical script file.
It goes like this:
docker inspect $1|php -r '$a=json_decode(stream_get_contents(STDIN),true);echo str_replace(["Array",":"],["Shares"," --> "],print_r($a[0]["HostConfig"]["Binds"],true));'
This piece of code will display shared folders between host & a container.
Please replace $1 by the container name or put it in a bash alias like ie displayshares() { ... }
I needed to take a CSV file and convert it to a TSV file. Sure, I could import the file into Excel and then re-export it, but where's the fun in that when piping the data through a converter means I can stay in the commandline and get the job done easily!
So, my script (called csv2tsv) is
#!/usr/bin/php
<?php
while(!feof(STDIN)){
echo implode("\t", str_getcsv(fgets(STDIN))), PHP_EOL;
}
I chmod +x csv2tsv.
I can then run it cat data.csv | csv2tsv > data.tsv and I now have my data as a TSV!
OK. No error checking (is the data an actual CSV file?), etc. but the principle works well.
And of course, you can chain as many commands as you need.
If you are wanting more to expand on this idea, then how about the ability to include additional options to your command?
Simple!
#!/usr/bin/php
<?php
$separator = $argv[1] ?? "\t";
while(!feof(STDIN)){
echo implode($separator, str_getcsv(fgets(STDIN))), PHP_EOL;
}
Now I can overwrite the default separator from being a tab to something else. A | maybe!
cat data.csv | csv2tsv '|' > data.psv
Hope this helps and allows you to see how much more you can do!
I want to see the output of the following code in the web browser:
code:
<?php
$var = system('fdisk -l');
echo "$var";
?>
When I open this from a web browser there is no output in the web browser. So how can I do this? Please help!
Thanks
Puspa
you can use passthru, like so:
$somevar = passthru('echo "Testing1"');
// $somevar now == "Testing1"
or
echo passthru('echo "Testing2"');
// outputs "Testing2"
use exec('command', $output);
print_r($output);
First of all, be sure that you (=user under which php runs) are allowed to call the external program (OS access rights, safe_mode setting in php.ini). Then you have quite a few options in PHP to call programs via command line. The most common I use are:
system
This function returns false if the command failed or the last line of the returned output.
$lastLine = system('...');
shell_exec or backtick operators
This function/operator return the whole output of the command as a string.
$output = shell_exec('...'); // or:
$output = `...`;
exec
This function returns the last line of the output of the command. But you can give it a second argument that then contains all lines from the command output.
$lastLine = exec('...'); // or capturing all lines from output:
$lastLine = exec('...', $allLines);
Here is the overview of all functions for these usecases: http://de.php.net/manual/en/ref.exec.php