Search code examples
phpcmddos

Running multiple dos commands and changing drive letters - all through php exec()


I'm trying to run a few commands through php exec() and am having a ton of trouble. #1, I can't change the drive letter the commands need to run on. #2, I can't run multiple commands - only the first command runs.

example of what I'm trying to do

"cmd.exe /c \"cd E:\files; p4 -P -u user1 -c client1 sync ...\""

This is driving me absolutely nuts, I've tried everything and cannot change the drive letter. Even without changing the drive letter, only my first command will run. Any help is appreciated.


Solution

  • I assume that the reason that you need to do this is because the p4 application needs to be started with a working directory of the directory in which it resides - in which case way to do this is to change the working directory of your PHP script (chdir()) before calling exec():

    // Get current working directory so we can set it back afterwards
    $oldDir = getcwd();
    
    // Change to required dir
    chdir('E:\\files');
    // Execute external program
    exec('p4 -P -u user1 -c client1 sync ..');
    
    // Change back to original working directory
    chdir($oldDir);
    

    If the working directory of the external program doesn't matter, you can just do this:

    exec('E:\\files\\p4 -P -u user1 -c client1 sync ...');
    

    You may also need to append the file extension (e.g. .exe) to the name of the file you are executing in order for it to work.