PHP file execution
Hey, I'm trying to use PHP to execute a shell command which will run remotely run a server on my box. Here is my PHP Code:
if ($key == "test") { echo "<font color='green'&g开发者_运维知识库t;Key is valid. Server satrted.</font>";
$start = system('cd /root/st/; ls;');
}
The problem is, the ls command runs from the same directory as the web server, which returns all of the files from /var/www/html instead of /root/st/. I have also tried the chdir command to no avail. Anyone know how you would get the directory to change so that the command could be run from a specified directory? Thanks.
Does the user that PHP is running as (eg, the user invoking the CLI script) have permission to read the directory? If you're going into /root/
but aren't root
, you'd need to either add cd
to sudoers for the current user, or choose another directory.
Edit: note that adding cd
to sudoers is not even remotely okay for anything other than a local, you-only script. :)
There are two ways I would approach this.
1: use proper unix commands, and see if they work. IE:
if ($key == "test") { echo "<font color='green'>Key is valid. Server satrted.</font>";
$start = system('ls /root/st/');
}
2: Make it run a script on the system, that can go outside the webserver's chroot.
if ($key == "test") { echo "<font color='green'>Key is valid. Server satrted.</font>";
$start = system('server.sh');
}
and server.sh is
#!/bin/bash
cd /root/st
ls
PHP has a chdir()
function. Not sure if it applies to exec/system calls, but worth a try.
Store the location in a variable, say $loc = '/root/st'
and then do ls $loc
in your code. Hope this helps.
Your problem is not the directory the script is running in (or more precisely the current working directory of the user running the script), but that cd /root/st/
will fail on any reasonable configured UNIX/Linux system. /root
is usually owned by root
and can't be accessed by any other user.
Using you snippet this will silently fail because you unconditionally chained the cd
and the ls
commands with a semicolon instead of &&
.
精彩评论