简体   繁体   中英

PHP: Running a shell command from PHP?

echo shell_exec("ll");

为什么运行此代码时php为什么不显示文件和目录列表?

You're using an aliased command. That's why. What happens when you run ls ?

Source: PHP page for shell_exec and experience

ll isn't the command. I believe that echo shell_exec("ls"); will output a list of directories.

Also you can have some problems if you are running PHP in safe mode. Here you have more information: http://php.net/manual/en/function.shell-exec.php

shell_exec : This function is disabled when PHP is running in safe mode.

Eventually, you have more secure alternatives to execute a command in a bash like readdir : http://php.net/manual/en/function.readdir.php . This is a function that read the files that are in a certain directory.

readdir($dir_handle) example:

<?php

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

    closedir($handle);
}
?>

ll is often added as a default alias in bash (in your .bashrc file).

To double check whether ot not this is the case, type the following in your terminal:

type -a ll

Your shell will tell you whether or not ll is an alias or an actual program.

PHP runs in a different environment which does not have your default aliases installed.

The command expression you probably want is:

shell_exec("ls -l");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM