使用php passthru()更改目录

I want to change the working directory using passthru() method and commandline ..

This is the php script

<?php
passthru("chdir C:/Documents and Settings/svn");
print passthru("dir");

?>

However, it is not changing the working directory to C:/Documents and Settings/svn.. It is outputting the files from the current directory .. How can i fix this ?

Your current code has several issues:

  1. passthru runs a new process, which may change its own current directory -- but this does not affect the current directory of the PHP process at all
  2. passthru prints the output of the command, but it does not return anything; so the print at the end does nothing at all
  3. it attempts to change the current directory even though it does not really need to

To fix the first two, use simply chdir instead of the first passthru and scrap the print:

chdir("C:/Documents and Settings/svn");
passthru("dir");

To fix all three:

passthru("dir \"C:/Documents and Settings/svn\"");

When the command executed via passthru terminates, the current working directory is not propagated to PHP, because it is a child process, different from PHP.

In your case, you could append the wanted directory to the "dir" command, like this:

passthru("dir \"C:/Documents and Settings/svn\"");

I don't recommend directly using the PHP chdir() function in your case, because it could have nasty side-effects, especially if you're including other PHP files from your script. It also might not work as expected if you are using safe mode.

passthru("chdir C:/Documents and Settings/svn; dir");