Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP exec() line length (chars per line)

Tags:

shell

php

exec

I'm trying to read information from the command line via exec();

function ex($cmd){

    @exec($cmd,$exec,$status);

    if($status == 0){
        return $exec;   
    }
    return "";

}

I'm trying to parse the output "line by line" but the problem is that the output lines are splitted (just as if the terminal window is "too small"). For parsing it would be pretty helpful if there is no "line length limit" for the output and one line keeps one line no matter what size it is.

How can I archive that?

like image 980
Daniel K. Avatar asked Jul 29 '26 19:07

Daniel K.


1 Answers

A workaround with proc_open(). It's expensive, but this should give you the exact output from your command:

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w")
);

$shell = '/bin/bash';
$command = 'apt-get --just-print upgrade';

$process = proc_open($shell, $descriptorspec, $pipes);

if (is_resource($process)) {

    fwrite($pipes[0], $command);
    fclose($pipes[0]);

    $output = stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    proc_close($process);
}

//$output holds the output in a single string

$lines = explode("\n", $output); // the full lines as array
like image 188
marfis Avatar answered Aug 01 '26 11:08

marfis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!