views:

46

answers:

3

Is it possible to execute cmd commands in Windows OS with PHP exec() function?

I tried this:

<?php

try {

    echo exec(
    'O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf'
    );

} catch (Exception $e) {
    echo $e->getMessage();
}

Basically, I'm trying to merge two pdf files with the pdftk program. If I just write the same exact command to the cmd by hand, it works and the O:\test\123.pdf file is created. But when I execute the above PHP file, nothing happens (blank page, the file is not created).

+1  A: 

Try escaping the directory separator:

exec("O:\\test\\pdftk.exe O:\\test\\outputs\\OPP\\out.pdf O:\\test\\outputs\\OPP\\out2.pdf cat output O:\\test\\123.pdf");

Or even better, use single quotes instead:

exec('O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf');
Andy E
No. That doesn't work. I also tried shell_exec() which doesn't work as well.
Richard Knop
@Richard: Even still, you will need to correctly escape the directory separator or use single quotes instead. Have you made sure `exec` and `shell_exec` are enabled in your configuration?
Andy E
@Richard Knop try something simpler like writing some text to a file with shell_exec then maybe something else is wrong and not with php configuration(that is if exec is enabled)
c0mrade
exec() is enabled. I tried exec('ipconfig -all'); and shell_exec('ipconfig - all'); and both worked.
Richard Knop
@Richard: That would suggest there's a problem with your command. Try passing an array to the second parameter of exec, then `print_r` that array afterwards.
Andy E
I get empty array.
Richard Knop
But once gain, when I write the command to the cmd manually by hand, it works. So the command must be ok. Also the exec() is enabled because when I try other commands, they work.
Richard Knop
@Richard: that doesn't make much sense - if there was an error with the command then it would be output. Is the [author's PHP script](http://www.accesspdf.com/pdftk/#forge_fdf) of any use to you? Other than that, I'm out of ideas - sorry!
Andy E
+1  A: 

Can your PHP user access cmd.exe? You might find the tools at Microsoft's Sysinternals very useful; particularly the process monitor.

Andy
I think yes. Other commands do work. If I try exec('ipconfig -all'), for example, it works. I downloaded the process monitor and it seems that every process with pdftk gets executed correctly. There is just one process which says "buffer overflown" or something like that.
Richard Knop
Can you confirm that if you open cmd.exe and run 'O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf' that it works as expected?
Andy
Yes. It works as expected when I type it directly into shell.
Richard Knop
A: 

try Executing using the Admin Privileges for command prompt

Someone