Recently I was working on an application which uses exec() function of php to execute some commands. Apparently I observed abnormal behavior for long commands, there was no output and no error. After some research, I came across facts below:

  • On command prompt, total length of the command that you can use cannot exceed more than 2047 or 8191 characters.(windows XP or later). [Source]
  • The maximum command line length for the CreateProcess function is 32767 characters. CreateProcess is the core function for creating processes. If you are reaching CreateProcess by some other means, then the limits may vary.[Source]

Now the solution is to reach CreateProcess in php. Well, it is not recommended to write software which utilizes such big command lengths for operation. But if you are still stuck with the case , the proc_open() function of php is the solution which provides greater degree of control over the program execution. I did not get exact solution to the problem online that’s why I decided to write this article. Refer proc_open() manual for details.

So you just have to call proc open and enable bypass_shell to TRUE, and it will not take path through command prompt . The code is given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$cmd="my command";

$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("pipe", "w")
);

$options=array('bypass_shell' => TRUE);

$process = proc_open($cmd, $descriptorspec, $pipes, NULL, NULL,$options);

if (is_resource($process)) {
    $output=stream_get_contents($pipes[1]);

    fclose($pipes[0]);fclose($pipes[1]);fclose($pipes[2]);

    proc_close($process);
}

This is just a quick worka around. Hope it helps !