php shell_exec() out put to get a text file
13,006
Solution 1
As you forgot to mention, your command provides a non ending output stream. To read the output in real time, you need to use popen.
Example from PHP's website :
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
You can read the process output just like a file.
Solution 2
If you don't need PHP, you can just run that in the shell :
rate -c 192.168.122.0/24 > file.txt
If you have to run it from PHP :
shell_exec('rate -c 192.168.122.0/24 > file.txt');
The ">" character redirect the output of the command to a file.
Solution 3
You can also get the output via PHP, and then save it to a text file
$output = shell_exec('rate -c 192.168.122.0/24');
$fh = fopen('output.txt','w');
fwrite($fh,$output);
fclose($fh);
Author by
Roshan Wijesena
Open source developer at WSO2. https://github.com/rswijesena
Updated on June 04, 2022Comments
-
Roshan Wijesena almost 2 years
I'm trying to run
rate -c 192.168.122.0/24
command on my Centos computer and write down the output of that command to the text file usingshell_exec('rate -c 192.168.122.0/24')
command; still no luck!! -
Matthieu Napoli about 13 yearsWell if you run the command yourself do you get an output ? With and without the "> file.txt". This is weird if the text file is empty, that means that the command doesn't print any result.
-
Roshan Wijesena about 13 yearsthank you for your reply .yes i can get the out put when run the command in terminal its non ending output stream
-
Salman A about 13 years@Roshan: Did you run into a "permission problem"? Try adding
2>&1
to the above mentioned command line. I doubt if you can run arbitrary commands from php. -
Roshan Wijesena about 13 years@Salman There is no problem in file permission i can get the out out of ls -l to the text file easily..
-
Roshan Wijesena about 13 yearsNo luck buddy nothing get write to the text file
-
Salman A about 13 years@Roshan: it could still be a permission problem, ls command could have different permissions compared to rate command. Did you try redirecting standard error to a text file?
-
Matthieu Napoli about 13 yearsOk if this is a non ending output that is normal. I'll try another answer.
-
Matthieu Napoli about 13 yearsSee my answer regarding popen.
-
Roshan Wijesena about 13 yearsyes this works fine thank you very much dude for your help very appreciated.