Alternate PHP exec() function bypassing cmd.exe

I had a problem running executables (like identify.exe and convert.exe from ImageMagick) from php under windows using the exec() funciton. The solution provided by others was kind off stupid... Give full permisions on cmd.exe to IURS... Like you wanna do that.....
I wrote a exec() replacement function using the bypass_shell option proc_open has. It works great for me. Do your favour with it.

 
<?php
 
	function executeCommand($cmd) {
 
		if(DEBUG === true) {
			echo "Command: ".$cmd;
			echo "<br>";
			echo "Tempdir: ".TEMP_DIR;
			echo "<br>";
		}
 
		$descriptorspec = array(
		   0 => array("pipe", "r"),
		   1 => array("pipe", "w"),
		   2 => array("pipe", "w")
		);
 
		$process = proc_open(
				$cmd,
				$descriptorspec,
				$pipes,
				TEMP_DIR,
				NULL,
				array('bypass_shell' => TRUE)
		);
 
		if(!is_resource($process)) {
			return false;
		}
 
		if(!$pipes[1]) {
			if(DEBUG === true) {
				echo "No STDOUT<br>";
			}
			return false;
		}
		$output = stream_get_contents($pipes[1]);
		fclose($pipes[1]);
		$err = stream_get_contents($pipes[2]);
		fclose($pipes[2]);
 
		$x = proc_get_status($process);
 
		$return_value = proc_close($process);
 
		if($return_value == 0) {
			if(DEBUG === true) {
				echo "Return value {$return_value}<br>";
				print_r($x);
				echo "<br><br><br>";
			}
			return explode("\n", str_replace("\r", '', $output));
		} else {
			if(DEBUG === true) {
				echo "Return value {$return_value}<br>";
				print_r($x);
				echo "Output: ".$output;
				echo "Error: ".$err;
				echo "<br><br><br>";
			}
			return false;
		}
 
	}
?>
 

2 Responses to “Alternate PHP exec() function bypassing cmd.exe”

  1. Cesar on 22 Feb 2010 at 5:03 pm #

    TEMP_DIR?????????

  2. Daniel on 22 Feb 2010 at 7:18 pm #

    Yeah, you need to define this:

    define(”TEMP_DIR”, “whatever/dir/name”);

Trackback URI | Comments RSS

Leave a Reply

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a