简体   繁体   中英

“exec('sh foo.sh')” in PHP not working

I've recently set up my Apache2 Server on my Linux machine. Now I've wanted to execute a PHP script (index.php), which runs a shell script (foo.sh), which creates a folder in my home directory, but the directory was not created.

These are the original two files:

foo.sh:

#!bin/bash

mkdir /home/lorenzo/testDir

index.php:

<?php

exec('sh test.sh');

?>

So, I thought maybe the problem occurs because of privileges or something, and indeed after I changed the files to that:

foo.sh:

#!bin/bash

echo "Hello world"

index.php:

<?php

$temp=exec('sh test.sh');
echo $temp;

?>

I saw the output Hello World on my website.

So the PHP script is executed and it runs the shell script. But why can't the shell script execute the mkdir command?

This indeed is most likely a permission issue.

You first have to figure out which user apache runs at. This is usually www-data (on Debian-ish Linuxes, such as Ubuntu) or apache (on RedHat-ish Linuxes) or something along the lines. A ps -eF | grep apache ps -eF | grep apache will reveal the user.

After you figured that out, make sure that the apache user has the appropriate rights in your home directory. You can either add it to your user group (using usermod -a -G ... and then chmod g+w ~ ) or allow writing for all users ( chmod o+w ~ ).

But , both of this is a bad idea. Your php script (or anything else running as the apache user) can be broken into and cracked, leaving you home directory open for malicious attackers to modify and rm -rf .

In addition, if you're running a RedHat-ish Linux, you will run into SELinux which by defaut prevents apache from accessing user directories at all. In that case, you also have to set setsebool -P httpd_enable_homedirs on .

Instead , I would recommend that you use a different directory and give your user full access to that. Something along the lines of /var/www/testDir with the apache as owner and group, and adding yourself to the apache user group is probably a sane idea.

It looks like a permission issue. Make sure that Apache has write permission to that directory

You may have permission issues on the server. Try to use chmod -R 775 <dirname>(or 777) in your ssh command line. You can do this in php code with chmod() too but I don't suggest you because it would run it everytime the php code runs and changing it more times is pointless. It can output to the screen but I bet the directory the script wants to make file has permission 755. Try to check it.

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