Executing .sh scripts via PHP

2019-05-07 10:39发布

问题:

I have a few game servers that that I need to run shell scripts for frequality. I'm trying to figure out how to run these scripts via a webpage on the same server. It's a Ubuntu Dedicated server.

The website files are located via /var/www/... The .sh files I need to manually run are located in /home/amservers/.../start.sh.

I've looked at other answers and I still can't figure it out. How do locate the files and store it and then run exec()?

回答1:

You could just use the shell_exec() function in PHP:

http://php.net/manual/en/function.shell-exec.php

shell_exec('sh script.sh');

And if you want to use the variables ($1, $2 etc. in bash) you could just type:

shell_exec('sh script.sh variable1 variable2');


回答2:

You can use either an absolute path or a relative path. For relative paths, the current directory is usually the PHP files's. If you can't access your scripts even with an absolute path, there could be a problem with filesystem access rights. Keep in mind PHP scripts are typically executed as the web server's (system) user account.

Your shell scripts should be stored somewhere near or inside your application tree, so that you can grant acces to them to your PHP scripts (i.e. to your web server), without compromising too much your file system security.



回答3:

if you want to check the output of the script on browser than you can simply use

var_dump(shell_exec('sh script.sh'));

or

var_dump(shell_exec('sh script.sh variable1 variable2'));



标签: php linux sh