Sending proc_open output to a function or a file

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
stevelloyd
New php-forum User
New php-forum User
Posts: 1
Joined: Tue Feb 20, 2018 6:57 pm

Tue Feb 20, 2018 7:05 pm

How would I change this function so that I could send the output to another function or file as it is written ? for instance. If cmd was apt-get update I would like the output of that command to be sent to a file or a function in real time.

Code: Select all

function cmdResults($cmd,$args='',$dir='',$timeout=0){
	if(!is_dir($dir)){$dir=null;}
	if(strlen($args)){$cmd .= ' '.trim($args);}
	$proc=proc_open($cmd,
		array(
			0=>array('pipe', 'r'), //stdin
			1=>array('pipe', 'w'), //stdout
			2=>array('pipe', 'a')  //stderr
			),
		$pipes,
		$dir
		);
	stream_set_blocking($pipes[2], 0);
	fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
    $rtncode=proc_close($proc);
    $rtn=array(
    	'cmd'	=> $cmd,
    	'args'	=> $args,
    	'dir'	=> $dir,
		'stdout'=>$stdout,
        'stderr'=>$stderr,
        'rtncode'=>$rtncode
    );
    //remove blank vals
    foreach($rtn as $k=>$v){
    	if(!is_array($v)){
			if(!strlen($v)){unset($rtn[$k]);}
    		else{$rtn[$k]=trim($v);}
		}
	}
	return $rtn;
}

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 696
Joined: Mon Feb 22, 2016 5:52 pm

Fri Feb 23, 2018 10:43 am

Unless what you are doing is just using PHP to help write some bash scripts, then what you're looking at is very bad practice. If you are looking to use PHP to help write the scripts, then read on as there can be problems which apply equally.

If you want to use / write command line scripts, then use command line scripts. By using PHP to do this, all you are doing is opening up your system for abuse (i.e. creating a security nightmare); the scripts won't be portable and you'll be setting your self up for problems in the future.

Whatever you think you want to do to the system, can be done using PHP (mostly), if you can't then there is good reason for it.

Post Reply